id
stringlengths 33
37
| content
stringlengths 47
206k
|
|---|---|
api-misuse-repair-complete_data_1
|
@Override public void processJSONResponse(JSONObject synchronizationResponse) { JSONArray results; long maxCallId = 0; try { results = synchronizationResponse.getJSONArray("results"); for (int i = 0; i < results.length(); i++) { if (results.getJSONObject(i).getBoolean("status")) { maxCallId = results.getJSONObject(i).getLong("id"); } } this.logLastId(maxCallId); } catch (JSONException e) { e.printStackTrace(); } }
@Override public void processJSONResponse(JSONObject synchronizationResponse) { JSONArray results; long maxCallId = this.getMaxId(); try { results = synchronizationResponse.getJSONArray("results"); for (int i = 0; i < results.length(); i++) { if (results.getJSONObject(i).getBoolean("status")) { maxCallId = Math.max(results.getJSONObject(i).getLong("id"), maxCallId); } } this.logLastId(maxCallId); } catch (JSONException e) { e.printStackTrace(); } }
|
api-misuse-repair-complete_data_2
|
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window window = getWindow(); prepareForApp(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.setStatusBarColor(GetAppColor.getInstance().getAppColor(this)); window.setNavigationBarColor(GetAppColor.getInstance().getAppColor(this)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } setContentView(R.layout.main); context = this; setVolumeControlStream(AudioManager.STREAM_MUSIC); initBroadcast(); initWidget(); setListener(); includeFragment(); showWhatsNew(); drawerLayout.postDelayed(new Runnable() { public void run() { checkForUpdate(); } }, 10000); if (!TextUtils.isEmpty(getIntent().getStringExtra("pushIntent"))) { drawerLayout.postDelayed(new Runnable() { @Override public void run() { ((MainFragment) (getSupportFragmentManager().getFragments().get(0))).setShowItem(2); } }, 300); } ((MusicApplication) getApplication()).pushActivity(this); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window window = getWindow(); prepareForApp(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.setStatusBarColor(GetAppColor.getInstance().getAppColor(this)); window.setNavigationBarColor(GetAppColor.getInstance().getAppColor(this)); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } setContentView(R.layout.main); context = this; setVolumeControlStream(AudioManager.STREAM_MUSIC); initBroadcast(); initWidget(); setListener(); includeFragment(); showWhatsNew(); drawerLayout.postDelayed(new Runnable() { public void run() { checkForUpdate(); } }, 10000); if (!TextUtils.isEmpty(getIntent().getStringExtra("pushIntent"))) { drawerLayout.postDelayed(new Runnable() { @Override public void run() { ((MainFragment) (getSupportFragmentManager().getFragments().get(1))).setShowItem(2); } }, 200); } ((MusicApplication) getApplication()).pushActivity(this); }
|
api-misuse-repair-complete_data_3
|
public final Answer getData() { Answer result = null; try { HttpClient client = new DefaultHttpClient(); HttpRequestBase request = this.getRequest(); String address = config.getAddress(); address = address.concat(address.charAt(address.length() - 1) == '/' ? SUFFIX + this.CMD : "/api/v1/" + this.CMD); request.setURI(new URI(address)); request.addHeader("x-api-key", config.getApi()); request.addHeader("x-api-user", config.getUser()); request.addHeader("Accept-Encoding", "gzip"); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != 200) { if (response.getStatusLine().getStatusCode() == 504) { throw new WebServiceException("The server is experiencing issues. Please either wait or change server."); } System.out.println(response.getStatusLine().getStatusCode() + "-" + response.getStatusLine().getReasonPhrase()); } HttpEntity httpEntity = response.getEntity(); InputStream is = httpEntity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { is = new GZIPInputStream(is); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); String jsonstr = sb.toString(); System.out.println(jsonstr); JSONObject jsonObj = new JSONObject(jsonstr); result = findAnswer(jsonObj); } catch (UnsupportedEncodingException e) { this.callback.onError("There was an error with the Encoding. Check the server's address"); e.printStackTrace(); } catch (ClientProtocolException e) { this.callback.onError("There was an error with the client protocol?!"); e.printStackTrace(); } catch (UnknownHostException e) { this.callback.onError("No address associated with hostname. Please check your connection and your host settings"); e.printStackTrace(); } catch (IOException e) { this.callback.onError("An error happened... Are you still connected to the internet?"); e.printStackTrace(); } catch (WebServiceException e) { this.callback.onError(e.getMessage()); e.printStackTrace(); } catch (JSONException e) { this.callback.onError("The server returned an unexpected answer. It might be due to a server maintenance, but please check your settings"); e.printStackTrace(); } catch (URISyntaxException e) { this.callback.onError("The server's URL isn't well formatted. Please check your settings"); e.printStackTrace(); } catch (Exception e) { this.callback.onError("An unknown error happend... Please check your settings."); e.printStackTrace(); } return result; }
public final Answer getData() { Answer result = null; try { HttpClient client = new DefaultHttpClient(); HttpRequestBase request = this.getRequest(); String address = config.getAddress(); address = address.concat(address.charAt(address.length() - 1) == '/' ? SUFFIX + this.CMD : "/api/v1/" + this.CMD); request.setURI(new URI(address)); request.addHeader("x-api-key", config.getApi()); request.addHeader("x-api-user", config.getUser()); request.addHeader("Accept-Encoding", "gzip"); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != 200) { if (response.getStatusLine().getStatusCode() == 504) { throw new WebServiceException("The server is experiencing issues. Please either wait or change server."); } else if (response.getStatusLine().getStatusCode() == 401) { throw new WebServiceException("There was a problem with the authentication. Please check your settings."); } System.out.println(response.getStatusLine().getStatusCode() + "-" + response.getStatusLine().getReasonPhrase()); } HttpEntity httpEntity = response.getEntity(); InputStream is = httpEntity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { is = new GZIPInputStream(is); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); String jsonstr = sb.toString(); System.out.println(jsonstr); JSONObject jsonObj = new JSONObject(jsonstr); result = findAnswer(jsonObj); } catch (UnsupportedEncodingException e) { this.callback.onError("There was an error with the Encoding. Please check the server's address"); e.printStackTrace(); } catch (ClientProtocolException e) { this.callback.onError("There was an error with the client protocol?!"); e.printStackTrace(); } catch (UnknownHostException e) { this.callback.onError("No address associated with hostname. Please check your connection and your host settings"); e.printStackTrace(); } catch (IOException e) { this.callback.onError("An error happened... Are you still connected to the internet?"); e.printStackTrace(); } catch (WebServiceException e) { this.callback.onError(e.getMessage()); e.printStackTrace(); } catch (JSONException e) { this.callback.onError("The server returned an unexpected answer. Feel free to change server in the settings"); e.printStackTrace(); } catch (URISyntaxException e) { this.callback.onError("The server's URL isn't well formatted. Please check the server address in the settings"); e.printStackTrace(); } catch (Exception e) { this.callback.onError("An unknown error happend... Maybe because of your connection, or of your settings?"); e.printStackTrace(); } return result; }
|
api-misuse-repair-complete_data_4
|
public boolean addStudent(Student s) { int spot = this.getEmptySpot(); if (spot != -1) { students[spot] = s.getId(); currentEnrollment++; return true; } return false; }
public boolean addStudent(Student s) { int spot = this.getEmptySpot(); if (spot != -1) { students[spot] = s.getID(); currentEnrollment++; return true; } return false; }
|
api-misuse-repair-complete_data_5
|
@Override public boolean next() throws SQLException { if (maxRows > 0) { if (currentRow >= maxRows) { return false; } } currentRow++; if (resultCursorPreIterated) { resultCursorPreIterated = false; return !resultCursor.atEnd(); } else { return resultCursor.next(); } }
@Override public boolean next() throws SQLException { if (maxRows > 0) { if (resultCursor.position() >= maxRows) { return false; } } if (resultCursorPreIterated) { resultCursorPreIterated = false; return resultCursor.hasRecord(); } else { return resultCursor.next(); } }
|
api-misuse-repair-complete_data_6
|
private void createDataList(PixelMap map) throws BrokenImage { this.map = map; mas = map.getPixels(); changeImage(); tess4J.processImage(xLine, yLine, map, img, dirName); Pixel zeroPixel = tess4J.getZeroPixel(); List<Pixel> pixelTimeList = new ArrayList<>(); for (int i = yLine; i < map.getWidth() - 10; ++i) { boolean ok = false; for (int k = 1; k < 4; ++k) if (mas[xLine + k][i].equals(mas[xLine][i], 50)) { ok = true; break; } if (ok) pixelTimeList.add(mas[xLine][i]); } if (pixelTimeList.size() < 72) throw new BrokenImage("Не найдены все значения оси X, найдено " + pixelTimeList.size() + " из 72"); int hour = 0; int dataCount = 0; for (Pixel px : pixelTimeList) { int x = px.getX(); for (int y = zeroPixel.getY() - 1; y > 0; --y) if (mas[y][x].equals(bl, 150)) { dataList.addLast(new Pair<>((hour++) % 24, Double.parseDouble(String.format("%.4f", tess4J.getValue(mas[y][x], dirName)).replace(",", ".")))); dataCount += 1; break; } } if (dataCount < 72) System.out.println("Warning: Не найдены все 72 точек(за 3 дня), возможно график обрезан или неправильный"); System.out.println("Найдено точек: " + dataCount); }
private void createDataList(PixelMap map) throws BrokenImage { this.map = map; mas = map.getPixels(); changeImage(); tess4J.processImage(xLine, yLine, map, img, dirName); Pixel zeroPixel = tess4J.getZeroPixel(); List<Pixel> pixelTimeList = new ArrayList<>(); for (int i = yLine; i < map.getWidth() - 10; ++i) { boolean ok = false; for (int k = 1; k < 4; ++k) if (mas[xLine + k][i].equals(mas[xLine][i], 50)) { ok = true; break; } if (ok) pixelTimeList.add(mas[xLine][i]); } int hour = 0; int dataCount = 0; for (Pixel px : pixelTimeList) { int x = px.getX(); for (int y = zeroPixel.getY() - 1; y > 0; --y) if (mas[y][x].equals(bl, 150)) { dataList.addLast(new Pair<>((hour++) % 24, Double.parseDouble(String.format("%.4f", tess4J.getValue(mas[y][x], dirName)).replace(",", ".")))); dataCount += 1; break; } } if (dataCount < 24) System.out.println("Warning: Не найдены все 24 точек, возможно график обрезан или неправильный"); System.out.println("Найдено точек: " + dataCount); }
|
api-misuse-repair-complete_data_7
|
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_annotation_animated_marker); mapView = (MapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { final Marker marker = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(64.900932, -18.167040))); Toast.makeText(AnimatedMarkerActivity.this, getString(R.string.tap_on_map_instruction), Toast.LENGTH_LONG).show(); mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() { @Override public void onMapClick(@NonNull LatLng point) { ValueAnimator markerAnimator = ObjectAnimator.ofObject(marker, "position", new LatLngEvaluator(), marker.getPosition(), point); markerAnimator.setDuration(2000); markerAnimator.start(); } }); } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Mapbox.getInstance(this, getString(R.string.access_token)); setContentView(R.layout.activity_annotation_animated_marker); mapView = (MapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { final Marker marker = mapboxMap.addMarker(new MarkerViewOptions().position(new LatLng(64.900932, -18.167040))); Toast.makeText(AnimatedMarkerActivity.this, getString(R.string.tap_on_map_instruction), Toast.LENGTH_LONG).show(); mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() { @Override public void onMapClick(@NonNull LatLng point) { ValueAnimator markerAnimator = ObjectAnimator.ofObject(marker, "position", new LatLngEvaluator(), marker.getPosition(), point); markerAnimator.setDuration(2000); markerAnimator.start(); } }); } }); }
|
api-misuse-repair-complete_data_8
|
@Override public void preStart() { cluster.subscribe(getSelf(), MemberUp.class); context().system().actorOf(ClusterSingletonManager.props(Props.create(VideoStorageCoordinator.class), new PoisonPill(), settings), "video-storage-coordinator"); context().system().actorOf(ClusterSingletonProxy.props("/user/video-storage-coordinator", proxySettings), "video-storage-coordinator-proxy"); }
@Override public void preStart() { cluster.subscribe(getSelf(), MemberUp.class); context().system().actorOf(ClusterSingletonManager.props(Props.create(VideoStorageCoordinator.class), new End(), settings), "video-storage-coordinator"); context().system().actorOf(ClusterSingletonProxy.props("/user/video-storage-coordinator", proxySettings), "video-storage-coordinator-proxy"); }
|
api-misuse-repair-complete_data_9
|
@Override public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { final String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_group, null); } TextView lblListHeader = (TextView) convertView.findViewById(R.id.trackName); lblListHeader.setText(headerTitle); ImageButton imgBtnMap = (ImageButton) convertView.findViewById(R.id.imgBtnMap); ImageButton imgBtnDelete = (ImageButton) convertView.findViewById(R.id.imgBtnDelete); imgBtnMap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Track track = getHelper().getTrackByName(headerTitle); if (track.getLocations().size() > 0) { Intent intent = new Intent(context, MapsActivity.class); intent.putExtra("trackName", headerTitle); context.startActivity(intent); } else MainActivity.createAlertDialog(context, R.string.alert_empty_track_title, R.string.alert_empty_track_message); } catch (SQLException e) { e.printStackTrace(); } } }); imgBtnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.delete_confirm_title).setMessage(R.string.delete_confirm_message); builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (!Objects.equals(MainActivity.getLocationName(), headerTitle)) { try { trackHeaders.remove(headerTitle); getHelper().deleteTrackByName(headerTitle); long countOfTracks = trackDao.countOf(); if (countOfTracks == 0) { Toast.makeText(context, R.string.alert_empty_list_title, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, MainActivity.class); context.startActivity(intent); } else notifyDataSetChanged(); } catch (SQLException e) { e.printStackTrace(); } } else MainActivity.createAlertDialog(context, R.string.delete_error_title, R.string.delete_error_message); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dialog = builder.create(); dialog.show(); } }); return convertView; }
@Override public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { final String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_group, null); } TextView lblListHeader = (TextView) convertView.findViewById(R.id.trackName); lblListHeader.setText(headerTitle); ImageButton imgBtnMap = (ImageButton) convertView.findViewById(R.id.imgBtnMap); ImageButton imgBtnDelete = (ImageButton) convertView.findViewById(R.id.imgBtnDelete); imgBtnMap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Track track = getHelper().getTrackByName(headerTitle); if (track.getLocations().size() > 0) { Intent intent = new Intent(context, MapsActivity.class); intent.putExtra("trackName", headerTitle); context.startActivity(intent); } else MainActivity.createAlertDialog(context, R.string.alert_empty_track_title, R.string.alert_empty_track_message); } catch (SQLException e) { e.printStackTrace(); } } }); imgBtnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.delete_confirm_title).setMessage(R.string.delete_confirm_message); builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (!Objects.equals(MainActivity.getLocationName(), headerTitle)) { try { trackHeaders.remove(headerTitle); getHelper().deleteTrackByName(headerTitle); long countOfTracks = trackDao.countOf(); if (countOfTracks == 0) { Toast.makeText(context, R.string.alert_empty_list_title, Toast.LENGTH_SHORT).show(); ((Activity) context).finish(); } else notifyDataSetChanged(); } catch (SQLException e) { e.printStackTrace(); } } else MainActivity.createAlertDialog(context, R.string.delete_error_title, R.string.delete_error_message); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dialog = builder.create(); dialog.show(); } }); return convertView; }
|
api-misuse-repair-complete_data_10
|
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_response); Intent intent = getIntent(); String message = intent.getStringExtra(SubmitListener.EXTRA_MESSAGE); result = (TextView) findViewById(R.id.result); result.setText(message); returnButton = (Button) findViewById(R.id.search); returnButton.setOnClickListener(new BackButtonListener(this)); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_response); Intent intent = getIntent(); String message = intent.getStringExtra(SubmitListener.MESSAGE_ADDR); result = (TextView) findViewById(R.id.result); result.setText(message); returnButton = (Button) findViewById(R.id.search); returnButton.setOnClickListener(new BackButtonListener(this)); }
|
api-misuse-repair-complete_data_11
|
public void checkInOutStudents(boolean in) { String inOrOut = "out"; if (in) inOrOut = "in"; Calendar cal = Calendar.getInstance(); ListView lv = (ListView) findViewById(R.id.student_list); SparseBooleanArray checked = lv.getCheckedItemPositions(); long time = cal.getTimeInMillis(); int countSuccessful = 0; for (int i = 0; i < lv.getCount(); i++) { Log.d("value,i ", checked.get(i) + ", " + i); if (checked.get(i)) { Student student = (Student) lv.getItemAtPosition(i); Log.d("selected student", i + " " + lv.getCount() + ""); Checkin checkin = checkinData.getOrCreate(CURRENT_SESSION_ID, currentActivityID, student.getID()); if (checkin.getInTime() <= 0 && in) { checkin.setInTime(time); checkin.setLastChangeTime(time); checkinData.save(checkin); countSuccessful++; } else if (checkin.getOutTime() <= 0 && checkin.getInTime() >= 0 && !in) { checkin.setOutTime(time); checkin.setLastChangeTime(time); checkinData.save(checkin); countSuccessful++; } } } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Toast.makeText(getApplicationContext(), "Checked " + inOrOut + " " + countSuccessful + " student(s) at " + dateFormat.format(time), Toast.LENGTH_LONG).show(); reloadList(); }
public void checkInOutStudents(boolean in) { String inOrOut = "out"; if (in) inOrOut = "in"; Calendar cal = Calendar.getInstance(); ListView lv = (ListView) findViewById(R.id.student_list); SparseBooleanArray checked = lv.getCheckedItemPositions(); long time = cal.getTimeInMillis(); int countSuccessful = 0; for (int i = 0; i < lv.getCount(); i++) { Log.d("value,i ", checked.get(i) + ", " + i); if (checked.get(i)) { Student student = (Student) lv.getItemAtPosition(i); Log.d("selected student", i + " " + lv.getCount() + ""); Checkin checkin = checkinData.getOrCreate(CURRENT_SESSION_ID, currentActivityID, student.getID()); if (checkin.getInTime() <= 0 && in) { checkin.setInTime(time); checkin.setLastChangeTime(time); checkinData.save(checkin); countSuccessful++; } else if (checkin.getOutTime() <= 0 && checkin.getInTime() > 0 && !in) { checkin.setOutTime(time); checkin.setLastChangeTime(time); checkinData.save(checkin); countSuccessful++; } } } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Toast.makeText(getApplicationContext(), "Checked " + inOrOut + " " + countSuccessful + " student(s) at " + dateFormat.format(time), Toast.LENGTH_LONG).show(); reloadList(); }
|
api-misuse-repair-complete_data_12
|
public static void main(String[] args) { String ipDir = args[0]; String indexDir = args[1]; File ipDirectory = new File(ipDir); String[] catDirectories = ipDirectory.list(); String[] files; File dir; Document d = null; IndexWriter writer = new IndexWriter(indexDir); try { for (String cat : catDirectories) { dir = new File(cat); files = dir.list(); for (String f : files) { try { d = Parser.parse(f); writer.addDocument(d); } catch (ParserException e) { e.printStackTrace(); } } } writer.close(); } catch (IndexerException e) { e.printStackTrace(); } }
public static void main(String[] args) { String ipDir = "/Users/nicarus/Downloads/reuters_corpus-90_cat/training"; String indexDir = null; File ipDirectory = new File(ipDir); String[] catDirectories = ipDirectory.list(); String[] files; File dir; Document d = null; IndexWriter writer = new IndexWriter(indexDir); try { for (String cat : catDirectories) { dir = new File(ipDir + File.separator + cat); files = dir.list(); if (files == null) continue; for (String f : files) { try { d = Parser.parse(dir.getAbsolutePath() + File.separator + f); writer.addDocument(d); } catch (ParserException e) { e.printStackTrace(); } } } writer.close(); } catch (IndexerException e) { e.printStackTrace(); } }
|
api-misuse-repair-complete_data_13
|
public static String getStringFromGrammarStringLiteral(String literal) { StringBuilder buf = new StringBuilder(); int i = 1; int n = literal.length() - 1; while (i < n) { int end = i + 1; if (literal.charAt(i) == '\\') { end = i + 2; if (i + 1 < n && literal.charAt(i + 1) == 'u') { if (i + 2 < n && literal.charAt(i + 2) == '{') { end = i + 3; while (true) { if (end + 1 > n) return null; char charAt = literal.charAt(end++); if (charAt == '}') { break; } if (!Character.isDigit(charAt) && !(charAt >= 'a' && charAt <= 'f') && !(charAt >= 'A' && charAt <= 'F')) { return null; } } } else { for (end = i + 2; end < i + 6; end++) { if (end > n) return null; char charAt = literal.charAt(end); if (!Character.isDigit(charAt) && !(charAt >= 'a' && charAt <= 'f') && !(charAt >= 'A' && charAt <= 'F')) { return null; } } } } } if (end > n) return null; String esc = literal.substring(i, end); int c = getCharValueFromCharInGrammarLiteral(esc); if (c == -1) { return null; } else buf.append((char) c); i = end; } return buf.toString(); }
public static String getStringFromGrammarStringLiteral(String literal) { StringBuilder buf = new StringBuilder(); int i = 1; int n = literal.length() - 1; while (i < n) { int end = i + 1; if (literal.charAt(i) == '\\') { end = i + 2; if (i + 1 < n && literal.charAt(i + 1) == 'u') { if (i + 2 < n && literal.charAt(i + 2) == '{') { end = i + 3; while (true) { if (end + 1 > n) return null; char charAt = literal.charAt(end++); if (charAt == '}') { break; } if (!Character.isDigit(charAt) && !(charAt >= 'a' && charAt <= 'f') && !(charAt >= 'A' && charAt <= 'F')) { return null; } } } else { for (end = i + 2; end < i + 6; end++) { if (end > n) return null; char charAt = literal.charAt(end); if (!Character.isDigit(charAt) && !(charAt >= 'a' && charAt <= 'f') && !(charAt >= 'A' && charAt <= 'F')) { return null; } } } } } if (end > n) return null; String esc = literal.substring(i, end); int c = getCharValueFromCharInGrammarLiteral(esc); if (c == -1) { return null; } else buf.appendCodePoint(c); i = end; } return buf.toString(); }
|
api-misuse-repair-complete_data_14
|
@RequestMapping("/show") public String show(Model model, HttpServletRequest request) throws ParseException { request.getSession().setAttribute(Constants.SEESION_LINK, "schedule_show"); String beginDate = request.getParameter("beginDate"); String endDate = request.getParameter("endDate"); if (CommonUtils.isEmpty(beginDate)) { beginDate = DateUtils.getMondayOfWeek(); } if (CommonUtils.isEmpty(endDate)) { endDate = DateUtils.getCurrentWeekday(); } List<DateArray> dateArray = DateUtils.dateArray(beginDate, endDate); Map<String, Map<Integer, Map<String, List<Schedule>>>> map = scheduleService.getSchedule(beginDate, endDate); model.addAttribute("beginDate", beginDate); model.addAttribute("endDate", endDate); model.addAttribute("dateArray", dateArray); model.addAttribute("map", map); return "schedule/show"; }
@RequestMapping("/show") public String show(Model model, HttpServletRequest request) throws ParseException { request.getSession().setAttribute(Constants.SEESION_LINK, "schedule_show"); String beginDate = request.getParameter("beginDate"); String endDate = request.getParameter("endDate"); if (CommonUtils.isEmpty(beginDate)) { beginDate = DateUtils.getMondayOfWeek(); } if (CommonUtils.isEmpty(endDate)) { endDate = DateUtils.getCurrentWeekday(); } User user = (User) request.getSession().getAttribute(Constants.SEESION_USER); List<DateArray> dateArray = DateUtils.dateArray(beginDate, endDate); Map<String, Map<Integer, Map<String, List<Schedule>>>> map = scheduleService.getSchedule(beginDate, endDate, user); model.addAttribute("beginDate", beginDate); model.addAttribute("endDate", endDate); model.addAttribute("dateArray", dateArray); model.addAttribute("map", map); return "schedule/show"; }
|
api-misuse-repair-complete_data_15
|
@Override protected HashMap<String, String> doInBackground(String... arg0) { JSONParser json = new JSONParser(); try { String jsonData = json.getJSONFromUrl("http://www.smilyo.com/app/menu_item.php"); JSONObject jObj = new JSONObject(jsonData); map.put("title", jObj.getString("title")); map.put("URL", jObj.getString("URL")); } catch (JSONException e) { e.printStackTrace(); } return map; }
@Override protected HashMap<String, String> doInBackground(String... arg0) { JSONParser json = new JSONParser(); try { String jsonData = json.getJSONFromUrl(""); JSONObject jObj = new JSONObject(jsonData); map.put("title", jObj.getString("title")); map.put("URL", jObj.getString("URL")); } catch (JSONException e) { e.printStackTrace(); } return map; }
|
api-misuse-repair-complete_data_16
|
private WriteResult execute(DBObject condition) { List ids = null; if (!dao.getListenerList().isEmpty()) { ids = dao.getCollection().distinct(Operator.ID, condition); } WriteResult wr = dao.getCollection().update(condition, modifier, false, true); if (!dao.getListenerList().isEmpty() && ids != null) { DBObject in = new BasicDBObject(Operator.IN, ids); DBCursor cursor = dao.getCollection().find(new BasicDBObject(Operator.ID, in)); List<T> list = MapperUtil.toList(dao.getEntityClass(), cursor); for (T t : list) { dao.notifyUpdated((BuguEntity) t); } } return wr; }
private WriteResult execute(DBObject condition) { List ids = null; if (dao.hasUserListener) { ids = dao.getCollection().distinct(Operator.ID, condition); } WriteResult wr = dao.getCollection().update(condition, modifier, false, true); if (dao.hasUserListener && ids != null) { DBObject in = new BasicDBObject(Operator.IN, ids); DBCursor cursor = dao.getCollection().find(new BasicDBObject(Operator.ID, in)); List<T> list = MapperUtil.toList(dao.getEntityClass(), cursor); for (T t : list) { dao.notifyUpdated((BuguEntity) t); } } return wr; }
|
api-misuse-repair-complete_data_17
|
@Override public boolean isType(final NodeType checked) { return type.equals(checked); }
@Override public boolean isType(final NodeType checked) { return type == checked; }
|
api-misuse-repair-complete_data_18
|
public User find(String login) { Query query = em.createQuery("SELECT user FROM User user WHERE user.login = :login"); query.setParameter("login", login); User user = null; try { query.getSingleResult(); } catch (NullPointerException e) { } return user; }
public User find(String login) { TypedQuery<User> query = em.createQuery("SELECT user FROM User user WHERE user.login = :login", User.class); query.setParameter("login", login); User user = null; try { user = query.getSingleResult(); } catch (NoResultException e) { return user; } return user; }
|
api-misuse-repair-complete_data_19
|
public static void main(String[] args) { int tranType = 0; double accBal = 0, amount = 0, finalBal = 0; String output = ""; accBal = Double.parseDouble(JOptionPane.showInputDialog("Current Account Balance: ")); tranType = Integer.parseInt(JOptionPane.showInputDialog("Choose a transaction type (0: Deposit, 1: Withdraw): ")); if (tranType == 1) { amount = Double.parseDouble(JOptionPane.showInputDialog("Withdraw Amount: ")); finalBal = accBal - amount; output = String.format("Balance before withdraw: $%.2f\nFinal Balance: $%.2f", accBal, finalBal); } else { amount = Double.parseDouble(JOptionPane.showInputDialog("Deposit Amount: ")); finalBal = accBal + amount; output = String.format("Balance before deposit: $%.2f\nFinal Balance: $%.2f", accBal, finalBal); } JOptionPane.showMessageDialog(null, output); }
public static void main(String[] args) { int tranType = 0; double accBal = 0, amount = 0, finalBal = 0; int stop = JOptionPane.YES_OPTION; String output = ""; while (stop == JOptionPane.YES_OPTION) { accBal = Double.parseDouble(JOptionPane.showInputDialog("Current Account Balance: ")); if (accBal < 500) { stop = JOptionPane.showConfirmDialog(null, "ERROR: Current Account Balance is below 500." + "\nWould you like to enter agian?"); if (stop != JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "exit program"); System.exit(0); } } else { stop = JOptionPane.NO_OPTION; } } stop = JOptionPane.YES_OPTION; while (stop == JOptionPane.YES_OPTION) { tranType = Integer.parseInt(JOptionPane.showInputDialog("Choose a transaction type" + " (0: Deposit, 1: Withdraw): ")); if ((tranType != 1) && (tranType != 0)) { stop = JOptionPane.showConfirmDialog(null, "Invalid Input. Would you like to enter agian?"); if (stop != JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "exit program"); System.exit(0); } } else { stop = JOptionPane.NO_OPTION; } } stop = JOptionPane.YES_OPTION; if (tranType == 1) { while (stop == JOptionPane.YES_OPTION) { amount = Double.parseDouble(JOptionPane.showInputDialog("Withdraw Amount: ")); if (amount > accBal) { stop = JOptionPane.showConfirmDialog(null, "ERROR: Withdraw amount is more than current " + "balance.\nWould you like to enter agian?"); if (stop != JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "exit program"); System.exit(0); } } else { stop = JOptionPane.NO_OPTION; } } stop = JOptionPane.YES_OPTION; finalBal = accBal - amount; output = String.format("Balance before withdraw: $%.2f\nFinal Balance: $%.2f", accBal, finalBal); } else if (tranType == 0) { while (stop == JOptionPane.YES_OPTION) { amount = Double.parseDouble(JOptionPane.showInputDialog("Deposit Amount: ")); if (amount < 50) { stop = JOptionPane.showConfirmDialog(null, "ERROR: Minimum deposit amount is not met. " + "\nWould you like to enter agian?"); if (stop != JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "exit program"); System.exit(0); } } else { stop = JOptionPane.NO_OPTION; } } stop = JOptionPane.YES_OPTION; finalBal = accBal + amount; output = String.format("Balance before deposit: $%.2f\nFinal Balance: $%.2f", accBal, finalBal); } JOptionPane.showMessageDialog(null, output); }
|
api-misuse-repair-complete_data_20
|
@Override public void configure(HttpSecurity http) throws Exception { http.formLogin().loginPage("/login").and().logout().logoutSuccessUrl("/").and().authorizeRequests().mvcMatchers("/brouwers/toevoegen").hasAuthority(ADMINISTRATOR).mvcMatchers("/brouwers/brouwers", "/brouwers/beginnaam", "/brouwers/opalfabet").hasAnyAuthority(ADMINISTRATOR, USER).mvcMatchers("/", "/login").permitAll().and().exceptionHandling().accessDeniedPage("/WEB-INF/JSP/forbidden.jsp"); http.httpBasic(); }
@Override public void configure(HttpSecurity http) throws Exception { http.formLogin().loginPage("/login").and().logout().logoutSuccessUrl("/").and().authorizeRequests().mvcMatchers("/brouwers/toevoegen").hasAuthority(ADMINISTRATOR).mvcMatchers("/brouwers", "/brouwers/beginnaam", "/brouwers/opalfabet").hasAnyAuthority(ADMINISTRATOR, USER).mvcMatchers("/", "/login").permitAll().and().exceptionHandling().accessDeniedPage("/WEB-INF/JSP/forbidden.jsp"); http.httpBasic(); }
|
api-misuse-repair-complete_data_21
|
@Override public void setDataEncoding(DataEncoding dataEncoding) { super.setDataEncoding(dataEncoding); writer.setDataEncoding(dataEncoding); }
@Override public void setDataEncoding(DataEncoding dataEncoding) { writer.setDataEncoding(dataEncoding); super.dataEncoding = writer.getDataEncoding(); }
|
api-misuse-repair-complete_data_22
|
void initializeAllDevices() { this.driveSystem = new MecanumDriveSystem(hardwareMap, telemetry); this.imuSystem = new IMUSystem(this.hardwareMap, telemetry); this.lineFollowingSystem = new LineFollowingSystem(); }
void initializeAllDevices() { this.driveSystem = new MecanumDriveSystem(this); this.imuSystem = new IMUSystem(this); this.lineFollowingSystem = new LineFollowingSystem(); }
|
api-misuse-repair-complete_data_23
|
public static void main(String[] args) { JFrame frame = new JFrame("Survive"); frame.setVisible(true); frame.setSize(1920, 1080); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); hero CurrentUser = new hero(); ArrayList<Button> Buttons = new ArrayList<Button>(); Buttons.add(new Button(1800, 20, 50, 30, "pause", true, true)); Buttons.add(new Button(150, 250, 250, 75, "wooden axe", false, true)); Buttons.add(new Button(150, 350, 250, 75, "stone axe", false, true)); Buttons.add(new Button(425, 250, 250, 70, "thatch hut", false, true)); display window = new display(CurrentUser, Buttons); frame.add(window); window.setView("world"); ArrayList<element> worldParts = new ArrayList<element>(); int rand = (int) (Math.random() * 200); int randX; int randY; for (int i = 0; i < rand; i++) { randX = (int) (Math.random() * 4900); randY = (int) (Math.random() * 4900); worldParts.add(new element(randX, randY, 100, 100, ("tree"), 21, 105, 0, 100)); } rand = (int) (Math.random() * 100); for (int i = 0; i < rand; i++) { randX = (int) (Math.random() * 2900); randY = (int) (Math.random() * 2900); worldParts.add(new element(randX, randY, 100, 100, ("rock"), 122, 122, 122, 200)); } worldParts.add(new element(0, 0, 3000, 1, "wall", 0, 0, 0, 100)); worldParts.add(new element(0, 3000, 3000, 1, "wall", 0, 0, 0, 100)); worldParts.add(new element(0, 0, 1, 3000, "wall", 0, 0, 0, 100)); worldParts.add(new element(3000, 0, 1, 3000, "wall", 0, 0, 0, 100)); window.setElements(worldParts); int currentX = 0; int currentY = 0; keyboard listener = new keyboard(window, currentX, currentY); frame.addKeyListener(listener); mouse mouseListener = new mouse(window, Buttons); frame.addMouseListener(mouseListener); }
public static void main(String[] args) { JFrame frame = new JFrame("Survive"); frame.setVisible(true); frame.setSize(1920, 1080); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); hero CurrentUser = new hero(); ArrayList<Button> Buttons = new ArrayList<Button>(); Buttons.add(new Button(1800, 20, 50, 30, "pause", true, true)); Buttons.add(new Button(150, 250, 250, 75, "wooden axe", false, true)); Buttons.add(new Button(150, 350, 250, 75, "stone axe", false, true)); Buttons.add(new Button(425, 250, 250, 70, "thatch hut", false, true)); display window = new display(CurrentUser, Buttons); frame.add(window); window.setView("world"); ArrayList<element> worldParts = new ArrayList<element>(); int rand = (int) (Math.random() * 200); int randX; int randY; for (int i = 0; i < rand; i++) { randX = (int) (Math.random() * 4900); randY = (int) (Math.random() * 4900); worldParts.add(new element(randX, randY, 100, 100, ("tree"), 21, 105, 0, 100)); } rand = (int) (Math.random() * 100); for (int i = 0; i < rand; i++) { randX = (int) (Math.random() * 4900); randY = (int) (Math.random() * 4900); worldParts.add(new element(randX, randY, 100, 100, ("rock"), 122, 122, 122, 200)); } worldParts.add(new element(0, 0, 5000, 1, "wall", 0, 0, 0, 100)); worldParts.add(new element(0, 5000, 5000, 1, "wall", 0, 0, 0, 100)); worldParts.add(new element(0, 0, 1, 5000, "wall", 0, 0, 0, 100)); worldParts.add(new element(5000, 0, 1, 3000, "wall", 0, 0, 0, 100)); window.setElements(worldParts); int currentX = 0; int currentY = 0; keyboard listener = new keyboard(window, currentX, currentY); frame.addKeyListener(listener); mouse mouseListener = new mouse(window, Buttons); frame.addMouseListener(mouseListener); }
|
api-misuse-repair-complete_data_24
|
private WorkDuration subtractNeverNegative(WorkDuration workDuration, WorkDuration toSubtractWith) { WorkDuration result = workDuration.subtract(toSubtractWith); if (result.toSeconds() > 0) { return result; } return workDurationFactory.createFromWorkingLong(0L); }
@CheckForNull private WorkDuration subtractNeverNegative(@Nullable WorkDuration workDuration, WorkDuration toSubtractWith) { if (workDuration != null) { WorkDuration result = workDuration.subtract(toSubtractWith); if (result.toSeconds() > 0) { return result; } } return null; }
|
api-misuse-repair-complete_data_25
|
public void startServer(IConfig config, List<? extends InterceptHandler> handlers, ISslContextCreator sslCtxCreator) throws IOException { if (handlers == null) { handlers = Collections.emptyList(); } final String handlerProp = System.getProperty("intercept.handler"); if (handlerProp != null) { config.setProperty("intercept.handler", handlerProp); } LOG.info("Persistent store file: " + config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME)); final ProtocolProcessor processor = SimpleMessaging.getInstance().init(config, handlers); if (sslCtxCreator == null) { sslCtxCreator = new DefaultMoquetteSslContextCreator(config); } m_acceptor = new NettyAcceptor(); m_acceptor.initialize(processor, config, sslCtxCreator); m_processor = processor; m_initialized = true; }
public void startServer(IConfig config, List<? extends InterceptHandler> handlers, ISslContextCreator sslCtxCreator, IAuthenticator authenticator, IAuthorizator authorizator) throws IOException { if (handlers == null) { handlers = Collections.emptyList(); } final String handlerProp = System.getProperty("intercept.handler"); if (handlerProp != null) { config.setProperty("intercept.handler", handlerProp); } LOG.info("Persistent store file: " + config.getProperty(BrokerConstants.PERSISTENT_STORE_PROPERTY_NAME)); final ProtocolProcessor processor = SimpleMessaging.getInstance().init(config, handlers, authenticator, authorizator); if (sslCtxCreator == null) { sslCtxCreator = new DefaultMoquetteSslContextCreator(config); } m_acceptor = new NettyAcceptor(); m_acceptor.initialize(processor, config, sslCtxCreator); m_processor = processor; m_initialized = true; }
|
api-misuse-repair-complete_data_26
|
private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); }
private void setupActionBar() { getSupportActionBar().setDisplayHomeAsUpEnabled(true); }
|
api-misuse-repair-complete_data_27
|
private void updateCachedIssue(Issue issue) { TurboIssue newCached = new TurboIssue(issue); int index = getIndexOfIssue(issue.getNumber()); if (index != -1) { issues.set(index, newCached); } else { issues.add(0, newCached); } }
private void updateCachedIssue(Issue issue) { TurboIssue newCached = new TurboIssue(issue); int index = getIndexOfIssue(issue.getNumber()); if (index != -1) { updateIssueAtIndex(index, newCached); } else { issues.add(0, newCached); } }
|
api-misuse-repair-complete_data_28
|
@Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { Content c = this.getContent(); String resultStr = offs > 0 ? c.getString(0, c.length() - 1) + str : str + c.getString(0, c.length() - 1); if (format(resultStr)) { super.insertString(offs, str, a); } }
@Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { Content c = this.getContent(); StringBuilder stringBuilder = new StringBuilder(c.getString(0, c.length() - 1)); String resultStr = stringBuilder.insert(offs, str).toString(); if (format(resultStr)) { super.insertString(offs, str, a); } }
|
api-misuse-repair-complete_data_29
|
@Override public Node parse(final TokenStream tokenStream) { if (tokenStream.hasOneOf(FIRST_SET)) { final Token separator = tokenStream.next(); return this.getGrammar().getSyntaxTreeFactory().createSentenceMeatConjunction(separator.getConcept()); } return this.parsingTrouble(tokenStream); }
@Override public Node parse(final TokenStream tokenStream) { if (tokenStream.hasOneOf(FIRST_SET)) { final Token infix = tokenStream.next(); return this.getGrammar().getSyntaxTreeFactory().createSentenceMeatConjunction(infix.getConcept()); } return this.parsingTrouble(tokenStream); }
|
api-misuse-repair-complete_data_30
|
@RequestMapping("/productstore") @ResponseBody public List<SystemProduct> products(@RequestParam("bname") String bname) { Iterable<SystemProduct> Products; List<SystemProduct> products = new ArrayList<SystemProduct>(); if (bname.equals("zero")) { Products = sprepo.findAll(); for (SystemProduct p : Products) { products.add(p); } return products; } Products = sprepo.findByBrand(bname); for (SystemProduct p : Products) { products.add(p); } return products; }
@RequestMapping("/productstore") @ResponseBody public List<SystemProduct> products(@RequestParam("bname") String bname) { Iterable<SystemProduct> Products; List<SystemProduct> products = new ArrayList<SystemProduct>(); if (bname.equals("")) { Products = sprepo.findAll(); for (SystemProduct p : Products) { products.add(p); } return products; } Products = sprepo.findByBrand(bname); for (SystemProduct p : Products) { products.add(p); } return products; }
|
api-misuse-repair-complete_data_31
|
@Override public CompoundProperty addDistanceToCompoundFeature(Compound comp) { for (CompoundProperty prop : getAdditionalProperties()) { if (prop instanceof DistanceToProperty && ((DistanceToProperty) prop).getCompound() == comp) return prop; } Double[] d = new Double[getNumCompounds(true)]; for (int i = 0; i < d.length; i++) d[i] = clusteringData.getFeatureDistance(comp.getOrigIndex(), getCompounds().get(i).getOrigIndex()); DistanceToProperty dp = new DistanceToProperty(comp, clusteringData.getEmbeddingDistanceMeasure(), d); addNewAdditionalProperty(dp, null); return dp; }
@Override public CompoundProperty addDistanceToCompoundFeature(Compound comp) { for (CompoundProperty prop : getAdditionalProperties()) { if (prop instanceof DistanceToProperty && ((DistanceToProperty) prop).getCompound() == comp) return prop; } Double[] d = new Double[getNumUnfilteredCompounds(true)]; for (int i = 0; i < d.length; i++) d[i] = clusteringData.getFeatureDistance(comp.getOrigIndex(), getCompounds().get(i).getOrigIndex()); DistanceToProperty dp = new DistanceToProperty(comp, clusteringData.getEmbeddingDistanceMeasure(), d); addNewAdditionalProperty(dp, null); return dp; }
|
api-misuse-repair-complete_data_32
|
@PostMapping("/login") public ResultVO login(@RequestBody WxInfo wxInfo, HttpServletResponse response, HttpServletRequest request) { if (StringUtils.isBlank(wxInfo.getCode())) { return ResultUtil.error("empty code"); } try { WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(wxInfo.getCode()); log.info(session.getSessionKey()); log.info(session.getOpenid()); UserInfo userInfo = userService.findByOpenid(session.getOpenid()); if (userInfo == null) { WxMaUserInfo wxUserInfo = wxService.getUserService().getUserInfo(session.getSessionKey(), wxInfo.getEncryptedData(), wxInfo.getIv()); userInfo = userService.save(new UserInfo(wxUserInfo.getNickName(), wxUserInfo.getOpenId(), wxUserInfo.getAvatarUrl(), Integer.valueOf(userInfo.getUserGender()))); } UserVO userVO = new UserVO(); BeanUtils.copyProperties(userInfo, userVO); return ResultUtil.success(userVO); } catch (WxErrorException e) { log.error(e.getMessage(), e); return ResultUtil.error(e.getMessage()); } }
@PostMapping("/login") public ResultVO login(@RequestBody WxInfo wxInfo, HttpServletResponse response, HttpServletRequest request) { if (StringUtils.isBlank(wxInfo.getCode())) { return ResultUtil.error("empty code"); } try { WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(wxInfo.getCode()); log.info(session.getSessionKey()); log.info(session.getOpenid()); UserInfo userInfo = userService.findByOpenid(session.getOpenid()); if (userInfo == null) { WxMaUserInfo wxUserInfo = wxService.getUserService().getUserInfo(session.getSessionKey(), wxInfo.getEncryptedData(), wxInfo.getIv()); userInfo = userService.save(new UserInfo(wxUserInfo.getNickName(), wxUserInfo.getOpenId(), wxUserInfo.getAvatarUrl(), Integer.valueOf(wxUserInfo.getGender()))); } UserVO userVO = new UserVO(); BeanUtils.copyProperties(userInfo, userVO); return ResultUtil.success(userVO); } catch (WxErrorException e) { log.error(e.getMessage(), e); return ResultUtil.error(e.getMessage()); } }
|
api-misuse-repair-complete_data_33
|
public static void init(final boolean enableInDevelopmentFeatures, final boolean supplyChests) { GameRegistry.addRecipe(new ItemStack(ModBlocks.blockConstructionTape, 16), "SWS", "S S", "S S", 'S', Items.STICK, 'W', new ItemStack(Blocks.WOOL, 1, 4)); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.blockConstructionTapeCorner, 1), ModBlocks.blockConstructionTape); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.blockConstructionTape, 1), ModBlocks.blockConstructionTapeCorner); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutMiner, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WOODEN_PICKAXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutMiner, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.STONE_PICKAXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutLumberjack, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WOODEN_AXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutLumberjack, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.STONE_AXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.ACACIA_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.BIRCH_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.DARK_OAK_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.JUNGLE_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.OAK_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.SPRUCE_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutCitizen, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Blocks.TORCH); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutFisherman, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.FISHING_ROD); GameRegistry.addRecipe(new ItemStack(ModItems.scanTool, 1), " I", " S ", "S ", 'I', Items.IRON_INGOT, 'S', Items.STICK); GameRegistry.addRecipe(new ItemStack(ModItems.buildTool, 1), " C", " S ", "S ", 'C', Blocks.COBBLESTONE, 'S', Items.STICK); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockSubstitution, 16), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', ModItems.scanTool); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockSolidSubstitution, 16), "XXX", "X#X", "XXX", 'X', Blocks.LOG, '#', ModItems.scanTool); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutFarmer, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WOODEN_HOE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutFarmer, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.STONE_HOE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutField, 1), " Y ", "X#X", " X ", 'X', Items.STICK, '#', Items.LEATHER, 'Y', Blocks.HAY_BLOCK); GameRegistry.addRecipe(new ItemStack(Blocks.WEB, 1), "X X", " X ", "X X", 'X', Items.STRING); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutGuardTower, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.BOW); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutWareHouse, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Blocks.CHEST); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutDeliveryman, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.LEATHER_BOOTS); if (enableInDevelopmentFeatures) { GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBaker, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WHEAT); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBlacksmith, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.IRON_INGOT); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutStonemason, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Blocks.STONEBRICK); } if (supplyChests) { GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.ACACIA_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.BIRCH_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.DARK_OAK_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.JUNGLE_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.SPRUCE_BOAT); } else { GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutTownHall, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.BOAT); } }
public static void init(final boolean enableInDevelopmentFeatures, final boolean supplyChests) { GameRegistry.addRecipe(new ItemStack(ModBlocks.blockConstructionTape, 16), "SWS", "S S", "S S", 'S', Items.STICK, 'W', new ItemStack(Blocks.WOOL, 1, YELLOW_WOOL)); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.blockConstructionTapeCorner, 1), ModBlocks.blockConstructionTape); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.blockConstructionTape, 1), ModBlocks.blockConstructionTapeCorner); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutMiner, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WOODEN_PICKAXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutMiner, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.STONE_PICKAXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutLumberjack, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WOODEN_AXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutLumberjack, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.STONE_AXE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.ACACIA_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.BIRCH_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.DARK_OAK_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.JUNGLE_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.OAK_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBuilder, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.SPRUCE_DOOR); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutCitizen, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Blocks.TORCH); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutFisherman, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.FISHING_ROD); GameRegistry.addRecipe(new ItemStack(ModItems.scanTool, 1), " I", " S ", "S ", 'I', Items.IRON_INGOT, 'S', Items.STICK); GameRegistry.addRecipe(new ItemStack(ModItems.buildTool, 1), " C", " S ", "S ", 'C', Blocks.COBBLESTONE, 'S', Items.STICK); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockSubstitution, 16), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', ModItems.scanTool); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockSolidSubstitution, 16), "XXX", "X#X", "XXX", 'X', Blocks.LOG, '#', ModItems.scanTool); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutFarmer, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WOODEN_HOE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutFarmer, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.STONE_HOE); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutField, 1), " Y ", "X#X", " X ", 'X', Items.STICK, '#', Items.LEATHER, 'Y', Blocks.HAY_BLOCK); GameRegistry.addRecipe(new ItemStack(Blocks.WEB, 1), "X X", " X ", "X X", 'X', Items.STRING); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutGuardTower, 2), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.BOW); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutWareHouse, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Blocks.CHEST); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutDeliveryman, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.LEATHER_BOOTS); if (enableInDevelopmentFeatures) { GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBaker, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.WHEAT); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutBlacksmith, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.IRON_INGOT); GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutStonemason, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Blocks.STONEBRICK); } if (supplyChests) { GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.ACACIA_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.BIRCH_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.DARK_OAK_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.JUNGLE_BOAT); GameRegistry.addRecipe(new ItemStack(ModItems.supplyChest, 1), "B B", "BBB", 'B', Items.SPRUCE_BOAT); } else { GameRegistry.addRecipe(new ItemStack(ModBlocks.blockHutTownHall, 1), "XXX", "X#X", "XXX", 'X', Blocks.PLANKS, '#', Items.BOAT); } }
|
api-misuse-repair-complete_data_34
|
public void calcTangents() { for (int i = 0; i < indices.size(); i += 3) { int i0 = indices.get(i); int i1 = indices.get(i + 1); int i2 = indices.get(i + 2); Vector3f edge1 = positions.get(i1).sub(positions.get(i0)); Vector3f edge2 = positions.get(i2).sub(positions.get(i0)); float deltaU1 = texCoords.get(i1).getX() - texCoords.get(i0).getX(); float deltaV1 = texCoords.get(i1).getY() - texCoords.get(i0).getY(); float deltaU2 = texCoords.get(i2).getX() - texCoords.get(i0).getX(); float deltaV2 = texCoords.get(i2).getY() - texCoords.get(i0).getY(); float f = 1.0f / (deltaU1 * deltaV2 - deltaU2 * deltaV1); Vector3f tangent = new Vector3f(0, 0, 0); tangent.setX(f * (deltaV2 * edge1.getX() - deltaV1 * edge2.getX())); tangent.setY(f * (deltaV2 * edge1.getY() - deltaV1 * edge2.getY())); tangent.setZ(f * (deltaV2 * edge1.getZ() - deltaV1 * edge2.getZ())); tangents.get(i0).set(tangents.get(i0).add(tangent)); tangents.get(i1).set(tangents.get(i1).add(tangent)); tangents.get(i2).set(tangents.get(i2).add(tangent)); } for (int i = 0; i < tangents.size(); i++) tangents.get(i).set(tangents.get(i).normalized()); }
public void calcTangents() { for (int i = 0; i < indices.size(); i += 3) { int i0 = indices.get(i); int i1 = indices.get(i + 1); int i2 = indices.get(i + 2); Vector3f edge1 = positions.get(i1).sub(positions.get(i0)); Vector3f edge2 = positions.get(i2).sub(positions.get(i0)); float deltaU1 = texCoords.get(i1).getX() - texCoords.get(i0).getX(); float deltaV1 = texCoords.get(i1).getY() - texCoords.get(i0).getY(); float deltaU2 = texCoords.get(i2).getX() - texCoords.get(i0).getX(); float deltaV2 = texCoords.get(i2).getY() - texCoords.get(i0).getY(); float dividend = (deltaU1 * deltaV2 - deltaU2 * deltaV1); float f = dividend == 0 ? 1.0f : 1.0f / dividend; Vector3f tangent = new Vector3f(0, 0, 0); tangent.setX(f * (deltaV2 * edge1.getX() - deltaV1 * edge2.getX())); tangent.setY(f * (deltaV2 * edge1.getY() - deltaV1 * edge2.getY())); tangent.setZ(f * (deltaV2 * edge1.getZ() - deltaV1 * edge2.getZ())); tangents.get(i0).set(tangents.get(i0).add(tangent)); tangents.get(i1).set(tangents.get(i1).add(tangent)); tangents.get(i2).set(tangents.get(i2).add(tangent)); } for (int i = 0; i < tangents.size(); i++) tangents.get(i).set(tangents.get(i).normalized()); }
|
api-misuse-repair-complete_data_35
|
public static List<SourceColumn> getColumns(String source) { List<SourceColumn> columnList; SourceColumn idColumn; switch(source) { case "All": return new LinkedList<>(); case "Service": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); return columnList; case "ServiceInstance": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); SourceColumn serviceIdColumn = new SourceColumn("serviceId", "service_id", int.class, false); columnList.add(serviceIdColumn); return columnList; case "Endpoint": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); serviceIdColumn = new SourceColumn("serviceId", "service_id", int.class, false); columnList.add(serviceIdColumn); SourceColumn serviceInstanceIdColumn = new SourceColumn("serviceInstanceId", "service_instance_id", int.class, false); columnList.add(serviceInstanceIdColumn); return columnList; case "ServiceInstanceJVMCPU": case "ServiceInstanceJVMMemory": case "ServiceInstanceJVMMemoryPool": case "ServiceInstanceJVMGC": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); serviceInstanceIdColumn = new SourceColumn("serviceInstanceId", "service_instance_id", int.class, false); columnList.add(serviceInstanceIdColumn); return columnList; case "ServiceRelation": columnList = new LinkedList<>(); SourceColumn sourceService = new SourceColumn("entityId", "source_service_id", String.class, true); columnList.add(sourceService); return columnList; case "ServiceInstanceRelation": columnList = new LinkedList<>(); sourceService = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(sourceService); sourceService = new SourceColumn("sourceServiceId", "source_service_id", int.class, false); columnList.add(sourceService); SourceColumn destService = new SourceColumn("destServiceId", "destServiceId", int.class, false); columnList.add(destService); return columnList; case "EndpointRelation": columnList = new LinkedList<>(); SourceColumn sourceEndpointColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(sourceEndpointColumn); sourceService = new SourceColumn("serviceId", "service_id", int.class, false); columnList.add(sourceService); destService = new SourceColumn("childServiceId", "child_service_id", int.class, false); columnList.add(destService); SourceColumn sourceServiceInstance = new SourceColumn("serviceInstanceId", "service_instance_id", int.class, false); columnList.add(sourceServiceInstance); SourceColumn destServiceInstance = new SourceColumn("childServiceInstanceId", "child_service_instance_id", int.class, false); columnList.add(destServiceInstance); return columnList; default: throw new IllegalArgumentException("Illegal source :" + source); } }
public static List<SourceColumn> getColumns(String source) { List<SourceColumn> columnList; SourceColumn idColumn; switch(source) { case "All": return new LinkedList<>(); case "Service": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); return columnList; case "ServiceInstance": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); SourceColumn serviceIdColumn = new SourceColumn("serviceId", "service_id", int.class, false); columnList.add(serviceIdColumn); return columnList; case "Endpoint": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); serviceIdColumn = new SourceColumn("serviceId", "service_id", int.class, false); columnList.add(serviceIdColumn); SourceColumn serviceInstanceIdColumn = new SourceColumn("serviceInstanceId", "service_instance_id", int.class, false); columnList.add(serviceInstanceIdColumn); return columnList; case "ServiceInstanceJVMCPU": case "ServiceInstanceJVMMemory": case "ServiceInstanceJVMMemoryPool": case "ServiceInstanceJVMGC": columnList = new LinkedList<>(); idColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(idColumn); serviceInstanceIdColumn = new SourceColumn("serviceInstanceId", "service_instance_id", int.class, false); columnList.add(serviceInstanceIdColumn); return columnList; case "ServiceRelation": columnList = new LinkedList<>(); SourceColumn sourceService = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(sourceService); return columnList; case "ServiceInstanceRelation": columnList = new LinkedList<>(); sourceService = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(sourceService); sourceService = new SourceColumn("sourceServiceId", "source_service_id", int.class, false); columnList.add(sourceService); SourceColumn destService = new SourceColumn("destServiceId", "destServiceId", int.class, false); columnList.add(destService); return columnList; case "EndpointRelation": columnList = new LinkedList<>(); SourceColumn sourceEndpointColumn = new SourceColumn("entityId", "entity_id", String.class, true); columnList.add(sourceEndpointColumn); sourceService = new SourceColumn("serviceId", "service_id", int.class, false); columnList.add(sourceService); destService = new SourceColumn("childServiceId", "child_service_id", int.class, false); columnList.add(destService); SourceColumn sourceServiceInstance = new SourceColumn("serviceInstanceId", "service_instance_id", int.class, false); columnList.add(sourceServiceInstance); SourceColumn destServiceInstance = new SourceColumn("childServiceInstanceId", "child_service_instance_id", int.class, false); columnList.add(destServiceInstance); return columnList; default: throw new IllegalArgumentException("Illegal source :" + source); } }
|
api-misuse-repair-complete_data_36
|
public static Jets[] addJet(Jets[] list) { Scanner keyboard = new Scanner(System.in); Jets[] increasedArray = new Jets[list.length + 1]; for (int i = 0; i < list.length; i++) { increasedArray[i] = list[i]; } String nameOfJet; double speed; double range; float price; System.out.println("What would you like to name your new jet?"); nameOfJet = keyboard.next(); System.out.println("How fast do you want this thing to go?"); speed = keyboard.nextDouble(); System.out.println("How far would you like your jet to be able t travel?"); range = keyboard.nextDouble(); System.out.println("How much of a down payment would you like to make?"); price = keyboard.nextFloat(); Jets newJet = new Jets(nameOfJet, speed, range, price); increasedArray[(list.length)] = newJet; keyboard.close(); return increasedArray; }
public static Jets[] addJet(Jets[] list) { Scanner keyboard = new Scanner(System.in); Jets[] increasedArray = new Jets[list.length + 1]; for (int i = 0; i < list.length; i++) { increasedArray[i] = list[i]; } String nameOfJet; double speed; double range; float price; System.out.println("What would you like to name your new jet?"); nameOfJet = keyboard.nextLine(); System.out.println("How fast do you want this thing to go?"); speed = keyboard.nextDouble(); System.out.println("How far would you like your jet to be able to travel?"); range = keyboard.nextDouble(); System.out.println("How much of a down payment would you like to make?"); price = keyboard.nextFloat(); Jets newJet = new Jets(nameOfJet, speed, range, price); increasedArray[(list.length)] = newJet; return increasedArray; }
|
api-misuse-repair-complete_data_37
|
@Override public List<WeixinUser> searchSubscribers(int enterpriseId, CommonSearchCriteria sc) { return weixinDao.searchSubscribers(this.weixinId, sc); }
@Override public List<WeixinUser> searchSubscribers(int enterpriseId, CommonSearchCriteria sc) { return weixinDao.searchSubscribers(enterpriseId, sc); }
|
api-misuse-repair-complete_data_38
|
public void doWhenGuessed() { if (trueIfCorrectAnswer(getAnswerAsAlternative(theButtonPressed))) { theButtonPressed.setStyle("-fx-background-color: lawngreen"); ImageView theContinentToChange = game.getiAf().get(game.getCurrentTurnNumberArrayIndex()); game.getCurrentPlayerPlaying().getCollectedContinents().add(Continent.NORTH_AMERICA); theContinentToChange.setImage(new Image("edu/chl/trivialpursuit/view/africa_gold.png")); if (game.getCurrentPlayerPlaying().checkIfAllContinents()) { game.getCurrentPlayerPlaying().setHasTicket(true); } } else { theButtonPressed.setStyle("-fx-background-color: red"); game.setNextTurn(game.getAmountOfPlayersPlaying()); } startTimer(); }
public void doWhenGuessed() { if (trueIfCorrectAnswer(getAnswerAsAlternative(theButtonPressed))) { theButtonPressed.setStyle("-fx-background-color: lawngreen"); ImageView theContinentToChange = game.getiN().get(game.getCurrentTurnNumberArrayIndex()); game.getCurrentPlayerPlaying().getCollectedContinents().add(Continent.NORTH_AMERICA); theContinentToChange.setImage(new Image("edu/chl/trivialpursuit/view/northAm_gold.png")); if (game.getCurrentPlayerPlaying().checkIfAllContinents()) { game.getCurrentPlayerPlaying().setHasTicket(true); } } else { theButtonPressed.setStyle("-fx-background-color: red"); game.setNextTurn(game.getAmountOfPlayersPlaying()); } startTimer(); }
|
api-misuse-repair-complete_data_39
|
private String[] extractData() { String[] params = new String[textParam.size()]; for (int i = 0; i < textParam.size(); i++) { if (i == 0 && !textParam.get(i).getText().equals("") && !textParam.get(i).getText().contains("http")) params[0] = "http://" + textParam.get(i).getText(); else params[i] = textParam.get(i).getText().equals("") || textParam.get(i).getText().contains(" ") ? defaultValue[i] : textParam.get(i).getText(); } return params; }
private String[] extractData(boolean standard) { String[] params = new String[textParam.size()]; for (int i = 0; i < textParam.size(); i++) { if (i == 0 && !textParam.get(i).getText().equals("") && !textParam.get(i).getText().contains("http")) params[0] = standard ? defaultValue[i] : "http://" + textParam.get(i).getText(); else params[i] = standard ? defaultValue[i] : textParam.get(i).getText(); } return params; }
|
api-misuse-repair-complete_data_40
|
public static synchronized RdfStore getInstance() { return (instance == null ? new RdfStore() : instance); }
public static synchronized RdfStore getInstance() { return (instance == null ? instance = new RdfStore() : instance); }
|
api-misuse-repair-complete_data_41
|
private void newGame() throws JSONException { try { sqlConnection = DatabaseUtilities.getSQLConnection(); if (DatabaseUtilities.ensureUserExistsInDatabase(sqlConnection, userChallengedId.longValue(), parameter_userChallengedName)) { board.flipTeams(); final JSONObject boardJSON = board.makeJSON(); final String boardJSONString = boardJSON.toString(); byte runStatus = RUN_STATUS_NO_ERROR; String digest = null; for (boolean continueToRun = true; continueToRun; ) { digest = null; try { digest = createDigest(userChallengedId.toString().getBytes(Utilities.UTF8), userCreatorId.toString().getBytes(Utilities.UTF8), boardJSONString.getBytes(Utilities.UTF8)); } catch (final NoSuchAlgorithmException e) { runStatus = RUN_STATUS_NO_SUCH_ALGORITHM; } catch (final UnsupportedEncodingException e) { runStatus = RUN_STATUS_UNSUPPORTED_ENCODING; } if (runStatus != RUN_STATUS_NO_ERROR || digest == null || digest.isEmpty()) { continueToRun = false; } else { String sqlStatementString = "SELECT " + DatabaseUtilities.TABLE_GAMES_COLUMN_FINISHED + " FROM " + DatabaseUtilities.TABLE_GAMES + " WHERE " + DatabaseUtilities.TABLE_GAMES_COLUMN_ID + " = ?"; sqlStatement = sqlConnection.prepareStatement(sqlStatementString); sqlStatement.setString(1, digest); final ResultSet sqlResult = sqlStatement.executeQuery(); if (sqlResult.next()) { if (sqlResult.getByte(DatabaseUtilities.TABLE_GAMES_COLUMN_FINISHED) == DatabaseUtilities.TABLE_GAMES_FINISHED_TRUE) { DatabaseUtilities.closeSQLStatement(sqlStatement); sqlStatementString = "UPDATE " + DatabaseUtilities.TABLE_GAMES + " SET " + DatabaseUtilities.TABLE_GAMES_COLUMN_USER_CREATOR + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_USER_CHALLENGED + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_BOARD + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_TURN + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_GAME_TYPE + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_FINISHED + " = ? WHERE " + DatabaseUtilities.TABLE_GAMES_COLUMN_ID + " = ?"; sqlStatement = sqlConnection.prepareStatement(sqlStatementString); sqlStatement.setLong(1, userCreatorId.longValue()); sqlStatement.setLong(2, userChallengedId.longValue()); sqlStatement.setString(3, boardJSONString); sqlStatement.setByte(4, DatabaseUtilities.TABLE_GAMES_TURN_CHALLENGED); sqlStatement.setByte(5, gameType.byteValue()); sqlStatement.setByte(6, DatabaseUtilities.TABLE_GAMES_FINISHED_FALSE); sqlStatement.setString(7, digest); sqlStatement.executeUpdate(); continueToRun = false; } } else { DatabaseUtilities.closeSQLStatement(sqlStatement); sqlStatementString = "INSERT INTO " + DatabaseUtilities.TABLE_GAMES + " " + DatabaseUtilities.TABLE_GAMES_FORMAT + " " + DatabaseUtilities.TABLE_GAMES_VALUES; sqlStatement = sqlConnection.prepareStatement(sqlStatementString); sqlStatement.setString(1, digest); sqlStatement.setLong(2, userCreatorId.longValue()); sqlStatement.setLong(3, userChallengedId.longValue()); sqlStatement.setString(4, boardJSONString); sqlStatement.setByte(5, DatabaseUtilities.TABLE_GAMES_TURN_CHALLENGED); sqlStatement.setByte(6, DatabaseUtilities.TABLE_GAMES_FINISHED_FALSE); sqlStatement.executeUpdate(); continueToRun = false; } } } switch(runStatus) { case RUN_STATUS_NO_SUCH_ALGORITHM: printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_COULD_NOT_CREATE_GAME_ID)); break; case RUN_STATUS_UNSUPPORTED_ENCODING: printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_COULD_NOT_CREATE_GAME_ID)); break; default: GCMUtilities.sendMessage(sqlConnection, digest, userCreatorId, userChallengedId, gameType, Byte.valueOf(Utilities.BOARD_NEW_GAME)); printWriter.write(Utilities.makePostDataSuccess(Utilities.POST_SUCCESS_GAME_ADDED_TO_DATABASE)); break; } } else { printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_INVALID_CHALLENGER)); } } catch (final SQLException e) { printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_DATABASE_COULD_NOT_CONNECT)); } finally { DatabaseUtilities.closeSQL(sqlConnection, sqlStatement); } }
private void newGame() throws JSONException { try { sqlConnection = DatabaseUtilities.getSQLConnection(); if (DatabaseUtilities.ensureUserExistsInDatabase(sqlConnection, userChallengedId.longValue(), parameter_userChallengedName)) { board.flipTeams(); final JSONObject boardJSON = board.makeJSON(); final String boardJSONString = boardJSON.toString(); byte runStatus = RUN_STATUS_NO_ERROR; String digest = null; for (boolean continueToRun = true; continueToRun; ) { digest = null; try { digest = createDigest(userChallengedId.toString().getBytes(Utilities.UTF8), userCreatorId.toString().getBytes(Utilities.UTF8), boardJSONString.getBytes(Utilities.UTF8)); } catch (final NoSuchAlgorithmException e) { runStatus = RUN_STATUS_NO_SUCH_ALGORITHM; } catch (final UnsupportedEncodingException e) { runStatus = RUN_STATUS_UNSUPPORTED_ENCODING; } if (runStatus != RUN_STATUS_NO_ERROR || digest == null || digest.isEmpty()) { continueToRun = false; } else { String sqlStatementString = "SELECT " + DatabaseUtilities.TABLE_GAMES_COLUMN_FINISHED + " FROM " + DatabaseUtilities.TABLE_GAMES + " WHERE " + DatabaseUtilities.TABLE_GAMES_COLUMN_ID + " = ?"; sqlStatement = sqlConnection.prepareStatement(sqlStatementString); sqlStatement.setString(1, digest); final ResultSet sqlResult = sqlStatement.executeQuery(); if (sqlResult.next()) { if (sqlResult.getByte(DatabaseUtilities.TABLE_GAMES_COLUMN_FINISHED) == DatabaseUtilities.TABLE_GAMES_FINISHED_TRUE) { DatabaseUtilities.closeSQLStatement(sqlStatement); sqlStatementString = "UPDATE " + DatabaseUtilities.TABLE_GAMES + " SET " + DatabaseUtilities.TABLE_GAMES_COLUMN_USER_CREATOR + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_USER_CHALLENGED + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_BOARD + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_TURN + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_GAME_TYPE + " = ?, " + DatabaseUtilities.TABLE_GAMES_COLUMN_FINISHED + " = ? WHERE " + DatabaseUtilities.TABLE_GAMES_COLUMN_ID + " = ?"; sqlStatement = sqlConnection.prepareStatement(sqlStatementString); sqlStatement.setLong(1, userCreatorId.longValue()); sqlStatement.setLong(2, userChallengedId.longValue()); sqlStatement.setString(3, boardJSONString); sqlStatement.setByte(4, DatabaseUtilities.TABLE_GAMES_TURN_CHALLENGED); sqlStatement.setByte(5, gameType.byteValue()); sqlStatement.setByte(6, DatabaseUtilities.TABLE_GAMES_FINISHED_FALSE); sqlStatement.setString(7, digest); sqlStatement.executeUpdate(); continueToRun = false; } } else { DatabaseUtilities.closeSQLStatement(sqlStatement); sqlStatementString = "INSERT INTO " + DatabaseUtilities.TABLE_GAMES + " " + DatabaseUtilities.TABLE_GAMES_FORMAT + " " + DatabaseUtilities.TABLE_GAMES_VALUES; sqlStatement = sqlConnection.prepareStatement(sqlStatementString); sqlStatement.setString(1, digest); sqlStatement.setLong(2, userCreatorId.longValue()); sqlStatement.setLong(3, userChallengedId.longValue()); sqlStatement.setString(4, boardJSONString); sqlStatement.setByte(5, DatabaseUtilities.TABLE_GAMES_TURN_CHALLENGED); sqlStatement.setByte(6, gameType.byteValue()); sqlStatement.setByte(7, DatabaseUtilities.TABLE_GAMES_FINISHED_FALSE); sqlStatement.executeUpdate(); continueToRun = false; } } } switch(runStatus) { case RUN_STATUS_NO_SUCH_ALGORITHM: printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_COULD_NOT_CREATE_GAME_ID)); break; case RUN_STATUS_UNSUPPORTED_ENCODING: printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_COULD_NOT_CREATE_GAME_ID)); break; default: GCMUtilities.sendMessage(sqlConnection, digest, userCreatorId, userChallengedId, gameType, Byte.valueOf(Utilities.BOARD_NEW_GAME)); printWriter.write(Utilities.makePostDataSuccess(Utilities.POST_SUCCESS_GAME_ADDED_TO_DATABASE)); break; } } else { printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_INVALID_CHALLENGER)); } } catch (final SQLException e) { printWriter.write(Utilities.makePostDataError(Utilities.POST_ERROR_DATABASE_COULD_NOT_CONNECT)); } finally { DatabaseUtilities.closeSQL(sqlConnection, sqlStatement); } }
|
api-misuse-repair-complete_data_42
|
public void addPlayer(String player) { if (!playerNames.contains(player)) { if (getCurrentPlayerAge(player) == 999) { playerNames.add(player); } else if (getCurrentPlayerAge(player) <= DataHolder.getInstance().getTarget_age()) { playerNames.add(player); } else if ((getCurrentPlayerAge(player) > DataHolder.getInstance().getTarget_age()) && (overage_counter < 2)) { playerNames.add(player); overage_counter++; if (overage_counter == 2) { Toast.makeText(ScreenFour.this, "Max Spelare Över Åldersgräns", Toast.LENGTH_SHORT).show(); } } } else { for (int i = 0; i < playerNames.size(); i++) { if (playerNames.get(i) == player) { if (getCurrentPlayerAge(player) > DataHolder.getInstance().getTarget_age()) { overage_counter--; playerNames.remove(i); } else { playerNames.remove(i); } } } } }
public void addPlayer(String player) { if (!playerNames.contains(player)) { if (getCurrentPlayerAge(player) == 999) { playerNames.add(player); } else if (getCurrentPlayerAge(player) <= DataHolder.getInstance().getTarget_age()) { playerNames.add(player); } else if ((getCurrentPlayerAge(player) > DataHolder.getInstance().getTarget_age()) && (overage_counter < 2)) { playerNames.add(player); Toast.makeText(ScreenFour.this, "Antal spelare över åldersgräns: " + overage_counter, Toast.LENGTH_SHORT).show(); overage_counter++; if (overage_counter == 2) { Toast.makeText(ScreenFour.this, player + " är över åldersgräns, lades ej till i spelarlistan pga överskridet maxantal", Toast.LENGTH_LONG).show(); } } } else { for (int i = 0; i < playerNames.size(); i++) { if (playerNames.get(i) == player) { if (getCurrentPlayerAge(player) > DataHolder.getInstance().getTarget_age()) { overage_counter--; playerNames.remove(i); } else { playerNames.remove(i); } } } } }
|
api-misuse-repair-complete_data_43
|
public void run() { final MetadataCreator metadataCreator = new MetadataCreator(dataset.getAbsolutePath()); final Metadata metadata = metadataCreator.getMetadata(); String outputPath = getOutputPath(); createSnakeYamlFile(metadata, outputPath); IJ.open(outputPath); }
public void run() { final MetadataCreator metadataCreator = new MetadataCreator(dataset.getAbsolutePath()); final MetaData metadata = metadataCreator.getMetadata(); String outputPath = getOutputPath(); createSnakeYamlFile(metadata, outputPath); IJ.open(outputPath); }
|
api-misuse-repair-complete_data_44
|
public void sort(InitialChunkProducer producer, Merger merger, Comparator<long[]> comparator, File workingDir, int maxNumberOfOpenFiles, LongOutputWriter output) { maxNumberOfOpenFiles -= 1; try { List<File> chunks = new ArrayList<>(); producer.loadNextChunk(); while (producer.hasNextChunk()) { File chunk = File.createTempFile("initialChunk-", "", workingDir); chunks.add(chunk); try (EncodedLongFileOutputStream chunkOut = new EncodedLongFileOutputStream(chunk)) { producer.sort(comparator); producer.writeChunk(chunkOut); } producer.loadNextChunk(); } producer.close(); while (!chunks.isEmpty()) { List<File> mergedChunks = new ArrayList<>(); for (int iterationStart = 0; iterationStart < chunks.size(); iterationStart += maxNumberOfOpenFiles - 1) { int numberOfProcessedFiles = Math.min(maxNumberOfOpenFiles - 1, chunks.size() - iterationStart); EncodedLongFileInputStream[] inputs = new EncodedLongFileInputStream[numberOfProcessedFiles]; EncodedLongFileInputIterator[] iterators = new EncodedLongFileInputIterator[numberOfProcessedFiles]; LongOutputWriter out = null; try { long[][] nextElements = new long[numberOfProcessedFiles][]; for (int i = 0; i < numberOfProcessedFiles; i++) { inputs[i] = new EncodedLongFileInputStream(chunks.get(iterationStart + i)); iterators[i] = new EncodedLongFileInputIterator(inputs[i]); if (iterators[i].hasNext()) { nextElements[i] = merger.readNextElement(iterators[i]); } else { nextElements[i] = null; iterators[i].close(); iterators[i] = null; } } if (chunks.size() <= (maxNumberOfOpenFiles - 1)) { out = output; } else { File chunk = File.createTempFile("mergeChunk-", "", workingDir); mergedChunks.add(chunk); out = new EncodedLongFileOutputStream(chunk); } for (BitSet indicesOfSmallestElement = getIndicesOfSmallestElement(nextElements, comparator); !indicesOfSmallestElement.isEmpty(); indicesOfSmallestElement = getIndicesOfSmallestElement(nextElements, comparator)) { merger.mergeAndWrite(indicesOfSmallestElement, nextElements, iterators, out); for (int i = indicesOfSmallestElement.nextSetBit(0); i >= 0; i = indicesOfSmallestElement.nextSetBit(i + 1)) { if (iterators[i].hasNext()) { nextElements[i] = merger.readNextElement(iterators[i]); } else { nextElements[i] = null; iterators[i].close(); iterators[i] = null; } } } } finally { try { merger.close(); } catch (Exception e) { throw new RuntimeException(e); } if (out != null) { out.close(); } for (EncodedLongFileInputIterator iter : iterators) { if (iter != null) { iter.close(); } } for (EncodedLongFileInputStream input : inputs) { if (input != null) { input.close(); } } } for (File chunk : chunks) { chunk.delete(); } } chunks = mergedChunks; } } catch (IOException e) { throw new RuntimeException(e); } }
public void sort(InitialChunkProducer producer, Merger merger, Comparator<long[]> comparator, File workingDir, int maxNumberOfOpenFiles, LongOutputWriter output) { maxNumberOfOpenFiles -= 1; try { List<File> chunks = new ArrayList<>(); producer.loadNextChunk(); while (producer.hasNextChunk()) { File chunk = File.createTempFile("initialChunk-", "", workingDir); chunks.add(chunk); try (EncodedLongFileOutputStream chunkOut = new EncodedLongFileOutputStream(chunk)) { producer.sort(comparator); producer.writeChunk(chunkOut); } producer.loadNextChunk(); } producer.close(); while (!chunks.isEmpty()) { List<File> mergedChunks = new ArrayList<>(); for (int iterationStart = 0; iterationStart < chunks.size(); iterationStart += maxNumberOfOpenFiles - 1) { int numberOfProcessedFiles = Math.min(maxNumberOfOpenFiles - 1, chunks.size() - iterationStart); EncodedLongFileInputStream[] inputs = new EncodedLongFileInputStream[numberOfProcessedFiles]; LongIterator[] iterators = new LongIterator[numberOfProcessedFiles]; LongOutputWriter out = null; try { long[][] nextElements = new long[numberOfProcessedFiles][]; for (int i = 0; i < numberOfProcessedFiles; i++) { inputs[i] = new EncodedLongFileInputStream(chunks.get(iterationStart + i)); iterators[i] = inputs[i].iterator(); if (iterators[i].hasNext()) { nextElements[i] = merger.readNextElement(iterators[i]); } else { nextElements[i] = null; iterators[i].close(); iterators[i] = null; } } if (chunks.size() <= (maxNumberOfOpenFiles - 1)) { out = output; } else { File chunk = File.createTempFile("mergeChunk-", "", workingDir); mergedChunks.add(chunk); out = new EncodedLongFileOutputStream(chunk); } for (BitSet indicesOfSmallestElement = getIndicesOfSmallestElement(nextElements, comparator); !indicesOfSmallestElement.isEmpty(); indicesOfSmallestElement = getIndicesOfSmallestElement(nextElements, comparator)) { merger.mergeAndWrite(indicesOfSmallestElement, nextElements, iterators, out); for (int i = indicesOfSmallestElement.nextSetBit(0); i >= 0; i = indicesOfSmallestElement.nextSetBit(i + 1)) { if (iterators[i].hasNext()) { nextElements[i] = merger.readNextElement(iterators[i]); } else { nextElements[i] = null; iterators[i].close(); iterators[i] = null; } } } } finally { try { merger.close(); } catch (Exception e) { throw new RuntimeException(e); } if (out != null) { out.close(); } for (LongIterator iter : iterators) { if (iter != null) { iter.close(); } } for (EncodedLongFileInputStream input : inputs) { if (input != null) { input.close(); } } } for (int i = 0; i < numberOfProcessedFiles; i++) { chunks.get(iterationStart + i).delete(); } } chunks = mergedChunks; } } catch (IOException e) { throw new RuntimeException(e); } }
|
api-misuse-repair-complete_data_45
|
public void setUpEntityMentionBuilding(Properties properties) { this.buildEntityMentions = PropertiesUtils.getBool(properties, "ner.buildEntityMentions", true); if (this.buildEntityMentions) { String entityMentionsPrefix = "ner.entitymentions"; Properties entityMentionsProps = PropertiesUtils.extractPrefixedProperties(properties, entityMentionsPrefix + "."); entityMentionsAnnotator = new EntityMentionsAnnotator("ner.entitymentions", entityMentionsProps); } }
public void setUpEntityMentionBuilding(Properties properties) { this.buildEntityMentions = PropertiesUtils.getBool(properties, "ner.buildEntityMentions", true); if (this.buildEntityMentions) { String entityMentionsPrefix = "ner.entitymentions"; Properties entityMentionsProps = PropertiesUtils.extractPrefixedProperties(properties, entityMentionsPrefix + ".", true); entityMentionsAnnotator = new EntityMentionsAnnotator(entityMentionsPrefix, entityMentionsProps); } }
|
api-misuse-repair-complete_data_46
|
private int appendUnfragmentedMessage(final DirectBuffer srcBuffer, final int srcOffset, final int length) { final int frameLength = length + HEADER_LENGTH; final int alignedLength = align(frameLength, FRAME_ALIGNMENT); final int frameOffset = getTailAndAdd(alignedLength); final UnsafeBuffer termBuffer = termBuffer(); final int capacity = termBuffer.capacity(); if (isBeyondLogBufferCapacity(frameOffset, alignedLength, capacity)) { if (frameOffset < capacity) { appendPaddingFrame(termBuffer, frameOffset, capacity); return TRIPPED; } else if (frameOffset == capacity) { return TRIPPED; } return FAILED; } termBuffer.putBytes(frameOffset, defaultHeader, 0, HEADER_LENGTH); termBuffer.putBytes(frameOffset + HEADER_LENGTH, srcBuffer, srcOffset, length); frameFlags(termBuffer, frameOffset, UNFRAGMENTED); frameTermOffset(termBuffer, frameOffset, frameOffset); frameLengthOrdered(termBuffer, frameOffset, frameLength); return frameOffset + alignedLength; }
private int appendUnfragmentedMessage(final DirectBuffer srcBuffer, final int srcOffset, final int length) { final int frameLength = length + HEADER_LENGTH; final int alignedLength = align(frameLength, FRAME_ALIGNMENT); final int frameOffset = getTailAndAdd(alignedLength); final UnsafeBuffer termBuffer = termBuffer(); final int capacity = termBuffer.capacity(); if (isBeyondTermCapacity(frameOffset, alignedLength, capacity)) { if (frameOffset <= (capacity - HEADER_LENGTH)) { appendPaddingFrame(termBuffer, frameOffset, capacity); return TRIPPED; } else if (frameOffset == capacity) { return TRIPPED; } return FAILED; } termBuffer.putBytes(frameOffset, defaultHeader, 0, HEADER_LENGTH); termBuffer.putBytes(frameOffset + HEADER_LENGTH, srcBuffer, srcOffset, length); frameFlags(termBuffer, frameOffset, UNFRAGMENTED); frameTermOffset(termBuffer, frameOffset, frameOffset); frameLengthOrdered(termBuffer, frameOffset, frameLength); return frameOffset + alignedLength; }
|
api-misuse-repair-complete_data_47
|
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { HttpSession session = request.getSession(); Profiles user = (Profiles) session.getAttribute("profile"); ServletContext ctx = getServletContext(); Connection conn = (Connection) ctx.getAttribute("connection"); String artId = request.getParameter("id"); String title = request.getParameter("title"); String desc = request.getParameter("desc"); String tempPrice = request.getParameter("price"); if (tempPrice == null) { tempPrice = "0"; } Float price = Float.parseFloat(tempPrice); String[] allTag = request.getParameter("tags").split(","); Art art = new Art(conn, id); art.setTitle(title); art.setDesc(desc); art.getProduct().setPrice(price); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("UPDATE usami.Image SET image_name = ?, Image.desc = ? WHERE image_id = ?;"); pstmt.setString(1, title); pstmt.setString(2, desc); pstmt.setString(3, artId); pstmt.executeUpdate(); pstmt = conn.prepareStatement("DELETE FROM usami.Tag_has WHERE image_id = ?"); pstmt.setString(1, artId); pstmt.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } out.println(art.getProduct()); out.println(art.getProduct().getProduct_id()); art.updateArts(); for (String tag : allTag) { ArtTag artTag = new ArtTag(conn, tag); if (artTag.getTag_id() == 0) { artTag.insertTag(); } artTag.insertTag_has(artId); } response.sendRedirect("/Usami/Storage"); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { HttpSession session = request.getSession(); Profiles user = (Profiles) session.getAttribute("profile"); ServletContext ctx = getServletContext(); Connection conn = (Connection) ctx.getAttribute("connection"); String artId = request.getParameter("id"); String title = request.getParameter("title"); String desc = request.getParameter("desc"); String tempPrice = request.getParameter("price"); if (tempPrice == null) { tempPrice = "0"; } Float price = Float.parseFloat(tempPrice); String[] allTag = request.getParameter("tags").split(","); Art art = new Art(conn, artId); art.setTitle(title); art.setDesc(desc); art.getProduct().setPrice(price); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("UPDATE usami.Image SET image_name = ?, Image.desc = ? WHERE image_id = ?;"); pstmt.setString(1, title); pstmt.setString(2, desc); pstmt.setString(3, artId); pstmt.executeUpdate(); pstmt = conn.prepareStatement("DELETE FROM usami.Tag_has WHERE image_id = ?"); pstmt.setString(1, artId); pstmt.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } out.println(art.getProduct()); out.println(art.getProduct().getProduct_id()); art.updateArts(); for (String tag : allTag) { ArtTag artTag = new ArtTag(conn, tag); if (artTag.getTag_id() == 0) { artTag.insertTag(); } artTag.insertTag_has(artId); } response.sendRedirect("/Usami/Storage"); } }
|
api-misuse-repair-complete_data_48
|
protected String FetchUrl(String url) { try { final URL u = new URL(url); URLConnection c = u.openConnection(); if (u.getProtocol().equals("https")) { HttpsURLConnection sslconn = (HttpsURLConnection) c; if (override_certname != null && !override_certname.equals("")) { sslconn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { X509Certificate cert; try { cert = (X509Certificate) session.getPeerCertificates()[0]; } catch (SSLPeerUnverifiedException e) { throw new RuntimeException(String.format("Failed to verify peer for url: %s (%s)", e, u.toString())); } Matcher m = DNPattern.matcher(cert.getSubjectDN().getName()); if (!m.find()) { throw new RuntimeException(String.format("Could not extract hostname from '%s' for url %s", cert.getSubjectDN(), u.toString())); } String sslname = m.group(1); if (sslname.equals(override_certname)) { return true; } throw new RuntimeException(String.format("Certificate hostname '%s' does not match expected hostname '%s'", sslname, override_certname)); } }); } if (whitelisted_cert != null && !whitelisted_cert.equals("")) { SSLContext context; try { context = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Could not find TLS context!"); } try { context.init(null, new X509TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Could not find SHA-1 digest"); } md.update(chain[0].getEncoded()); byte[] digest = md.digest(); BigInteger bi = new BigInteger(1, digest); String fingerprint = String.format("%0" + (digest.length << 1) + "X", bi); if (!fingerprint.equals(whitelisted_cert)) { throw new CertificateException("Certificate fingerprint does not match the configured one!"); } } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, null); } catch (KeyManagementException e) { throw new RuntimeException(String.format("Unable to set up key management: %s", e.toString())); } sslconn.setSSLSocketFactory(context.getSocketFactory()); } } InputStreamReader isr = new InputStreamReader(c.getInputStream()); BufferedReader r = new BufferedReader(isr); StringWriter sw = new StringWriter(); String line; while ((line = r.readLine()) != null) { sw.write(line); sw.write("\n"); } return sw.toString(); } catch (MalformedURLException e) { throw new RuntimeException(String.format("Failed to fetch url: %s (%s)", e, url)); } catch (IOException e) { throw new RuntimeException(String.format("Failed to fetch url: %s (%s)", e, url)); } }
protected String FetchUrl(String url) { try { final URL u = new URL(url); URLConnection c = u.openConnection(java.net.Proxy.NO_PROXY); if (u.getProtocol().equals("https")) { HttpsURLConnection sslconn = (HttpsURLConnection) c; if (override_certname != null && !override_certname.equals("")) { sslconn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { X509Certificate cert; try { cert = (X509Certificate) session.getPeerCertificates()[0]; } catch (SSLPeerUnverifiedException e) { throw new RuntimeException(String.format("Failed to verify peer for url: %s (%s)", e, u.toString())); } Matcher m = DNPattern.matcher(cert.getSubjectDN().getName()); if (!m.find()) { throw new RuntimeException(String.format("Could not extract hostname from '%s' for url %s", cert.getSubjectDN(), u.toString())); } String sslname = m.group(1); if (sslname.equals(override_certname)) { return true; } throw new RuntimeException(String.format("Certificate hostname '%s' does not match expected hostname '%s'", sslname, override_certname)); } }); } if (whitelisted_cert != null && !whitelisted_cert.equals("")) { SSLContext context; try { context = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Could not find TLS context!"); } try { context.init(null, new X509TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Could not find SHA-1 digest"); } md.update(chain[0].getEncoded()); byte[] digest = md.digest(); BigInteger bi = new BigInteger(1, digest); String fingerprint = String.format("%0" + (digest.length << 1) + "X", bi); if (!fingerprint.equals(whitelisted_cert)) { throw new CertificateException("Certificate fingerprint does not match the configured one!"); } } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, null); } catch (KeyManagementException e) { throw new RuntimeException(String.format("Unable to set up key management: %s", e.toString())); } sslconn.setSSLSocketFactory(context.getSocketFactory()); } } InputStreamReader isr = new InputStreamReader(c.getInputStream()); BufferedReader r = new BufferedReader(isr); StringWriter sw = new StringWriter(); String line; while ((line = r.readLine()) != null) { sw.write(line); sw.write("\n"); } r.close(); isr.close(); return sw.toString(); } catch (MalformedURLException e) { throw new RuntimeException(String.format("Failed to fetch url: %s (%s)", e, url)); } catch (IOException e) { throw new RuntimeException(String.format("Failed to fetch url: %s (%s)", e, url)); } }
|
api-misuse-repair-complete_data_49
|
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { moving = 1; Input input = gc.getInput(); menu(gc, sbg); barriarsCollision(gc); movingCollision(); if (heroPositionX < -5910) { sbg.enterState(2); } for (int z = 0; z < movingObstacles.size(); z++) { Rectangle obstacle = movingObstacles.get(z); if (obstacle.y > 1000) { movingObstacles.clear(); addMovingObstacles(true); } } if (restart) { score = 0; heroPositionX = 0; heroPositionY = 0; time = 1; movingObstacles.clear(); obstacles.clear(); loadObstacbles(); addMovingObstacles(true); buttons.clear(); generateAnswers(time, question); restart = false; } for (int i = 0; i < movingObstacles.size(); i++) { movingObstacle = movingObstacles.get(i); movingObstacle.y++; if (input.isKeyDown(Input.KEY_UP)) { movingObstacle.y += moving; } if (input.isKeyDown(Input.KEY_DOWN)) { movingObstacle.y -= moving; } if (input.isKeyDown(Input.KEY_LEFT)) { movingObstacle.x += moving; } if (input.isKeyDown(Input.KEY_RIGHT)) { movingObstacle.x -= moving; } } anwserCheck(gc); if (input.isKeyDown(Input.KEY_UP)) { hero = movingUp; heroPositionY += moving; } if (input.isKeyDown(Input.KEY_DOWN)) { hero = movingDown; heroPositionY -= moving; } if (input.isKeyDown(Input.KEY_LEFT)) { hero = movingLeft; heroPositionX += moving; } if (input.isKeyDown(Input.KEY_RIGHT)) { hero = movingRight; heroPositionX -= moving; } }
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException { moving = 1; Input input = gc.getInput(); menu(gc, sbg); barriarsCollision(gc); movingCollision(); if (heroPositionX < -5910) { sbg.enterState(2); } for (int z = 0; z < movingObstacles.size(); z++) { Rectangle obstacle = movingObstacles.get(z); if (obstacle.y > 1000) { movingObstacles.clear(); addMovingObstacles(true); } } if (restart) { score = 0; heroPositionX = 0; heroPositionY = 0; time = 1; movingObstacles.clear(); obstacles.clear(); loadObstacbles(); addMovingObstacles(true); buttons.clear(); generateAnswers(time, question); restart = false; } for (int i = 0; i < movingObstacles.size(); i++) { movingObstacle = movingObstacles.get(i); movingObstacle.y++; if (input.isKeyDown(Input.KEY_UP)) { movingObstacle.y += moving; } if (input.isKeyDown(Input.KEY_DOWN)) { movingObstacle.y -= moving; } if (input.isKeyDown(Input.KEY_LEFT)) { movingObstacle.x += moving; } if (input.isKeyDown(Input.KEY_RIGHT)) { movingObstacle.x -= moving; } } anwserCheck(gc); if (input.isKeyDown(Input.KEY_UP)) { hero = movingUp; heroPositionY += moving; if (heroPositionY > 278) { heroPositionY -= 20; collision.up(obstacles, movingObstacles, buttons, 20); } } if (input.isKeyDown(Input.KEY_DOWN)) { hero = movingDown; heroPositionY -= moving; if (heroPositionY < -493) { heroPositionY += 20; collision.down(obstacles, movingObstacles, buttons, 20); } } if (input.isKeyDown(Input.KEY_LEFT)) { hero = movingLeft; heroPositionX += moving; } if (input.isKeyDown(Input.KEY_RIGHT)) { hero = movingRight; heroPositionX -= moving; } }
|
api-misuse-repair-complete_data_50
|
public void matInit() { matrixCalPanel.setLayout(null); matrixCalPanel.add(matInputPanel); matrixCalPanel.add(matBtnPanel); matrixCalPanel.add(matResultPanel); matInputPanel.setLayout(null); matInputPanel.setBounds(0, 0, 680, 140); matInputPanel.setBackground(deepGrey); matInputPanel.add(matA); matInputPanel.add(matB); matInputPanel.add(matRowTipA); matInputPanel.add(matRowA); matInputPanel.add(matColTipA); matInputPanel.add(matColA); matInputPanel.add(matTextA); matInputPanel.add(matFacTipA); matInputPanel.add(matRowTipB); matInputPanel.add(matRowB); matInputPanel.add(matColTipB); matInputPanel.add(matColB); matInputPanel.add(matTextB); matInputPanel.add(matFacTipB); matA.setBounds(0, matHeightA, 80, matSize); matRowTipA.setBounds(80, matHeightA, 40, matSize); matRowA.setBounds(120, matHeightA, 40, matSize); matColTipA.setBounds(160, matHeightA, 40, matSize); matColA.setBounds(200, matHeightA, 40, matSize); matFacTipA.setBounds(240, matHeightA, 40, matSize); matTextA.setBounds(280, 10, 400, 40); matB.setBounds(0, matHeightB, 80, matSize); matRowTipB.setBounds(80, matHeightB, 40, matSize); matRowB.setBounds(120, matHeightB, 40, matSize); matColTipB.setBounds(160, matHeightB, 40, matSize); matColB.setBounds(200, matHeightB, 40, matSize); matFacTipB.setBounds(240, matHeightB, 40, matSize); matTextB.setBounds(280, 75, 400, 40); matA.setSelected(true); matA.setForeground(Color.WHITE); matRowTipA.setForeground(Color.WHITE); matColTipA.setForeground(Color.WHITE); matFacTipA.setForeground(Color.WHITE); matB.setForeground(Color.WHITE); matRowTipB.setForeground(Color.WHITE); matColTipB.setForeground(Color.WHITE); matFacTipB.setForeground(Color.WHITE); matRowB.setEditable(false); matRowB.setBackground(Color.GRAY); matColB.setEditable(false); matColB.setBackground(Color.GRAY); matTextB.setEditable(false); matTextB.setBackground(Color.GRAY); matBtnPanel.setLayout(new GridLayout(2, 4, 0, 0)); matBtnPanel.setBounds(0, 140, 400, 195); matBtnPanel.setBackground(deepGrey); for (int i = 0; i < matBtnText.length; ++i) { matBtns[i] = new JButton(matBtnText[i]); matBtnPanel.add(matBtns[i]); } matResultPanel.setBounds(400, 140, 280, 195); matResultPanel.add(matResult); matResultPanel.setLayout(null); matResult.setBounds(0, 0, 280, 195); matResult.setForeground(Color.WHITE); matResult.setEditable(false); }
public void matInit() { matrixCalPanel.setLayout(null); matrixCalPanel.add(matInputPanel); matrixCalPanel.add(matBtnPanel); matrixCalPanel.add(matResultPanel); matInputPanel.setLayout(null); matInputPanel.setBounds(0, 0, 680, 140); matInputPanel.setBackground(deepGrey); matInputPanel.add(matA); matInputPanel.add(matB); matInputPanel.add(matRowTipA); matInputPanel.add(matRowA); matInputPanel.add(matColTipA); matInputPanel.add(matColA); matInputPanel.add(matTextA); matInputPanel.add(matFacTipA); matInputPanel.add(matRowTipB); matInputPanel.add(matRowB); matInputPanel.add(matColTipB); matInputPanel.add(matColB); matInputPanel.add(matTextB); matInputPanel.add(matFacTipB); matA.setBounds(0, matHeightA, 80, matSize); matRowTipA.setBounds(80, matHeightA, 40, matSize); matRowA.setBounds(120, matHeightA, 40, matSize); matColTipA.setBounds(160, matHeightA, 40, matSize); matColA.setBounds(200, matHeightA, 40, matSize); matFacTipA.setBounds(240, matHeightA, 40, matSize); matTextA.setBounds(280, 10, 400, 40); matB.setBounds(0, matHeightB, 80, matSize); matRowTipB.setBounds(80, matHeightB, 40, matSize); matRowB.setBounds(120, matHeightB, 40, matSize); matColTipB.setBounds(160, matHeightB, 40, matSize); matColB.setBounds(200, matHeightB, 40, matSize); matFacTipB.setBounds(240, matHeightB, 40, matSize); matTextB.setBounds(280, 75, 400, 40); matA.setSelected(true); matA.setForeground(Color.WHITE); matRowTipA.setForeground(Color.WHITE); matColTipA.setForeground(Color.WHITE); matFacTipA.setForeground(Color.WHITE); matB.setForeground(Color.WHITE); matRowTipB.setForeground(Color.WHITE); matColTipB.setForeground(Color.WHITE); matFacTipB.setForeground(Color.WHITE); matRowB.setEditable(false); matRowB.setBackground(Color.GRAY); matColB.setEditable(false); matColB.setBackground(Color.GRAY); matTextB.setEditable(false); matTextB.setBackground(Color.GRAY); matBtnPanel.setLayout(new GridLayout(2, 4, 0, 0)); matBtnPanel.setBounds(0, 140, 400, 200); matBtnPanel.setBackground(deepGrey); for (int i = 0; i < matBtnText.length; ++i) { matBtns[i] = new JButton(matBtnText[i]); matBtnPanel.add(matBtns[i]); } matResultPanel.setBounds(400, 140, 280, 200); matResultPanel.add(matResult); matResultPanel.setLayout(null); matResult.setBounds(0, 0, 280, 200); matResult.setForeground(Color.WHITE); matResult.setEditable(false); }
|
api-misuse-repair-complete_data_51
|
public void print(TextView view) { String s = "YAW: " + Double.toString(yaw) + " PITCH: " + Double.toString(pitch) + " ROLL: " + Double.toString(roll); if (view != null) { view.setText(s); } else { System.out.println(s); } }
public void print(TextView view) { String s = "YAW: " + Integer.toString(yaw) + " PITCH: " + Integer.toString(pitch) + " ROLL: " + Integer.toString(roll); if (view != null) { view.setText(s); } else { System.out.println(s); } }
|
api-misuse-repair-complete_data_52
|
protected void setupHttpServer() throws Exception { _httpServer = new LocalFileServer(); _configUrl = _httpServer.serveDir("/conf", "conf", _localFileServerPort); LOG.info("Started HTTP server from which config for the MesosSupervisor's may be fetched. URL: " + _configUrl); }
protected void setupHttpServer() throws Exception { _httpServer = new LocalFileServer(); String filePath = "/usr/local/etc/storm/conf"; _configUrl = _httpServer.serveDir("/conf", filePath, _localFileServerPort); LOG.info("Started HTTP server from which config for the MesosSupervisor's may be fetched. URL: " + _configUrl); }
|
api-misuse-repair-complete_data_53
|
protected void purgeExpired() { if (expirations == null || expirations.isEmpty()) { return; } final Set<Expiration> current = new TreeSet<Expiration>(expirations); logger.info("Checking {} expirations", current.size()); for (final Expiration exp : current) { if (exp == null) { continue; } final ExpirationKey key = exp.getKey(); logger.debug("Checking expiration for: {}", key); boolean cancel = false; if (!exp.isActive()) { logger.info("Expiration no longer active: {}", exp); cancel = true; } boolean expired = false; if (!cancel) { expired = exp.getExpires() <= System.currentTimeMillis(); logger.info("Checking expiration: {} vs current time: {}. Expired? {}", exp.getExpires(), System.currentTimeMillis(), expired); if (expired) { try { logger.info("\n\n\n [{}] TRIGGERING: {} (expiration timeout: {})\n\n\n", System.currentTimeMillis(), exp, exp.getExpires()); trigger(exp); } catch (final ExpirationManagerException e) { logger.error("Failed to trigger expiration: {}. Reason: {}", e, key, e.getMessage()); cancel = true; } } } if (cancel) { logger.info("Canceling: {}", key); try { cancel(exp); } catch (final ExpirationManagerException e) { logger.error("Failed to cancel expiration: {}. Reason: {}", e, key, e.getMessage()); } } if (cancel || expired) { logger.info("Removing handled expiration: {}", key); try { remove(exp); } catch (final ExpirationManagerException e) { logger.error("Failed to remove expiration: {}. Reason: {}", e, key, e.getMessage()); } } } }
protected void purgeExpired() { if (expirations == null || expirations.isEmpty()) { return; } final Set<Expiration> current = new TreeSet<Expiration>(expirations); logger.info("Checking {} expirations", current.size()); for (final Expiration exp : current) { if (exp == null) { continue; } final ExpirationKey key = exp.getKey(); logger.debug("Checking expiration for: {}", key); boolean cancel = false; if (!exp.isActive()) { logger.info("Expiration no longer active: {}", exp); cancel = true; } boolean expired = false; if (!cancel) { expired = exp.getExpires() <= System.currentTimeMillis(); logger.info("Checking expiration: {} vs current time: {}. Expired? {}", exp.getExpires(), System.currentTimeMillis(), expired); if (expired) { try { logger.info("\n\n\n [{}] TRIGGERING: {} (expiration timeout: {})\n\n\n", System.currentTimeMillis(), exp, exp.getExpires()); trigger(exp); } catch (final ExpirationManagerException e) { logger.error(String.format("Failed to trigger expiration: %s. Reason: %s", key, e.getMessage()), e); cancel = true; } } } if (cancel) { logger.info("Canceling: {}", key); try { cancel(exp); } catch (final ExpirationManagerException e) { logger.error(String.format("Failed to cancel expiration: %s. Reason: %s", key, e.getMessage()), e); } } if (cancel || expired) { logger.info("Removing handled expiration: {}", key); try { remove(exp); } catch (final ExpirationManagerException e) { logger.error(String.format("Failed to remove expiration: %s. Reason: %s", key, e.getMessage()), e); } } } }
|
api-misuse-repair-complete_data_54
|
public String getMovieQuote() { return ""; }
public String getMovieQuote() { return EMPTY_STRING; }
|
api-misuse-repair-complete_data_55
|
public static String read(StreamSourceChannel channel) throws IOException { final int capacity = 1024; ByteArrayOutputStream os = new ByteArrayOutputStream(capacity); ByteBuffer buf = ByteBuffer.allocate(capacity); while (Channels.readBlocking(channel, buf) != -1) { buf.flip(); os.write(buf.array()); buf.clear(); } return new String(os.toByteArray(), CHARSET); }
public static String read(StreamSourceChannel channel) throws IOException { final int capacity = 1024; ByteArrayOutputStream os = new ByteArrayOutputStream(capacity); ByteBuffer buf = ByteBuffer.allocate(capacity); int read = Channels.readBlocking(channel, buf); while (read != -1) { buf.flip(); os.write(buf.array(), 0, read); buf.clear(); read = Channels.readBlocking(channel, buf); } String ret = os.toString(CHARSET.name()); return ret; }
|
api-misuse-repair-complete_data_56
|
public static ChangeBlockEvent.Place callBlockPlaceEvent(Event event) { if (!(event instanceof ChangeBlockEvent.Place)) { throw new IllegalArgumentException("Event is not a valid ChangeBlockEventPlace"); } ChangeBlockEvent.Place spongeEvent = (ChangeBlockEvent.Place) event; if (spongeEvent.getCause().first(Player.class).isPresent()) { EntityPlayer player = (EntityPlayer) spongeEvent.getCause().first(Player.class).get(); net.minecraft.world.World world = (net.minecraft.world.World) spongeEvent.getTargetWorld(); if (spongeEvent.getTransactions().size() == 1) { BlockPos pos = VecHelper.toBlockPos(spongeEvent.getTransactions().get(0).getOriginal().getPosition()); IBlockState state = (IBlockState) spongeEvent.getTransactions().get(0).getOriginal().getState(); net.minecraftforge.common.util.BlockSnapshot blockSnapshot = new net.minecraftforge.common.util.BlockSnapshot(world, pos, state); IBlockState placedAgainst = Blocks.air.getDefaultState(); if (StaticMixinHelper.packetPlayer != null && StaticMixinHelper.processingPacket instanceof C08PacketPlayerBlockPlacement) { C08PacketPlayerBlockPlacement packet = (C08PacketPlayerBlockPlacement) StaticMixinHelper.processingPacket; EnumFacing facing = EnumFacing.getFront(packet.getPlacedBlockDirection()); placedAgainst = blockSnapshot.world.getBlockState(blockSnapshot.pos.offset(facing.getOpposite())); } BlockEvent.PlaceEvent forgeEvent = new BlockEvent.PlaceEvent(blockSnapshot, placedAgainst, player); ((IMixinEventBus) MinecraftForge.EVENT_BUS).post(forgeEvent, true); if (forgeEvent.isCanceled()) { spongeEvent.getTransactions().get(0).setValid(false); } } else { Iterator<Transaction<BlockSnapshot>> iterator = spongeEvent.getTransactions().iterator(); List<net.minecraftforge.common.util.BlockSnapshot> blockSnapshots = new ArrayList<>(); while (iterator.hasNext()) { Transaction<BlockSnapshot> transaction = iterator.next(); Location<World> location = transaction.getOriginal().getLocation().get(); IBlockState state = (IBlockState) transaction.getOriginal().getState(); BlockPos pos = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()); net.minecraftforge.common.util.BlockSnapshot blockSnapshot = new net.minecraftforge.common.util.BlockSnapshot(world, pos, state); blockSnapshots.add(blockSnapshot); } IBlockState placedAgainst = Blocks.air.getDefaultState(); if (StaticMixinHelper.packetPlayer != null && StaticMixinHelper.processingPacket instanceof C08PacketPlayerBlockPlacement) { C08PacketPlayerBlockPlacement packet = (C08PacketPlayerBlockPlacement) StaticMixinHelper.processingPacket; EnumFacing facing = EnumFacing.getFront(packet.getPlacedBlockDirection()); placedAgainst = blockSnapshots.get(0).world.getBlockState(blockSnapshots.get(0).pos.offset(facing.getOpposite())); } BlockEvent.MultiPlaceEvent forgeEvent = new BlockEvent.MultiPlaceEvent(blockSnapshots, placedAgainst, player); ((IMixinEventBus) MinecraftForge.EVENT_BUS).post(forgeEvent, true); if (forgeEvent.isCanceled()) { while (iterator.hasNext()) { iterator.next().setValid(false); } } } } return spongeEvent; }
public static ChangeBlockEvent.Place callBlockPlaceEvent(Event event) { if (!(event instanceof ChangeBlockEvent.Place)) { throw new IllegalArgumentException("Event is not a valid ChangeBlockEventPlace"); } ChangeBlockEvent.Place spongeEvent = (ChangeBlockEvent.Place) event; if (spongeEvent.getCause().first(Player.class).isPresent()) { EntityPlayer player = (EntityPlayer) spongeEvent.getCause().first(Player.class).get(); net.minecraft.world.World world = (net.minecraft.world.World) spongeEvent.getTargetWorld(); final CauseTracker causeTracker = ((IMixinWorld) world).getCauseTracker(); if (spongeEvent.getTransactions().size() == 1) { BlockPos pos = VecHelper.toBlockPos(spongeEvent.getTransactions().get(0).getOriginal().getPosition()); IBlockState state = (IBlockState) spongeEvent.getTransactions().get(0).getOriginal().getState(); net.minecraftforge.common.util.BlockSnapshot blockSnapshot = new net.minecraftforge.common.util.BlockSnapshot(world, pos, state); IBlockState placedAgainst = Blocks.air.getDefaultState(); if (causeTracker.getCurrentPlayerPacket() instanceof C08PacketPlayerBlockPlacement) { C08PacketPlayerBlockPlacement packet = (C08PacketPlayerBlockPlacement) causeTracker.getCurrentPlayerPacket(); EnumFacing facing = EnumFacing.getFront(packet.getPlacedBlockDirection()); placedAgainst = blockSnapshot.world.getBlockState(blockSnapshot.pos.offset(facing.getOpposite())); } BlockEvent.PlaceEvent forgeEvent = new BlockEvent.PlaceEvent(blockSnapshot, placedAgainst, player); ((IMixinEventBus) MinecraftForge.EVENT_BUS).post(forgeEvent, true); if (forgeEvent.isCanceled()) { spongeEvent.getTransactions().get(0).setValid(false); } } else { Iterator<Transaction<BlockSnapshot>> iterator = spongeEvent.getTransactions().iterator(); List<net.minecraftforge.common.util.BlockSnapshot> blockSnapshots = new ArrayList<>(); while (iterator.hasNext()) { Transaction<BlockSnapshot> transaction = iterator.next(); Location<World> location = transaction.getOriginal().getLocation().get(); IBlockState state = (IBlockState) transaction.getOriginal().getState(); BlockPos pos = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()); net.minecraftforge.common.util.BlockSnapshot blockSnapshot = new net.minecraftforge.common.util.BlockSnapshot(world, pos, state); blockSnapshots.add(blockSnapshot); } IBlockState placedAgainst = Blocks.air.getDefaultState(); if (causeTracker.getCurrentPlayerPacket() instanceof C08PacketPlayerBlockPlacement) { C08PacketPlayerBlockPlacement packet = (C08PacketPlayerBlockPlacement) causeTracker.getCurrentPlayerPacket(); EnumFacing facing = EnumFacing.getFront(packet.getPlacedBlockDirection()); placedAgainst = blockSnapshots.get(0).world.getBlockState(blockSnapshots.get(0).pos.offset(facing.getOpposite())); } BlockEvent.MultiPlaceEvent forgeEvent = new BlockEvent.MultiPlaceEvent(blockSnapshots, placedAgainst, player); ((IMixinEventBus) MinecraftForge.EVENT_BUS).post(forgeEvent, true); if (forgeEvent.isCanceled()) { while (iterator.hasNext()) { iterator.next().setValid(false); } } } } return spongeEvent; }
|
api-misuse-repair-complete_data_57
|
public void start() { boolean running = true; experimentAgenda = new ArrayList<Test>(); if (regression) { try { experimentAgenda.addAll(regression()); } catch (TestExecutionException e) { logger.warn("Problems during the regression", e); } } experimentAgenda.addAll(createRandomTests()); if (!dryrun) { if (bootstrap) { try { bootstrap(); } catch (TestExecutionException e) { logger.warn("Problems during the bootstrap", e); } } while (running) { try { logger.info("IterImpl.start() Scheduling : " + experimentAgenda.size() + " experiments to run."); scheduleAndRunExperiments(experimentAgenda); } catch (InterruptedException e) { logger.warn("Interrupted execution. Exit"); running = false; break; } logger.info("IterImpl.start() Experiments that remains to run or must be repeated: " + experimentAgenda.size()); Collection<Test> newExperiments = null; try { newExperiments = testSuiteEvolver.evolveTestSuite(testSuite, testResultsCollector.getTestResults()); } catch (Exception e) { logger.warn("Error during test suite evolution. Continue", e); } experimentAgenda.addAll(newExperiments); if (experimentAgenda.size() == 0) { logger.info("There are no more tests to run !"); running = false; } } try { TestResultsCollector.saveToFile(testResultFile.getAbsolutePath(), testResultsCollector); logger.info("Results stored to " + testResultFile.getAbsolutePath()); } catch (Exception e) { logger.error("Results cannot be stored to " + testResultFile.getAbsolutePath()); e.printStackTrace(); } } else { logger.info("DryRun option active"); } }
public void start() { boolean running = true; experimentAgenda = new ArrayList<Test>(); if (regression) { try { experimentAgenda.addAll(regression()); } catch (TestExecutionException e) { logger.warn("Problems during the regression", e); } } experimentAgenda.addAll(generateInitialTestSuite()); if (!dryrun) { if (bootstrap) { try { bootstrap(); } catch (TestExecutionException e) { logger.warn("Problems during the bootstrap", e); } } while (running) { try { logger.info("IterImpl.start() Scheduling : " + experimentAgenda.size() + " experiments to run."); scheduleAndRunExperiments(experimentAgenda); } catch (InterruptedException e) { logger.warn("Interrupted execution. Exit"); running = false; break; } logger.info("IterImpl.start() Experiments that remains to run or must be repeated: " + experimentAgenda.size()); Collection<Test> newExperiments = null; try { newExperiments = testSuiteEvolver.evolveTestSuite(testSuite, testResultsCollector.getTestResults()); } catch (Exception e) { logger.warn("Error during test suite evolution. Continue", e); } experimentAgenda.addAll(newExperiments); if (experimentAgenda.size() == 0) { logger.info("There are no more tests to run !"); running = false; } } try { TestResultsCollector.saveToFile(testResultFile.getAbsolutePath(), testResultsCollector); logger.info("Results stored to " + testResultFile.getAbsolutePath()); } catch (Exception e) { logger.error("Results cannot be stored to " + testResultFile.getAbsolutePath()); e.printStackTrace(); } } else { logger.info("DryRun option active"); } }
|
api-misuse-repair-complete_data_58
|
private void tryToMove(int space) { if (!startedMove) { onNotStartedMove(space); } else { onStartedMove(space); } if (finishedMove) { onFinishedMove(); } }
private void tryToMove(int space) { if (!startedMove) { if (capturedOnce && presenter.checkCapturePossibility(space)) onNotStartedMove(space); else { if (!capturedOnce) onNotStartedMove(space); else JOptionPane.showMessageDialog($$$getRootComponent$$$(), "Movimento inválido."); } } else { onStartedMove(space); } if (finishedMove) { onFinishedMove(); } }
|
api-misuse-repair-complete_data_59
|
public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("customer.xml"); CustomerDaoImpl cdi = (CustomerDaoImpl) app.getBean("customerBean"); Customer cust = new Customer(2, "sam", 26); System.out.println("success!"); Customer result = cdi.findById(2); System.out.println(result.getName()); }
public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("customer.xml"); CustomerDaoImpl cdi = (CustomerDaoImpl) app.getBean("customerBean"); JdbcSupportExm jse = (JdbcSupportExm) app.getBean("jdbcSupport"); Customer cust = new Customer(4, "Liyam", 28); jse.insert(cust); System.out.println("success!"); Customer result = cdi.findById(2); System.out.println(result.getName()); }
|
api-misuse-repair-complete_data_60
|
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { File theDir = new File(location); if (!theDir.exists()) { try { FileWriter writer = new FileWriter(theDir); writer.close(); } catch (IOException e) { e.printStackTrace(); } } Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (!(sender instanceof Player)) { sender.sendMessage("This command does not support console useage."); return true; } PlayerProfile PP = Users.getProfile(player); if (args.length < 1) { player.sendMessage("Usage is /deity create"); player.sendMessage("/deity remove"); player.sendMessage("/deity worship"); player.sendMessage("/deity leave"); player.sendMessage("/deity list"); return true; } if (args[0].equals("create")) { if (player != null && !mcPermissions.getInstance().mmoedit(player)) { sender.sendMessage("This command requires permissions. Only Admins may create deities"); return true; } if (args.length > 6) { player.sendMessage(ChatColor.RED + " Usage: /deity create deityname PositiveSkill PositiveSkill NegativeSkill NegativeSkill"); return true; } if (!Skills.isSkill(args[2]) || !Skills.isSkill(args[3]) || !Skills.isSkill(args[4]) || !Skills.isSkill(args[5])) { player.sendMessage(ChatColor.RED + " Usage: /deity create deityname PositiveSkill PositiveSkill NegativeSkill NegativeSkill"); return true; } else { try { FileWriter file = new FileWriter(location, true); BufferedWriter out = new BufferedWriter(file); out.append(args[1] + ":"); out.append(args[2] + ":"); out.append(args[3] + ":"); out.append(args[4] + ":"); out.append(args[5] + ":"); out.close(); } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } player.sendMessage("You have created a deity"); } } else if (args[0].equals("worship")) { if (args.length > 2) { player.sendMessage(ChatColor.RED + "Usage is /deity worship <deityname>"); return true; } if (!PP.getDeityName().equals("")) { player.sendMessage("You must first leave your current deity"); return true; } else { try { FileReader file = new FileReader(location); Scanner src = new Scanner(file); src.useDelimiter(":"); while (src.hasNext()) { if (src.next().equals(args[1])) { Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); PP.setDeityName(args[1]); file.close(); player.sendMessage("You have started worshiping " + args[1]); return true; } } player.sendMessage("That deity does not exist"); return true; } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } } } else if (args[0].equals("leave")) { if (args.length > 2) { player.sendMessage(ChatColor.RED + "Usage is /deity leave"); return true; } if (PP.getDeityName().equals("")) { player.sendMessage("You must first have a deity to leave"); return true; } else { try { FileReader file = new FileReader(location); Scanner src = new Scanner(file); src.findInLine(PP.getDeityName()); if (src.hasNext()) { src.reset(); src.useDelimiter(":"); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); PP.setDeityName(""); file.close(); player.sendMessage("You have forsaken your deity"); return true; } else { player.sendMessage("That deity does not exist"); return true; } } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } } } else if (args[0].equals("list")) { try { FileReader file = new FileReader(location); Scanner src = new Scanner(file); src.reset(); src.useDelimiter(":"); while (src.hasNext()) { player.sendMessage(ChatColor.GOLD + src.next() + ChatColor.YELLOW + ": Positive Domains: " + ChatColor.BLUE + src.next() + ", " + src.next() + ChatColor.YELLOW + ", Neagtive Domains: " + ChatColor.RED + src.next() + ", " + src.next()); } return true; } catch (Exception e) { } } else if (args[0].equals("remove")) { if (player != null && !mcPermissions.getInstance().mmoedit(player)) { sender.sendMessage("This command requires permissions. Only Admins may create deities"); return true; } if (args.length > 2) { player.sendMessage(ChatColor.RED + "Usage is /deity remove <deityname>"); return true; } try { FileReader file = new FileReader(location); BufferedReader in = new BufferedReader(file); StringBuilder writer = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { if (!line.split(":")[0].equalsIgnoreCase(args[1])) { writer.append(line).append("\r\n"); } else { } } in.close(); FileWriter out = new FileWriter(location); out.write(writer.toString()); out.close(); } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } } else { player.sendMessage("Usage is /deity create"); player.sendMessage("/deity remove"); player.sendMessage("/deity worship"); player.sendMessage("/deity leave"); player.sendMessage("/deity list"); return true; } return true; }
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { File theDir = new File(location); if (!theDir.exists()) { try { FileWriter writer = new FileWriter(theDir); writer.close(); } catch (IOException e) { e.printStackTrace(); } } Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (!(sender instanceof Player)) { sender.sendMessage("This command does not support console useage."); return true; } PlayerProfile PP = Users.getProfile(player); if (args.length < 1) { player.sendMessage("Usage is /deity create"); player.sendMessage("/deity remove"); player.sendMessage("/deity worship"); player.sendMessage("/deity leave"); player.sendMessage("/deity list"); return true; } if (args[0].equals("create")) { if (player != null && !mcPermissions.getInstance().mmoedit(player)) { sender.sendMessage("This command requires permissions. Only Admins may create deities"); return true; } if (args.length != 6) { player.sendMessage(ChatColor.RED + " Usage: /deity create deityname PositiveSkill PositiveSkill NegativeSkill NegativeSkill"); return true; } if (!Skills.isSkill(args[2]) || !Skills.isSkill(args[3]) || !Skills.isSkill(args[4]) || !Skills.isSkill(args[5])) { player.sendMessage(ChatColor.RED + " Usage: /deity create deityname PositiveSkill PositiveSkill NegativeSkill NegativeSkill"); return true; } else { try { FileWriter file = new FileWriter(location, true); BufferedWriter out = new BufferedWriter(file); out.append(args[1] + ":"); out.append(args[2] + ":"); out.append(args[3] + ":"); out.append(args[4] + ":"); out.append(args[5] + ":"); out.close(); } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } player.sendMessage("You have created a deity"); } } else if (args[0].equals("worship")) { if (args.length > 2) { player.sendMessage(ChatColor.RED + "Usage is /deity worship <deityname>"); return true; } if (!PP.getDeityName().equals("")) { player.sendMessage("You must first leave your current deity"); return true; } else { try { FileReader file = new FileReader(location); Scanner src = new Scanner(file); src.useDelimiter(":"); while (src.hasNext()) { if (src.next().equals(args[1])) { Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); PP.setDeityName(args[1]); file.close(); player.sendMessage("You have started worshiping " + args[1]); return true; } } player.sendMessage("That deity does not exist"); return true; } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } } } else if (args[0].equals("leave")) { if (args.length > 2) { player.sendMessage(ChatColor.RED + "Usage is /deity leave"); return true; } if (PP.getDeityName().equals("")) { player.sendMessage("You must first have a deity to leave"); return true; } else { try { FileReader file = new FileReader(location); Scanner src = new Scanner(file); src.findInLine(PP.getDeityName()); if (src.hasNext()) { src.reset(); src.useDelimiter(":"); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), -LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); Users.getProfile(player).addLevels(Skills.getSkillType(src.next()), LoadProperties.deityBonus); PP.setDeityName(""); file.close(); player.sendMessage("You have forsaken your deity"); return true; } else { player.sendMessage("That deity does not exist"); return true; } } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } } } else if (args[0].equals("list")) { try { FileReader file = new FileReader(location); Scanner src = new Scanner(file); src.reset(); src.useDelimiter(":"); while (src.hasNext()) { player.sendMessage(ChatColor.GOLD + src.next() + ChatColor.YELLOW + ": Positive Domains: " + ChatColor.BLUE + src.next() + ", " + src.next() + ChatColor.YELLOW + ", Neagtive Domains: " + ChatColor.RED + src.next() + ", " + src.next()); } return true; } catch (Exception e) { } } else if (args[0].equals("remove")) { if (player != null && !mcPermissions.getInstance().mmoedit(player)) { sender.sendMessage("This command requires permissions. Only Admins may create deities"); return true; } if (args.length > 2) { player.sendMessage(ChatColor.RED + "Usage is /deity remove <deityname>"); return true; } try { FileReader file = new FileReader(location); BufferedReader in = new BufferedReader(file); StringBuilder writer = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null) { if (!line.split(":")[0].equalsIgnoreCase(args[1])) { writer.append(line).append("\r\n"); } else { } } in.close(); FileWriter out = new FileWriter(location); out.write(writer.toString()); out.close(); } catch (Exception e) { Bukkit.getLogger().severe("Exception while writing to " + location + " (Are you sure you formatted it correctly?)" + e.toString()); } } else { player.sendMessage("Usage is /deity create"); player.sendMessage("/deity remove"); player.sendMessage("/deity worship"); player.sendMessage("/deity leave"); player.sendMessage("/deity list"); return true; } return true; }
|
api-misuse-repair-complete_data_61
|
public boolean isEmpty() { return (internalList.get(0) == null) ? true : false; }
public boolean isEmpty() { return (internalList.size() == 0) ? true : false; }
|
api-misuse-repair-complete_data_62
|
public static void replaceAllSpaceCharComic() { File flist = new File("./" + Config.defaultSavePath); for (File f : flist.listFiles()) { if (f.isDirectory() && f.getName().indexOf(' ') != -1) { f.renameTo(new File(f.getParentFile().getPath(), f.getName().replaceAll(" ", ""))); } } }
public static void replaceAllSpaceCharComic() { File[] flist = new File("./" + Config.defaultSavePath).listFiles(); if (flist == null) { return; } for (File f : flist) { if (f.isDirectory() && f.getName().indexOf(' ') != -1) { f.renameTo(new File(f.getParentFile().getPath(), f.getName().replaceAll(" ", ""))); } } }
|
api-misuse-repair-complete_data_63
|
public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); MonitorDataPostProcessor proc = ctx.getBean(MonitorDataPostProcessor.class); Client client = ctx.getBean(Client.class); client.useTube("data.reading"); while (true) { Job job = client.reserve(10); if (null == job) { continue; } else { String content = Serializer.byteArrayToSerializable(job.getData()).toString(); try { proc.exec(content); client.delete(job.getJobId()); } catch (Exception e) { logger.error(String.format("Failed to process job with content:%s!", content), e); } } } }
public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); MonitorDataPostProcessor proc = ctx.getBean(MonitorDataPostProcessor.class); Client client = ctx.getBean(Client.class); client.watch("data.reading"); while (true) { Job job = client.reserve(10); if (null == job) { continue; } else { String content = Serializer.byteArrayToSerializable(job.getData()).toString(); try { proc.exec(content); client.delete(job.getJobId()); } catch (Exception e) { logger.error(String.format("Failed to process job with content:%s!", content), e); } } } }
|
api-misuse-repair-complete_data_64
|
public Element invoke(String operationName, Element mesg, Map<String, Object> headers) throws Exception { mesg = WSDLHelper.unwrapMessagePart(mesg); SynchronousInOutHandler rh = new SynchronousInOutHandler(); Exchange exchange = _serviceReference.createExchange(operationName, rh); Message req = exchange.createMessage(); req.setContent(mesg); if (headers != null) { Set<String> keys = headers.keySet(); for (String key : keys) { exchange.getContext(req).setProperty(key, headers.get(key)).addLabels(EndpointLabel.SOAP.label()); } headers.clear(); } exchange.send(req); try { exchange = rh.waitForOut(_waitTimeout); } catch (DeliveryException e) { throw BPELMessages.MESSAGES.timedOutAfterMsWaitingOnSynchronousResponseFromTargetService(_waitTimeout, _serviceReference.getName().toString()); } Message resp = exchange.getMessage(); if (resp == null) { throw BPELMessages.MESSAGES.responseNotReturnedFromOperationOnService(operationName, _serviceReference.getName().toString()); } for (org.switchyard.Property p : exchange.getContext().getProperties(Scope.MESSAGE)) { if (p.hasLabel(EndpointLabel.SOAP.label())) { headers.put(p.getName(), p.getValue()); } } if (resp.getContent() instanceof Exception && !(resp.getContent() instanceof BPELFault)) { throw (Exception) resp.getContent(); } Element respelem = (Element) resp.getContent(Node.class); javax.wsdl.Operation operation = _portType.getOperation(operationName, null, null); if (exchange.getState() == ExchangeState.FAULT) { QName faultCode = null; if (respelem instanceof SOAPFault) { SOAPFault fault = (SOAPFault) respelem; respelem = (Element) fault.getDetail().getFirstChild(); faultCode = fault.getFaultCodeAsQName(); } Element newfault = WSDLHelper.wrapFaultMessagePart(respelem, operation, null); throw new Fault(faultCode, newfault); } Element newresp = WSDLHelper.wrapResponseMessagePart(respelem, operation); return ((Element) newresp); }
public Element invoke(String operationName, Element mesg, Map<String, Object> headers) throws Exception { Node node = WSDLHelper.unwrapMessagePart(mesg); SynchronousInOutHandler rh = new SynchronousInOutHandler(); Exchange exchange = _serviceReference.createExchange(operationName, rh); Message req = exchange.createMessage(); req.setContent(node); if (headers != null) { Set<String> keys = headers.keySet(); for (String key : keys) { exchange.getContext(req).setProperty(key, headers.get(key)).addLabels(EndpointLabel.SOAP.label()); } headers.clear(); } exchange.send(req); try { exchange = rh.waitForOut(_waitTimeout); } catch (DeliveryException e) { throw BPELMessages.MESSAGES.timedOutAfterMsWaitingOnSynchronousResponseFromTargetService(_waitTimeout, _serviceReference.getName().toString()); } Message resp = exchange.getMessage(); if (resp == null) { throw BPELMessages.MESSAGES.responseNotReturnedFromOperationOnService(operationName, _serviceReference.getName().toString()); } for (org.switchyard.Property p : exchange.getContext().getProperties(Scope.MESSAGE)) { if (p.hasLabel(EndpointLabel.SOAP.label())) { headers.put(p.getName(), p.getValue()); } } if (resp.getContent() instanceof Exception && !(resp.getContent() instanceof BPELFault)) { throw (Exception) resp.getContent(); } Element respelem = (Element) resp.getContent(Node.class); javax.wsdl.Operation operation = _portType.getOperation(operationName, null, null); if (exchange.getState() == ExchangeState.FAULT) { QName faultCode = null; if (respelem instanceof SOAPFault) { SOAPFault fault = (SOAPFault) respelem; respelem = (Element) fault.getDetail().getFirstChild(); faultCode = fault.getFaultCodeAsQName(); } Element newfault = WSDLHelper.wrapFaultMessagePart(respelem, operation, null); throw new Fault(faultCode, newfault); } Element newresp = WSDLHelper.wrapResponseMessagePart(respelem, operation); return ((Element) newresp); }
|
api-misuse-repair-complete_data_65
|
public void handleAction(AbstractSyntaxToken syntaxToken, AbstractToken lexicalToken, int phase) { ActionToken actionToken = (ActionToken) syntaxToken; String key = StringUtilsPlus.generateMethodKey(actionToken.getValue(), phase); if (actionMethodMap.containsKey(key)) { ObjectMethod objectMethod = actionMethodMap.get(key); boolean actionClassStability = objectMethod.getObject().getClass().getAnnotation(SemanticAction.class).stable(); if (!actionClassStability || actionToken.isStable()) { try { SemanticContext semanticContext; if (phase == 1) { GenericModel model = null; if (modelMethodMap.containsKey(actionToken.getValue())) { model = (GenericModel) modelMethodMap.get(actionToken.getValue()).invoke(null); } if (model != null && model instanceof DataModel) { ((DataModel) model).setLexicalToken(lexicalToken); } SymbolTableGenericEntry entry = null; if (entryMethodMap.containsKey(actionToken.getValue())) { entry = (SymbolTableGenericEntry) entryMethodMap.get(actionToken.getValue()).invoke(null); entry.setModel(model); } semanticContext = new SemanticContext(); semanticContext.setModel(model); semanticContext.setEntry(entry); semanticContext.setSemanticContextListener(new SemanticContextListener() { @Override public void error(String message) { errorsList.add(message); l.info("Semantic Error: " + message); } @Override public void generateCode(SemanticContext semanticContext) { if (semanticHandlerListener != null) { semanticHandlerListener.generateCode(actionToken, phase, semanticContext, symbolTableTree); } } }); semanticContextsQueue.offer(semanticContext); } else { semanticContext = semanticContextsQueue.poll(); semanticContextsQueue.offer(semanticContext); } objectMethod.getMethod().invoke(objectMethod.getObject(), semanticContext, semanticStack, symbolTableTree); } catch (IllegalAccessException | InvocationTargetException e) { l.error(e.getMessage()); } } else { l.warn("Skipping semantic action call for '" + actionToken.getValue() + "' because the parser is in error recovery mode (unstable)"); } } else { l.warn("Action: " + syntaxToken.getValue() + " at Phase: " + phase + " is not handled by any method."); } }
public void handleAction(AbstractSyntaxToken syntaxToken, AbstractToken lexicalToken, int phase) { ActionToken actionToken = (ActionToken) syntaxToken; String key = StringUtilsPlus.generateMethodKey(actionToken.getValue(), phase); if (actionMethodMap.containsKey(key)) { ObjectMethod objectMethod = actionMethodMap.get(key); boolean actionClassStability = objectMethod.getObject().getClass().getAnnotation(SemanticAction.class).stable(); if (!actionClassStability || actionToken.isStable()) { try { SemanticContext semanticContext; if (phase == 1) { GenericModel model = null; if (modelMethodMap.containsKey(actionToken.getValue())) { model = (GenericModel) modelMethodMap.get(actionToken.getValue()).invoke(null); } if (model != null && model instanceof DataModel) { ((DataModel) model).setLexicalToken(lexicalToken); } SymbolTableGenericEntry entry = null; if (entryMethodMap.containsKey(actionToken.getValue())) { entry = (SymbolTableGenericEntry) entryMethodMap.get(actionToken.getValue()).invoke(null); entry.setModel(model); } semanticContext = new SemanticContext(); semanticContext.setModel(model); semanticContext.setEntry(entry); semanticContext.setSemanticContextListener(new SemanticContextListener() { @Override public void error(String message) { errorsList.add(message); l.info("Semantic Error: " + message); } @Override public void generateCode(SemanticContext semanticContext) { if (semanticHandlerListener != null) { semanticHandlerListener.generateCode(actionToken, phase, semanticContext, symbolTableTree); } } }); semanticContextsQueue.offer(semanticContext); } else { semanticContext = semanticContextsQueue.poll(); semanticContextsQueue.offer(semanticContext); } objectMethod.getMethod().invoke(objectMethod.getObject(), semanticContext, semanticStack, symbolTableTree); } catch (IllegalAccessException | InvocationTargetException e) { l.error("Error invoking method for semantic action '" + actionToken.getValue() + "'"); } } else { l.warn("Skipping semantic action call for '" + actionToken.getValue() + "' because the parser is in error recovery mode (unstable)"); } } else { l.warn("Action: " + syntaxToken.getValue() + " at Phase: " + phase + " is not handled by any method."); } }
|
api-misuse-repair-complete_data_66
|
private void evalJointBreak() { if (palmJoint != null) { Vector2 v = palmJoint.getReactionForce(1.0f); float len = v.len(); if (len >= 0.45f && enableJointBreaking) { hand_l.body.getWorld().destroyJoint(palmJoint); palmJoint = null; enableJointBreaking = false; } else if (len <= 0.4f) { enableJointBreaking = true; } } }
private void evalJointBreak() { if (palmJoint != null) { Vector2 v = palmJoint.getReactionForce(1.0f); float len = v.len(); if (len >= 0.55f && enableJointBreaking && !dragging) { hand_l.body.getWorld().destroyJoint(palmJoint); palmJoint = null; enableJointBreaking = false; } else if (len <= 0.4f) { enableJointBreaking = true; } } }
|
api-misuse-repair-complete_data_67
|
private void processGenerationCandidateMethod(ExecutableElement attributeMethodCandidate) { Name name = attributeMethodCandidate.getSimpleName(); List<? extends VariableElement> parameters = attributeMethodCandidate.getParameters(); if (name.contentEquals(EQUALS_METHOD) && parameters.size() == 1 && parameters.get(0).asType().toString().equals(Object.class.getName()) && !attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT)) { type.isEqualToDefined = true; return; } if (name.contentEquals(HASH_CODE_METHOD) && parameters.isEmpty() && !attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT)) { type.isHashCodeDefined = true; return; } if (name.contentEquals(TO_STRING_METHOD) && parameters.isEmpty() && !attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT)) { type.isToStringDefined = true; return; } if (CheckMirror.isPresent(attributeMethodCandidate)) { if (attributeMethodCandidate.getReturnType().getKind() == TypeKind.VOID && attributeMethodCandidate.getParameters().isEmpty() && !attributeMethodCandidate.getModifiers().contains(Modifier.PRIVATE) && !attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT) && !attributeMethodCandidate.getModifiers().contains(Modifier.STATIC) && !attributeMethodCandidate.getModifiers().contains(Modifier.NATIVE)) { type.validationMethodName = attributeMethodCandidate.getSimpleName().toString(); } else { report(attributeMethodCandidate).error("Method '%s' annotated with @%s must be non-private parameter-less method and have void return type.", attributeMethodCandidate.getSimpleName(), CheckMirror.simpleName()); } } if (isDiscoveredAttribute(attributeMethodCandidate)) { TypeMirror returnType = resolveReturnType(attributeMethodCandidate); ValueAttribute attribute = new ValueAttribute(); boolean isFinal = isFinal(attributeMethodCandidate); boolean isAbstract = isAbstract(attributeMethodCandidate); boolean defaultAnnotationPresent = DefaultMirror.isPresent(attributeMethodCandidate); boolean derivedAnnotationPresent = DerivedMirror.isPresent(attributeMethodCandidate); if (isAbstract) { attribute.isGenerateAbstract = true; if (attributeMethodCandidate.getDefaultValue() != null) { attribute.isGenerateDefault = true; } else if (defaultAnnotationPresent) { report(attributeMethodCandidate).annotationNamed(DefaultMirror.simpleName()).error("@Value.Default should have initializer body", name); } else if (derivedAnnotationPresent) { report(attributeMethodCandidate).annotationNamed(DerivedMirror.simpleName()).error("@Value.Derived should have initializer body", name); } } else if (defaultAnnotationPresent && derivedAnnotationPresent) { report(attributeMethodCandidate).annotationNamed(DerivedMirror.simpleName()).error("Attribute '%s' cannot be both @Value.Default and @Value.Derived", name); attribute.isGenerateDefault = true; attribute.isGenerateDerived = false; } else if ((defaultAnnotationPresent || derivedAnnotationPresent) && isFinal) { report(attributeMethodCandidate).error("Annotated attribute '%s' will be overriden and cannot be final", name); } else if (defaultAnnotationPresent) { attribute.isGenerateDefault = true; } else if (derivedAnnotationPresent) { attribute.isGenerateDerived = true; } if (LazyMirror.isPresent(attributeMethodCandidate)) { if (isAbstract || isFinal) { report(attributeMethodCandidate).error("@Value.Lazy attribute '%s' must be non abstract and non-final", name); } else if (defaultAnnotationPresent || derivedAnnotationPresent) { report(attributeMethodCandidate).error("@Value.Lazy attribute '%s' cannot be @Value.Derived or @Value.Default", name); } else { attribute.isGenerateLazy = true; } } attribute.reporter = reporter; attribute.returnTypeName = computeReturnTypeString(returnType); attribute.returnType = returnType; attribute.names = styles.forAccessor(name.toString()); attribute.element = attributeMethodCandidate; attribute.containingType = type; attributes.add(attribute); } }
private void processGenerationCandidateMethod(ExecutableElement attributeMethodCandidate) { Name name = attributeMethodCandidate.getSimpleName(); List<? extends VariableElement> parameters = attributeMethodCandidate.getParameters(); if (name.contentEquals(EQUALS_METHOD) && parameters.size() == 1 && parameters.get(0).asType().toString().equals(Object.class.getName()) && !attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT)) { type.isEqualToDefined = true; return; } if (name.contentEquals(HASH_CODE_METHOD) && parameters.isEmpty()) { if (!attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT)) { type.isHashCodeDefined = true; } return; } if (name.contentEquals(TO_STRING_METHOD) && parameters.isEmpty()) { if (!attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT)) { type.isToStringDefined = true; } return; } if (CheckMirror.isPresent(attributeMethodCandidate)) { if (attributeMethodCandidate.getReturnType().getKind() == TypeKind.VOID && attributeMethodCandidate.getParameters().isEmpty() && !attributeMethodCandidate.getModifiers().contains(Modifier.PRIVATE) && !attributeMethodCandidate.getModifiers().contains(Modifier.ABSTRACT) && !attributeMethodCandidate.getModifiers().contains(Modifier.STATIC) && !attributeMethodCandidate.getModifiers().contains(Modifier.NATIVE)) { type.validationMethodName = attributeMethodCandidate.getSimpleName().toString(); } else { report(attributeMethodCandidate).error("Method '%s' annotated with @%s must be non-private parameter-less method and have void return type.", attributeMethodCandidate.getSimpleName(), CheckMirror.simpleName()); } } if (isDiscoveredAttribute(attributeMethodCandidate)) { TypeMirror returnType = resolveReturnType(attributeMethodCandidate); ValueAttribute attribute = new ValueAttribute(); boolean isFinal = isFinal(attributeMethodCandidate); boolean isAbstract = isAbstract(attributeMethodCandidate); boolean defaultAnnotationPresent = DefaultMirror.isPresent(attributeMethodCandidate); boolean derivedAnnotationPresent = DerivedMirror.isPresent(attributeMethodCandidate); if (isAbstract) { attribute.isGenerateAbstract = true; if (attributeMethodCandidate.getDefaultValue() != null) { attribute.isGenerateDefault = true; } else if (defaultAnnotationPresent) { report(attributeMethodCandidate).annotationNamed(DefaultMirror.simpleName()).error("@Value.Default should have initializer body", name); } else if (derivedAnnotationPresent) { report(attributeMethodCandidate).annotationNamed(DerivedMirror.simpleName()).error("@Value.Derived should have initializer body", name); } } else if (defaultAnnotationPresent && derivedAnnotationPresent) { report(attributeMethodCandidate).annotationNamed(DerivedMirror.simpleName()).error("Attribute '%s' cannot be both @Value.Default and @Value.Derived", name); attribute.isGenerateDefault = true; attribute.isGenerateDerived = false; } else if ((defaultAnnotationPresent || derivedAnnotationPresent) && isFinal) { report(attributeMethodCandidate).error("Annotated attribute '%s' will be overriden and cannot be final", name); } else if (defaultAnnotationPresent) { attribute.isGenerateDefault = true; } else if (derivedAnnotationPresent) { attribute.isGenerateDerived = true; } if (LazyMirror.isPresent(attributeMethodCandidate)) { if (isAbstract || isFinal) { report(attributeMethodCandidate).error("@Value.Lazy attribute '%s' must be non abstract and non-final", name); } else if (defaultAnnotationPresent || derivedAnnotationPresent) { report(attributeMethodCandidate).error("@Value.Lazy attribute '%s' cannot be @Value.Derived or @Value.Default", name); } else { attribute.isGenerateLazy = true; } } attribute.reporter = reporter; attribute.returnTypeName = computeReturnTypeString(returnType); attribute.returnType = returnType; attribute.names = styles.forAccessor(name.toString()); attribute.element = attributeMethodCandidate; attribute.containingType = type; attributes.add(attribute); } }
|
api-misuse-repair-complete_data_68
|
@SuppressWarnings({ "unchecked", "rawtypes" }) public static ISearchClient getSearchClient(AuthDescriptor ad) throws Exception { ISearchClient iSearchClient = null; log.info("Check Formal Parameter AuthDescriptor ..."); Assert.notNull(ad, "AuthDescriptor对象为空"); Assert.notNull(ad.getServiceId(), "service_id为空"); String srvId = ad.getServiceId(); String userPid = ad.getPid(); if (searchClients.containsKey(userPid + "_" + srvId)) { iSearchClient = searchClients.get(userPid + "_" + srvId); return iSearchClient; } AuthResult authResult = UserClientFactory.getUserClient().auth(ad); Assert.notNull(authResult.getUserId(), "UserId为空"); Assert.notNull(authResult.getConfigAddr(), "ConfigAddr为空"); Assert.notNull(authResult.getConfigUser(), "ConfigUser为空"); Assert.notNull(authResult.getConfigPasswd(), "ConfigPasswd为空"); log.info("Get confBase&conf ..."); String userId = authResult.getUserId(); ICCSComponent client = CCSComponentFactory.getConfigClient(authResult.getConfigAddr(), authResult.getConfigUser(), authResult.getConfigPasswd()); SesWatch watch = new SesWatch(client, userPid, userId, srvId); String personalConf = CCSComponentFactory.getConfigClient(authResult.getConfigAddr(), authResult.getConfigUser(), authResult.getConfigPasswd()).get(SEARCH_CONFIG_PATH + srvId); String mappingConf = CCSComponentFactory.getConfigClient(authResult.getConfigAddr(), authResult.getConfigUser(), authResult.getConfigPasswd()).get(SES_MAPPING_ZK_PATH + srvId, watch); Gson gson = new Gson(); Map<String, Object> personalConfMap = new HashMap<String, Object>(); Map<String, Object> mappingConfMap = new HashMap<String, Object>(); personalConfMap = gson.fromJson(personalConf, personalConfMap.getClass()); mappingConfMap = gson.fromJson(mappingConf, mappingConfMap.getClass()); String indexName = String.valueOf(Math.abs((authResult.getUserId() + srvId).hashCode())); String hosts = String.valueOf(personalConfMap.get(ELASTIC_HOST)); Map map = gson.fromJson(mappingConf, Map.class); JsonObject properties = gson.fromJson((String) map.get("mapping"), JsonObject.class).get(indexName).getAsJsonObject().get("properties").getAsJsonObject(); JsonObject idObj = gson.fromJson((String) map.get("mapping"), JsonObject.class).get(indexName).getAsJsonObject().get("_id").getAsJsonObject(); iSearchClient = new SearchClientImpl(hosts, indexName, properties, idObj.get("path").toString().replaceAll("\"", "")); searchClients.put(userPid + "_" + srvId, iSearchClient); return iSearchClient; }
@SuppressWarnings({ "unchecked", "rawtypes" }) public static ISearchClient getSearchClient(AuthDescriptor ad) throws Exception { ISearchClient iSearchClient = null; log.info("Check Formal Parameter AuthDescriptor ..."); Assert.notNull(ad, "AuthDescriptor对象为空"); Assert.notNull(ad.getServiceId(), "service_id为空"); String srvId = ad.getServiceId(); String userPid = ad.getPid(); if (searchClients.containsKey(userPid + "_" + srvId)) { iSearchClient = searchClients.get(userPid + "_" + srvId); return iSearchClient; } AuthResult authResult = UserClientFactory.getUserClient().auth(ad); Assert.notNull(authResult.getUserId(), "UserId为空"); Assert.notNull(authResult.getConfigAddr(), "ConfigAddr为空"); Assert.notNull(authResult.getConfigUser(), "ConfigUser为空"); Assert.notNull(authResult.getConfigPasswd(), "ConfigPasswd为空"); log.info("Get confBase&conf ..."); String userId = authResult.getUserId(); ICCSComponent client = CCSComponentFactory.getConfigClient(authResult.getConfigAddr(), authResult.getConfigUser(), authResult.getConfigPasswd()); SesWatch watch = new SesWatch(client, userPid, userId, srvId); String personalConf = CCSComponentFactory.getConfigClient(authResult.getConfigAddr(), authResult.getConfigUser(), authResult.getConfigPasswd()).get(SEARCH_CONFIG_PATH + srvId); String mappingConf = CCSComponentFactory.getConfigClient(authResult.getConfigAddr(), authResult.getConfigUser(), authResult.getConfigPasswd()).get(SES_MAPPING_ZK_PATH + srvId, watch); Gson gson = new Gson(); Map<String, Object> personalConfMap = new HashMap<String, Object>(); Map<String, Object> mappingConfMap = new HashMap<String, Object>(); personalConfMap = gson.fromJson(personalConf, personalConfMap.getClass()); mappingConfMap = gson.fromJson(mappingConf, mappingConfMap.getClass()); String indexName = String.valueOf(Math.abs((authResult.getUserId() + srvId).hashCode())); String hosts = String.valueOf(personalConfMap.get(ELASTIC_HOST)); Map map = gson.fromJson(mappingConf, Map.class); JsonObject properties = gson.fromJson((String) map.get("mapping"), JsonObject.class).get(indexName).getAsJsonObject().get("properties").getAsJsonObject(); String idConf = CCSComponentFactory.getConfigClient(authResult.getConfigAddr(), authResult.getConfigUser(), authResult.getConfigPasswd()).get(SEARCH_CONFIG_PATH + srvId + "/indexPK", watch); String id = null; if (StringUtil.isBlank(idConf)) { JsonObject idObj = gson.fromJson(idConf, JsonObject.class); id = null != idObj.get("indexPK") ? idObj.get("indexPK").getAsString() : null; } iSearchClient = new SearchClientImpl(hosts, indexName, properties, id); searchClients.put(userPid + "_" + srvId, iSearchClient); return iSearchClient; }
|
api-misuse-repair-complete_data_69
|
public static void main(String[] args) { final long start = System.currentTimeMillis(); a12 problem = new a12(); problem.solve(5); System.out.println(System.currentTimeMillis() - start + "ms"); }
public static void main(String[] args) { final long start = System.currentTimeMillis(); a12 problem = new a12(); problem.solve(500); System.out.println((System.currentTimeMillis() - start) / 100 + "ms"); }
|
api-misuse-repair-complete_data_70
|
private void parseColumnOption(final ComponentOption option) { GridComponentColumn column = new GridComponentColumn(option.getAtrributeValue("name")); String fields = option.getAtrributeValue("fields"); if (fields != null) { for (FieldDefinition field : parseFields(fields)) { column.addField(field); } } column.setExpression(option.getAtrributeValue("expression")); String columnWidth = option.getAtrributeValue("width"); if (columnWidth != null) { column.setWidth(Integer.valueOf(columnWidth)); } if (option.getAtrributeValue("link") != null) { column.setLink(Boolean.parseBoolean(option.getAtrributeValue("link"))); } if (option.getAtrributeValue("hidden") != null) { column.setHidden(Boolean.parseBoolean(option.getAtrributeValue("hidden"))); } columns.put(column.getName(), column); }
private void parseColumnOption(final ComponentOption option) { GridComponentColumn column = new GridComponentColumn(option.getAtrributeValue("name")); String fields = option.getAtrributeValue("fields"); if (fields != null) { for (FieldDefinition field : parseFields(fields, column)) { column.addField(field); } } column.setExpression(option.getAtrributeValue("expression")); String columnWidth = option.getAtrributeValue("width"); if (columnWidth != null) { column.setWidth(Integer.valueOf(columnWidth)); } if (option.getAtrributeValue("link") != null) { column.setLink(Boolean.parseBoolean(option.getAtrributeValue("link"))); } if (option.getAtrributeValue("hidden") != null) { column.setHidden(Boolean.parseBoolean(option.getAtrributeValue("hidden"))); } columns.put(column.getName(), column); }
|
api-misuse-repair-complete_data_71
|
private void hideCloakedPlayers(EntityLiving entity, EntityLivingBase target) { if (target == null) { return; } ItemStack targetLegs = target.getItemStackFromSlot(EntityEquipmentSlot.LEGS); if (targetLegs == null || targetLegs.getItem() instanceof ItemExosuitArmor) { return; } ItemExosuitArmor leggings = (ItemExosuitArmor) targetLegs.getItem(); if (!leggings.hasUpgrade(targetLegs, STEALTH.getItem())) { return; } IAttributeInstance iattributeinstance = entity.getEntityAttribute(SharedMonsterAttributes.FOLLOW_RANGE); double d0 = iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); d0 = d0 / 1.5D; List<Entity> list = entity.worldObj.getEntitiesWithinAABB(Entity.class, entity.getEntityBoundingBox().expand(d0, 4.0D, d0)); boolean foundPlayer = false; for (Entity mob : list) { if (mob == target) { foundPlayer = true; break; } } if (!foundPlayer) { entity.setAttackTarget(null); } }
private void hideCloakedPlayers(EntityLiving entity, EntityLivingBase target) { if (target == null) { return; } ItemStack targetLegs = target.getItemStackFromSlot(EntityEquipmentSlot.LEGS); if (targetLegs == null || !(targetLegs.getItem() instanceof ItemExosuitArmor)) { return; } ItemExosuitArmor leggings = (ItemExosuitArmor) targetLegs.getItem(); if (!leggings.hasUpgrade(targetLegs, STEALTH.getItem())) { return; } IAttributeInstance iattributeinstance = entity.getEntityAttribute(SharedMonsterAttributes.FOLLOW_RANGE); double d0 = (iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue()) / 1.5D; List<Entity> list = entity.worldObj.getEntitiesWithinAABB(Entity.class, entity.getEntityBoundingBox().expand(d0, 4.0D, d0)); boolean foundPlayer = false; for (Entity mob : list) { if (mob == target) { foundPlayer = true; break; } } if (!foundPlayer) { entity.setAttackTarget(null); } }
|
api-misuse-repair-complete_data_72
|
@Override public BinaryMaterial clone(BinaryMaterial material) { return binaryMaterialDAO.create(material.getTitle(), material.getContentType(), material.getContent(), material); }
@Override public BinaryMaterial clone(BinaryMaterial material) { return binaryMaterialController.createBinaryMaterial(material.getTitle(), material.getContentType(), material.getContent(), material); }
|
api-misuse-repair-complete_data_73
|
protected void runWithArguments(String[] args) { String estimated = null, reference = null; boolean help = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-r")) { reference = args[i + 1]; } if (args[i].equals("-e")) { estimated = args[i + 1]; } if (args[i].equals("-o")) { try { out = new PrintStream(args[i + 1]); } catch (FileNotFoundException e) { out = null; System.err.println(e.getLocalizedMessage()); } } if (args[i].equals("-c")) { char[] v = args[i + 1].toCharArray(); for (int j = 0; j < v.length; j++) { dashChars.add((int) v[j]); } System.err.println("Following characters are considered a dash: " + dashChars); } if (args[i].equals("-h")) { help = true; } } if (estimated == null || reference == null || out == null || help) { System.err.println("Usage: FastSP -r reference_alignment_file -e estimated_alignmet_file [-o output_file] [-c GAP_CHARS]"); System.err.println("Output: \n" + " SP-Score:\t number of shared homologies (aligned pairs) / total number of homologies in the reference alignment. \n" + " Modeler: \t number of shared homologies (aligned pairs) / total number of homologies in the estimated alignment. \n" + " SP-FN: \t 1 - SP-Score\n" + " SP-FP: \t 1 - Modeler\n" + " Compression: \t number of columns in the estimated alignment / number of columns in the reference alignment \n" + " TC: \t number of correctly aligned columns / total number of aligned columns in the reference alignment. \n"); System.exit(1); } run(reference, estimated); if (swapped) { long tmp = totalHomologies; totalHomologies = totalHomologiesInEsitmated; totalHomologiesInEsitmated = tmp; tmp = effectiveRefColumns; effectiveRefColumns = effectiveEstColumns; effectiveEstColumns = tmp; } System.err.println("Number of shared homologies: " + sharedHomologies); System.err.println("Number of homologies in the reference alignment: " + totalHomologies); System.err.println("Number of homologies in the estimated alignment: " + totalHomologiesInEsitmated); System.err.println("Number of correctly aligned columns: " + correctColumns); System.err.println("Number of aligned columns in ref. alignment: " + effectiveRefColumns); out.println("SP-Score " + getSPScore()); out.println("Modeler " + getModeler()); out.println("SPFN " + getSPFN()); out.println("SPFP " + getSPFP()); out.println("Compression " + getCompressionFactor()); out.println("TC " + getTC()); out.flush(); }
protected void runWithArguments(String[] args) { String estimated = null, reference = null; boolean help = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-r")) { reference = args[i + 1]; } if (args[i].equals("-e")) { estimated = args[i + 1]; } if (args[i].equals("-o")) { try { out = new PrintStream(args[i + 1]); } catch (FileNotFoundException e) { out = null; System.err.println(e.getLocalizedMessage()); } } if (args[i].equals("-c")) { char[] v = args[i + 1].toCharArray(); for (int j = 0; j < v.length; j++) { dashChars.add((int) v[j]); } System.err.println("Following characters are considered a dash: " + dashChars); } if (args[i].equals("-h")) { help = true; } } if (estimated == null || reference == null || out == null || help) { System.err.println("FastSp version " + this.VERSION + " develped by Siavash Mirarab and Tandy Warnow at UT at Austin\n\n" + "Usage: FastSP -r reference_alignment_file -e estimated_alignmet_file [-o output_file] [-c GAP_CHARS]"); System.err.println("Output: \n" + " SP-Score:\t number of shared homologies (aligned pairs) / total number of homologies in the reference alignment. \n" + " Modeler: \t number of shared homologies (aligned pairs) / total number of homologies in the estimated alignment. \n" + " SP-FN: \t 1 - SP-Score\n" + " SP-FP: \t 1 - Modeler\n" + " Compression: \t number of columns in the estimated alignment / number of columns in the reference alignment \n" + " TC: \t number of correctly aligned columns / total number of aligned columns in the reference alignment. \n"); System.exit(1); } run(reference, estimated); if (swapped) { long tmp = totalHomologies; totalHomologies = totalHomologiesInEsitmated; totalHomologiesInEsitmated = tmp; tmp = effectiveRefColumns; effectiveRefColumns = effectiveEstColumns; effectiveEstColumns = tmp; } System.err.println("Number of shared homologies: " + sharedHomologies); System.err.println("Number of homologies in the reference alignment: " + totalHomologies); System.err.println("Number of homologies in the estimated alignment: " + totalHomologiesInEsitmated); System.err.println("Number of correctly aligned columns: " + correctColumns); System.err.println("Number of aligned columns in ref. alignment: " + effectiveRefColumns); out.println("SP-Score " + getSPScore()); out.println("Modeler " + getModeler()); out.println("SPFN " + getSPFN()); out.println("SPFP " + getSPFP()); out.println("Compression " + getCompressionFactor()); out.println("TC " + getTC()); out.flush(); }
|
api-misuse-repair-complete_data_74
|
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); addressSearch = (EditText) this.findViewById(R.id.addressSearch); searchButton = (Button) this.findViewById(R.id.searchButton); Log.d("ACA", "Button is: " + (searchButton == null ? "NULL" : "NOT NULL")); resultTextView = (TextView) this.findViewById(R.id.resultTextView); geocoder = new Geocoder(this, Locale.getDefault()); Context context = getApplicationContext(); CharSequence text = "You must enter a valid City and State or Zip code."; int duration = Toast.LENGTH_SHORT; invalidSearchToast = Toast.makeText(context, text, duration); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { hideSoftKeyboard(getParent()); String searchText = addressSearch.getText().toString(); Address location; if (searchText.equals("")) { invalidSearchToast.show(); } else { try { location = geocoder.getFromLocationName(searchText.toString(), 1).get(0); resultTextView.setText("Latitude: " + location.getLatitude() + "\n" + "Longitude: " + location.getLongitude() + "\n" + "State: " + location.getAdminArea()); Intent apiServiceIntent = new Intent(getApplicationContext(), ApiService.class); startService(apiServiceIntent); } catch (IOException e) { e.printStackTrace(); invalidSearchToast.show(); } } } }; searchButton.setOnClickListener(listener); }
@Override protected void onCreate(Bundle savedInstanceState) { final Activity self = this; super.onCreate(savedInstanceState); setContentView(R.layout.main); addressSearch = (EditText) this.findViewById(R.id.addressSearch); searchButton = (Button) this.findViewById(R.id.searchButton); Log.d("ACA", "Button is: " + (searchButton == null ? "NULL" : "NOT NULL")); resultTextView = (TextView) this.findViewById(R.id.resultTextView); geocoder = new Geocoder(this, Locale.getDefault()); Context context = getApplicationContext(); CharSequence text = "You must enter a valid City and State or Zip code."; int duration = Toast.LENGTH_SHORT; invalidSearchToast = Toast.makeText(context, text, duration); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { hideSoftKeyboard(self); String searchText = addressSearch.getText().toString(); Address location; if (searchText.equals("")) { invalidSearchToast.show(); } else { try { location = geocoder.getFromLocationName(searchText.toString(), 1).get(0); resultTextView.setText("Latitude: " + location.getLatitude() + "\n" + "Longitude: " + location.getLongitude() + "\n" + "State: " + location.getAdminArea()); Intent apiServiceIntent = new Intent(getApplicationContext(), ApiService.class); startService(apiServiceIntent); } catch (IOException e) { e.printStackTrace(); invalidSearchToast.show(); } } } }; searchButton.setOnClickListener(listener); }
|
api-misuse-repair-complete_data_75
|
@Override public void setProcesses() { addState(new DriveStraightForward(this, 0.2, 4085)); addState(new TurnRight(this, 0.2, 1281)); addState(new RaiseArm(this, 0.5, 215)); addState(new ExtendArm(this, 0.5, 1290)); addState(new LeftGrabber(this, 0.5, 500)); addState(new DriveStraightForward(this, 0.5, 430)); }
@Override public void setProcesses() { addState(new DriveStraightForward(this, 0.2, 4085)); addState(new TurnRight(this, 0.2, 1281)); addState(new RaiseArm(this, 0.5, 215)); addState(new ExtendArm(this, 0.5, 1290)); addState(new LeftGrabber(this, 0.5, 215)); addState(new DriveStraightForward(this, 0.5, -430)); }
|
api-misuse-repair-complete_data_76
|
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == REQ_CODE_PICK_PICTURE) { ClipData clipData = data.getClipData(); int total = 0; Uri uri = null; if (clipData == null) { uri = data.getData(); total = 1; } else { total = clipData.getItemCount(); } for (int i = 0; i < total; i++) { if (clipData != null) { uri = clipData.getItemAt(i).getUri(); } final Uri imageUri = uri; final String imagePath = imageUri.getPath(); final DatabaseReference mReference = myRef.child(mAlbumKey).child("filelist"); final StorageReference albumReference = storageRef.child(mAlbumKey); StorageReference imageRef = albumReference.child(uri.getLastPathSegment()); final int count = i + 1; final int totalCount = total; BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; Bitmap src = null; try { src = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, options); } catch (Exception e) { } float ratio = (float) src.getHeight() / (float) src.getWidth(); Bitmap resized = Bitmap.createScaledBitmap(src, 100, (int) (100.0 * ratio), true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resized.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] bytes = baos.toByteArray(); UploadTask uploadTask = imageRef.putBytes(bytes); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { TextView progressView = (TextView) findViewById(R.id.progress); progressView.setVisibility(View.GONE); Uri downloadUrl = taskSnapshot.getDownloadUrl(); DatabaseReference r = mReference.push(); String filename = taskSnapshot.getMetadata().getName(); r.child("url").setValue(downloadUrl.toString()); r.child("filename").setValue(filename); r.child("owner").setValue(mUser.getUid()); if (mThumbnail != null) if (mThumbnail.equals("DEFALUT")) { mAlbumRef.child("thumbnail").setValue(downloadUrl.toString()); } albumList.add(downloadUrl.toString()); gridAdapter.notifyDataSetChanged(); } }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { TextView progressView = (TextView) findViewById(R.id.progress); progressView.setVisibility(View.VISIBLE); double progress = 100.0 * count * (taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()) / totalCount; System.out.println("Upload is " + progress + "% done"); progressView.setText("업로딩: " + progress + "%"); } }); } } } super.onActivityResult(requestCode, resultCode, data); }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == REQ_CODE_PICK_PICTURE) { ClipData clipData = data.getClipData(); int total = 0; Uri uri = null; if (clipData == null) { uri = data.getData(); total = 1; } else { total = clipData.getItemCount(); } for (int i = 0; i < total; i++) { if (clipData != null) { uri = clipData.getItemAt(i).getUri(); } final Uri imageUri = uri; final String imagePath = imageUri.getPath(); final DatabaseReference mReference = myRef.child(mAlbumKey).child("filelist"); final StorageReference albumReference = storageRef.child(mAlbumKey); StorageReference imageRef = albumReference.child(uri.getLastPathSegment()); final int count = i + 1; final int totalCount = total; BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; Bitmap src = null; try { src = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, options); } catch (Exception e) { } float ratio = (float) src.getHeight() / (float) src.getWidth(); Bitmap resized = Bitmap.createScaledBitmap(src, 100, (int) (100.0 * ratio), true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resized.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] bytes = baos.toByteArray(); UploadTask uploadTask = imageRef.putBytes(bytes); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { TextView progressView = (TextView) findViewById(R.id.progress); progressView.setVisibility(View.GONE); Uri downloadUrl = taskSnapshot.getDownloadUrl(); DatabaseReference r = mReference.push(); String filename = taskSnapshot.getMetadata().getName(); r.child("url").setValue(downloadUrl.toString()); r.child("filename").setValue(filename); r.child("owner").setValue(mUser.getUid()); if ("DEFALUT".equals(mThumbnail)) { myRef.child(mAlbumKey).child("thumbnail").setValue(downloadUrl.toString()); } albumList.add(downloadUrl.toString()); gridAdapter.notifyDataSetChanged(); } }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { TextView progressView = (TextView) findViewById(R.id.progress); progressView.setVisibility(View.VISIBLE); double progress = 100.0 * count * (taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()) / totalCount; System.out.println("Upload is " + progress + "% done"); progressView.setText("업로딩: " + progress + "%"); } }); } } } super.onActivityResult(requestCode, resultCode, data); }
|
api-misuse-repair-complete_data_77
|
public Map<String, Object> process(final Map<String, Object> local, final List<String> flowArgs) { HashMap<String, Object> output = Maps.newHashMap(local); SpringStepContext stepContext = new SpringStepContext(flowArgs, local); ExpressionParser parser = new SpelExpressionParser(); for (Assignment that : assignments) { Expression e = parser.parseExpression(that.getExpression()); EvaluationContext c = new StandardEvaluationContext(stepContext); Object value = e.getValue(c); logger.trace("parsing [" + that + "] with result +[" + value + "]"); if (output.containsKey(that.getAssignTo())) { throw new IllegalArgumentException("Cannot overwrite existing local variable [" + that.getAssignTo() + "]"); } output.put(that.getAssignTo(), value); } ; return output; }
public Map<String, Object> process(final Map<String, Object> local, final List<String> flowArgs) { HashMap<String, Object> output = Maps.newHashMap(local); SpringStepContext stepContext = new SpringStepContext(flowArgs, local); ExpressionParser parser = new SpelExpressionParser(); for (Assignment that : assignments) { Expression e = parser.parseExpression(that.getExpression()); StandardEvaluationContext c = new StandardEvaluationContext(stepContext); stepContext.assignVariables(c); Object value = e.getValue(c); logger.trace("parsing [" + that + "] with result +[" + value + "]"); if (output.containsKey(that.getAssignTo())) { throw new IllegalArgumentException("Cannot overwrite existing local variable [" + that.getAssignTo() + "]"); } output.put(that.getAssignTo(), value); } ; return output; }
|
api-misuse-repair-complete_data_78
|
public void pruneTrees(int height) { for (int i = 0; i < this.nextPopulation.size(); i++) { if (this.nextPopulation.get(i).getRoot().getDepth() <= height) { this.nextPopulation.remove(i); } } }
public void pruneTrees(int height) { ArrayList<EcTree> pruned = new ArrayList<EcTree>(); for (int i = 0; i < this.nextPopulation.size(); i++) { if (this.nextPopulation.get(i).getRoot().getDepth() > height) { pruned.add(this.nextPopulation.get(i)); } } this.setNextPopulation(pruned); }
|
api-misuse-repair-complete_data_79
|
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); UpdaterDialog = new PanterDialog(DialogActivity.this); mNoUpdate = new PromptDialog(this); ActivityCompat.requestPermissions(DialogActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 100); if (isOnline(this)) { if (!isVersionValid(UpdaterUri())) { Url = "https://raw.githubusercontent.com/Grace5921/OtaUpdater/master/Updater.xml"; } else { Url = UpdaterUri(); } RomUpdaterUtils romUpdaterUtils = new RomUpdaterUtils(this).setUpdateFrom(UpdateFrom.XML).setUpdateXML(Url).withListener(new RomUpdaterUtils.UpdateListener() { @Override public void onSuccess(final Update update, Boolean isUpdateAvailable) { if (Showlog().equals(true)) ; { Log.d(Tag, "Update Found"); Log.d(Tag, update.getLatestVersion() + ", " + update.getUrlToDownload() + ", " + Boolean.toString(isUpdateAvailable)); } if (isUpdateAvailable == false) { mProgressBar.setVisibility(View.GONE); if (Showlog().equals(true)) ; { Log.i(Tag, "No update found " + valueOf(isUpdateAvailable)); } mNoUpdate.setTitle("No Updates Found"); mNoUpdate.setDialogType(PromptDialog.DIALOG_TYPE_WRONG).setAnimationEnable(true).setTitleText("No update found").setContentText("Try again later").setPositiveListener("Ok", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { mNoUpdate.dismiss(); finish(); } }).show(); } if (isUpdateAvailable == true) { mProgressBar.setVisibility(View.GONE); UpdaterDialog.setTitle("Update Found").setHeaderBackground(R.color.colorPrimaryDark).setMessage("Changelog :- \n\n" + update.getReleaseNotes()).setPositive("Download", new View.OnClickListener() { @Override public void onClick(View view) { uri = Uri.parse(valueOf(update.getUrlToDownload())); DownloadFileName = uri.getLastPathSegment(); Downloader(DialogActivity.this); UpdaterDialog.dismiss(); } }).setNegative("DISMISS", new View.OnClickListener() { @Override public void onClick(View view) { finish(); UpdaterDialog.dismiss(); } }).isCancelable(false).withAnimation(Animation.SIDE).show(); if (Showlog().equals(true)) ; { Log.d("Found", valueOf(update.getUrlToDownload())); } } } @Override public void onFailed(RomUpdaterError error) { if (Showlog().equals(true)) ; { Log.d("RomUpdater", "Something went wrong"); } } }); romUpdaterUtils.start(); } else { mProgressBar.setVisibility(View.GONE); mNoUpdate.setTitle("No network found"); mNoUpdate.setDialogType(PromptDialog.DIALOG_TYPE_WRONG).setAnimationEnable(true).setTitleText("No network found").setContentText("Please connect to network").setPositiveListener("Ok", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { mNoUpdate.dismiss(); finish(); } }).show(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dialog); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); UpdaterDialog = new PanterDialog(DialogActivity.this); mNoUpdate = new PromptDialog(this); ActivityCompat.requestPermissions(DialogActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 100); if (isOnline(this)) { if (!isVersionValid(UpdaterUri())) { Url = "https://raw.githubusercontent.com/Grace5921/OtaUpdater/master/Updater.xml"; } else { Url = UpdaterUri(); } RomUpdaterUtils romUpdaterUtils = new RomUpdaterUtils(this).setUpdateFrom(UpdateFrom.XML).setUpdateXML(Url).withListener(new RomUpdaterUtils.UpdateListener() { @Override public void onSuccess(final Update update, Boolean isUpdateAvailable) { if (Showlog().equals(true)) ; { Log.d(Tag, "Update Found"); Log.d(Tag, update.getLatestVersion() + ", " + update.getUrlToDownload() + ", " + Boolean.toString(isUpdateAvailable)); } if (isUpdateAvailable == false) { mProgressBar.setVisibility(View.GONE); if (Showlog().equals(true)) ; { Log.i(Tag, "No update found " + valueOf(isUpdateAvailable)); } mNoUpdate.setTitle("No Updates Found"); mNoUpdate.setDialogType(PromptDialog.DIALOG_TYPE_WRONG).setAnimationEnable(true).setTitleText("No update found").setContentText("Try again later").setPositiveListener("Ok", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { mNoUpdate.dismiss(); finish(); } }).show(); } if (isUpdateAvailable == true) { mProgressBar.setVisibility(View.GONE); UpdaterDialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); UpdaterDialog.dismiss(); } return true; } }); UpdaterDialog.setTitle("Update Found").setHeaderBackground(R.color.colorPrimaryDark).setMessage("Changelog :- \n\n" + update.getReleaseNotes()).setPositive("Download", new View.OnClickListener() { @Override public void onClick(View view) { uri = Uri.parse(valueOf(update.getUrlToDownload())); DownloadFileName = uri.getLastPathSegment(); Downloader(DialogActivity.this); UpdaterDialog.dismiss(); } }).setNegative("DISMISS", new View.OnClickListener() { @Override public void onClick(View view) { finish(); UpdaterDialog.dismiss(); } }).isCancelable(false).withAnimation(Animation.SIDE); try { UpdaterDialog.show(); } catch (WindowManager.BadTokenException Bt) { } if (Showlog().equals(true)) ; { Log.d("Found", valueOf(update.getUrlToDownload())); } } } @Override public void onFailed(RomUpdaterError error) { if (Showlog().equals(true)) ; { Log.d("RomUpdater", "Something went wrong"); } } }); romUpdaterUtils.start(); } else { mProgressBar.setVisibility(View.GONE); mNoUpdate.setTitle("No network found"); mNoUpdate.setDialogType(PromptDialog.DIALOG_TYPE_WRONG).setAnimationEnable(true).setTitleText("No network found").setContentText("Please connect to network").setPositiveListener("Ok", new PromptDialog.OnPositiveListener() { @Override public void onClick(PromptDialog dialog) { mNoUpdate.dismiss(); finish(); } }).show(); } }
|
api-misuse-repair-complete_data_80
|
private WebTarget computeTarget() { String serviceUrl = baseUrl; if (method.isAnnotationPresent(Path.class)) { serviceUrl += method.getAnnotation(Path.class).value(); } return client.target(replacePathParams(serviceUrl, method, parameter)); }
private WebTarget computeTarget() { String serviceUrl = baseUrl; if (method.isAnnotationPresent(Path.class)) { String path = method.getAnnotation(Path.class).value(); serviceUrl = computeUrl(serviceUrl, path); } return client.target(replacePathParams(serviceUrl, method, parameter)); }
|
api-misuse-repair-complete_data_81
|
@Override public void persist(Object entity) { int rs = getDbmDao().insert(entity); throwIfEffectiveCountError("persist", 1, rs); }
@Override public <T> void persist(T entity) { int rs = getDbmDao().insert(entity); throwIfEffectiveCountError("persist", 1, rs); }
|
api-misuse-repair-complete_data_82
|
public static void main(String[] args) { Scanner in = new Scanner(System.in); int d1 = in.nextInt(); int m1 = in.nextInt(); int y1 = in.nextInt(); int d2 = in.nextInt(); int m2 = in.nextInt(); int y2 = in.nextInt(); int fine = 0; if (d1 == d2 && m1 == m2 && y1 == y2) { fine = 0; } else if (d1 != d2 && m1 == m2 && y1 == y2) { fine = 15 * (d1 - d2); } else if (m1 != m2 && y1 == y2) { fine = 500 * (m1 - m2); } else if (y1 != y2) { fine = 10000; } System.out.println(fine); }
public static void main(String[] args) { Scanner in = new Scanner(System.in); int d1 = in.nextInt(); int m1 = in.nextInt(); int y1 = in.nextInt(); int d2 = in.nextInt(); int m2 = in.nextInt(); int y2 = in.nextInt(); int fine = 0; if (y1 > y2) { fine = 10000; } else if (m1 > m2 && y1 == y2) { fine = 500 * (m1 - m2); } else if (d1 > d2 && m1 == m2 && y1 == y2) { fine = 15 * (d1 - d2); } else { fine = 0; } System.out.println(fine); }
|
api-misuse-repair-complete_data_83
|
protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final HostActivity activity, final String ip) { Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan); startPortRangeScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { start.clearFocus(); stop.clearFocus(); int startPort = start.getValue(); int stopPort = stop.getValue(); if ((startPort - stopPort >= 0)) { Toast.makeText(getApplicationContext(), "Please pick a valid port range", Toast.LENGTH_SHORT).show(); return; } UserPreference.savePortRangeStart(activity, startPort); UserPreference.savePortRangeHigh(activity, stopPort); ports.clear(); scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme); scanProgressDialog.setCancelable(false); scanProgressDialog.setTitle("Scanning Port " + startPort + " to " + stopPort); scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); scanProgressDialog.setProgress(0); scanProgressDialog.setMax(stopPort - startPort + 1); scanProgressDialog.show(); Host.scanPorts(ip, startPort, stopPort, timeout, activity); } }); }
protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) { Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan); startPortRangeScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { start.clearFocus(); stop.clearFocus(); int startPort = start.getValue(); int stopPort = stop.getValue(); if ((startPort - stopPort >= 0)) { Toast.makeText(getApplicationContext(), "Please pick a valid port range", Toast.LENGTH_SHORT).show(); return; } UserPreference.savePortRangeStart(activity, startPort); UserPreference.savePortRangeHigh(activity, stopPort); ports.clear(); scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme); scanProgressDialog.setCancelable(false); scanProgressDialog.setTitle("Scanning Port " + startPort + " to " + stopPort); scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); scanProgressDialog.setProgress(0); scanProgressDialog.setMax(stopPort - startPort + 1); scanProgressDialog.show(); Host.scanPorts(ip, startPort, stopPort, timeout, activity); } }); }
|
api-misuse-repair-complete_data_84
|
public String convert(int numberToTransform) { if (numberToTransform > 999999999) { throw new IllegalArgumentException("number is > 999999999"); } return executeConversion(numberToTransform); }
public String convert(int numberToTransform) { if (numberToTransform > 999999999) { throw new IllegalArgumentException("number is > 999999999"); } else if (numberToTransform < 0) { throw new IllegalArgumentException("number is negative"); } return executeConversion(numberToTransform); }
|
api-misuse-repair-complete_data_85
|
public static boolean isExternalFunctionNameIdentifier(PsiElement e) { if (!psiIsA(e, GoLiteralIdentifier.class)) return false; GoLiteralIdentifier identifier = (GoLiteralIdentifier) e; if (identifier.isQualified()) return false; e = e.getParent(); if (!psiIsA(e, GoLiteralExpression.class)) return false; if (!psiIsA(e.getParent(), GoCallOrConvExpression.class)) return false; return e.getStartOffsetInParent() == 0; }
public static boolean isFunctionNameIdentifier(PsiElement e) { if (!psiIsA(e, GoLiteralExpression.class)) return false; GoLiteral literal = ((GoLiteralExpression) e).getLiteral(); if (!(literal instanceof GoLiteralIdentifier)) return false; if (((GoLiteralIdentifier) literal).isQualified()) return false; if (!psiIsA(e.getParent(), GoCallOrConvExpression.class)) return false; return e.getStartOffsetInParent() == 0; }
|
api-misuse-repair-complete_data_86
|
protected void sendRequest(JSONArray args, final CallbackContext callbackContext) { Log.i(TAG, "sendRequest called"); try { final RestRequest request = prepareRestRequest(args); final RestClient restClient = getRestClient(); if (restClient == null) { return; } restClient.sendAsync(request, new RestClient.AsyncRequestCallback() { @Override public void onSuccess(RestRequest request, RestResponse response) { try { final JSONObject responseAsJSON = response.asJSONObject(); callbackContext.success(responseAsJSON); } catch (Exception e) { Log.e(TAG, "sendRequest", e); onError(e); } } @Override public void onError(Exception exception) { callbackContext.error(exception.getMessage()); } }); } catch (Exception exception) { callbackContext.error(exception.getMessage()); } }
protected void sendRequest(JSONArray args, final CallbackContext callbackContext) { Log.i(TAG, "sendRequest called"); try { final RestRequest request = prepareRestRequest(args); final RestClient restClient = getRestClient(); if (restClient == null) { return; } restClient.sendAsync(request, new RestClient.AsyncRequestCallback() { @Override public void onSuccess(RestRequest request, RestResponse response) { try { final JSONObject responseAsJSON = response.asJSONObject(); callbackContext.success(responseAsJSON); } catch (Exception e) { Log.e(TAG, "Error while converting response to JSONObject", e); try { final String responseAsString = response.asString(); callbackContext.success(responseAsString); } catch (Exception ex) { Log.e(TAG, "Error while converting response to String", ex); } finally { if (response.isSuccess()) { callbackContext.success(); } else { onError(e); } } } } @Override public void onError(Exception exception) { callbackContext.error(exception.getMessage()); } }); } catch (Exception exception) { callbackContext.error(exception.getMessage()); } }
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 1