language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
7,329
2.984375
3
[]
no_license
package connectfour.gui; import connectfour.ConnectFourException; import connectfour.client.ConnectFourBoard; import connectfour.client.ConnectFourNetworkClient; import connectfour.client.Observer; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import java.util.List; /** * A JavaFX GUI for the networked Connect Four game. * * @author James Heloitis @ RIT CS * @author Sean Strout @ RIT CS * @author Cameron Riu */ public class ConnectFourGUI extends Application implements Observer<ConnectFourBoard>{ private ConnectFourBoard board; private ConnectFourNetworkClient client; private static final int COL = 6; private static final int ROW = 5; private Button[][] buttons; private Label turnLabel; private Label movesLeft; private Image p1; private Image p2; /** * Connect to the client, create the board instance, * implement all global variables * @throws ConnectFourException exception */ @Override public void init() throws ConnectFourException { try { // get the command line args List<String> args = getParameters().getRaw(); // get host info and port from command line String host = args.get(0); int port = Integer.parseInt(args.get(1)); this.board = new ConnectFourBoard(); this.board.addObserver(this); this.client = new ConnectFourNetworkClient(host, port, board); this.turnLabel = new Label(""); this.movesLeft = new Label(""); this.p1 = new Image(getClass().getResourceAsStream("p1black.png")); this.p2 = new Image(getClass().getResourceAsStream("p2red.png")); } catch(NumberFormatException e) { System.err.println(e); throw new RuntimeException(e); } } /** * Construct the layout for the game. * * @param stage container (window) in which to render the GUI * @throws Exception if there is a problem */ public void start( Stage stage ) throws Exception { Image image = new Image(getClass().getResourceAsStream("empty.png")); GridPane gridPane = new GridPane(); buttons = new Button[COL+1][ROW+1]; for (int row = 0; row <= ROW; row++) { for (int col = 0; col <= COL; col++) { buttons[col][row] = new Button(); buttons[col][row].setGraphic(new ImageView(image)); buttons[col][row].setOnAction(clickedButton(col)); gridPane.add(buttons[col][row], col, row); } } disableButtons(); BorderPane borderPane = new BorderPane(); borderPane.setPrefSize(456, 456); borderPane.setCenter(gridPane); turnLabel.setText("NOT YOUR TURN"); movesLeft.setText("MOVES LEFT: " + board.getMovesLeft()); BorderPane labels = new BorderPane(); labels.setLeft(turnLabel); labels.setRight(movesLeft); borderPane.setBottom(labels); Scene scene = new Scene(borderPane); stage.setScene(scene); stage.setTitle("Connect Four"); stage.show(); client.startListener(); } /** * Event handler for when a button is pressed * @param col - clicked column to send to server * @return - sending a move to the client if it is my turn * and if it is a valid move */ private EventHandler<ActionEvent> clickedButton(int col) { return event -> { if (board.isMyTurn()) { if (board.isValidMove(col)) { client.sendMove(col); } } }; } /** * Helper method to disable all buttons when * it is not the players turn */ private void disableButtons() { for (int row = 0; row <= ROW; row++) { for (int col = 0; col <= COL; col++) { buttons[col][row].setDisable(true); } } } /** * Helper method to enable all buttons if it * is the players turn */ private void enableButtons() { for (int row = 0; row <= ROW; row++) { for (int col = 0; col <= COL; col++) { buttons[col][row].setDisable(false); } } } /** * This method checks the contents of the board and * updates the image based on what players piece is there */ private void checkBoard() { for (int row = 0; row <= ROW; row++) { for (int col = 0; col <= COL; col++) { if (board.getContents(row, col) == ConnectFourBoard.Move.PLAYER_ONE) { buttons[col][row].setGraphic(new ImageView(p1)); } else if (board.getContents(row, col) == ConnectFourBoard.Move.PLAYER_TWO) { buttons[col][row].setGraphic(new ImageView(p2)); } } } } /** * GUI is closing, so close the network connection. Server will get the message. */ @Override public void stop() { client.close(); } /** * Do your GUI updates here. */ private void refresh() { if (!board.isMyTurn()) { disableButtons(); turnLabel.setText("NOT YOUR TURN"); movesLeft.setText("MOVES LEFT: " + board.getMovesLeft()); checkBoard(); ConnectFourBoard.Status status = board.getStatus(); switch (status) { case ERROR: client.error("ERROR"); turnLabel.setText("ERROR"); break; case I_WON: turnLabel.setText("YOU WON"); break; case I_LOST: turnLabel.setText("YOU LOST"); break; case TIE: turnLabel.setText("YOU TIED"); break; } } else { enableButtons(); turnLabel.setText("YOUR TURN"); movesLeft.setText("MOVES LEFT: " + board.getMovesLeft()); checkBoard(); } } /** * Called by the model, client.ConnectFourBoard, whenever there is a state change * that needs to be updated by the GUI. * * @param connectFourBoard board */ @Override public void update(ConnectFourBoard connectFourBoard) { if ( Platform.isFxApplicationThread() ) { this.refresh(); } else { Platform.runLater( () -> this.refresh() ); } } /** * The main method expects the host and port. * * @param args command line arguments */ public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: java ConnectFourGUI host port"); System.exit(-1); } else { Application.launch(args); } } }
Python
UTF-8
489
2.984375
3
[]
no_license
N = int(input()) inputs = [int(input()) for _ in range(N)] def process(): global right, ans right += 1 if right == N - 1: ans = max(ans, right - left + 1) print(ans) exit() left = 0 right = 0 ans = 1 while right < N - 1: while inputs[right] < inputs[right + 1]: process() while inputs[right] > inputs[right + 1]: process() ans = max(ans, right - left + 1) left = right right += 1 print(ans)
Java
UTF-8
1,245
3.671875
4
[]
no_license
import java.io.*; import java.util.*; class Node{ int freq; char c; Node left, right; Node(char c, int freq, Node left, Node right){ this.freq = freq; this.c = c; this.left = left; this.right = right; } int getFreq(){ return freq; } char getChar(){ return c; } } public class HuffmanCoding { public static void main(String[] args) { PriorityQueue<Node> heap = new PriorityQueue<Node>(new Comparator<Node>(){ @Override public int compare(Node p1, Node p2){return p1.freq - p2.freq;} }); heap.add(new Node('a', 10, null, null)); heap.add(new Node('b', 50, null, null)); heap.add(new Node('d', 20, null, null)); heap.add(new Node('e', 40, null, null)); heap.add(new Node('f', 80, null, null)); while(heap.size() > 1 ){ Node left = heap.poll(); Node right = heap.poll(); int freq = left.getFreq() + right.getFreq(); heap.add(new Node('$', freq , left, right)); } printEncoded(heap.peek(), ""); } public static void printEncoded(Node peek, String str){ if(peek.getChar() != '$'){ System.out.println(peek.getChar() + " --> " + str); return; } printEncoded(peek.left, str + "0"); printEncoded(peek.right, str + "1"); } }
Java
UTF-8
1,909
2.296875
2
[]
no_license
package com.example.ahmed.mal_gp; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; /** * Created by Ahmed on 4/3/2016. */ public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.viewHolder> { ArrayList<VideoData> videoDataArrayList; Context context; LayoutInflater layoutInflater; public VideoAdapter(Context context , ArrayList<VideoData> data){ this.context = context; videoDataArrayList = data; layoutInflater = LayoutInflater.from(context); } @Override public VideoAdapter.viewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = layoutInflater.inflate(R.layout.trailer , parent ,false); viewHolder holder =new viewHolder(v); return holder; } @Override public void onBindViewHolder(VideoAdapter.viewHolder holder, int position) { holder.trailer_name.setText(videoDataArrayList.get(position).getName()); } @Override public int getItemCount() { return videoDataArrayList.size(); } public class viewHolder extends RecyclerView.ViewHolder{ TextView trailer_name; public viewHolder(final View itemView) { super(itemView); trailer_name = (TextView) itemView.findViewById(R.id.trailer_title); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, PlayTrailer.class); i.putExtra("key",videoDataArrayList.get(getPosition()).getKey()); context.startActivity(i); } }); } } }
Java
UTF-8
2,043
3.078125
3
[]
no_license
import java.io.*; class MAXOR { BufferedReader bf; PrintWriter writer; StringBuilder sb; static boolean local_system = false; long solve(int[] d) { long c = 0; for (int i = 0, h = d.length; i < h; i++) { for (int j = i + 1; j < h; j++) { if ((d[i] & d[j]) == d[i]) c++; else if ( (d[i] & d[j]) == d[j] ) c++; } } return c; } long solve1(int[] d) { int[] h = new int[1000001]; for (int i = 0, l = d.length; i < l; i++) h[d[i]]++; long count = 0; for (int i = 0, l = d.length; i < l; i++) { for (int j = d[i]; j > 0; j = d[i] & (j - 1)) { if (j != d[i]) count += h[j]; } } for (int e : h) count += (e * (e - 1)) >> 1; return count; } void run() throws IOException { int t = i(); while (t-- > 0) { i(); int[] d = ni(); sb.append(solve1(d)).append("\n"); } writer.println(sb.toString().trim()); } public static void main(String[] args) throws IOException { long start_time = System.currentTimeMillis(); MAXOR obj = new MAXOR(); obj.run(); long end_time = System.currentTimeMillis(); if (local_system) obj.writer.println( "Time : " + (end_time - start_time) ); obj.close(); } public MAXOR() { writer = new PrintWriter(System.out); bf = new BufferedReader(new InputStreamReader(System.in)); sb = new StringBuilder(); } public int i() throws IOException { return Integer.parseInt(bf.readLine()); } public long l() throws IOException { return Long.parseLong(bf.readLine()); } public int[] ni() throws IOException { String[] data = bf.readLine().split(" "); int[] send = new int[data.length]; for (int i = 0, h = data.length; i < h; i++) send[i] = Integer.parseInt(data[i]); return send; } public long[] nl() throws IOException { String[] data = bf.readLine().split(" "); long[] send = new long[data.length]; for (int i = 0, h = data.length; i < h; i++) send[i] = Long.parseLong(data[i]); return send; } public void close() throws IOException { writer.flush(); writer.close(); bf.close(); } }
SQL
UTF-8
1,312
4.125
4
[ "Apache-2.0" ]
permissive
#standardSQL # pages markup metrics grouped by device and button type # returns button struct CREATE TEMPORARY FUNCTION get_markup_buttons_info(markup_string STRING) RETURNS ARRAY<STRUCT< name STRING, freq INT64 >> LANGUAGE js AS ''' var result = []; try { var markup = JSON.parse(markup_string); if (Array.isArray(markup) || typeof markup != 'object') return result; if (markup.buttons && markup.buttons.types) { var total = markup.buttons.total; var withType = 0; result = Object.entries(markup.buttons.types).map(([name, freq]) => { withType+=freq; return {name: name.toLowerCase().trim(), freq};}); result.push({name:"NO_TYPE", freq: total - withType}) return result; } } catch (e) {} return result; '''; SELECT _TABLE_SUFFIX AS client, button_type_info.name AS button_type, COUNTIF(button_type_info.freq > 0) AS freq, SUM(COUNT(0)) OVER (PARTITION BY _TABLE_SUFFIX) AS total, COUNTIF(button_type_info.freq > 0) / SUM(COUNT(0)) OVER (PARTITION BY _TABLE_SUFFIX) AS pct_page_with_button_type FROM `httparchive.pages.2021_07_01_*`, UNNEST(get_markup_buttons_info(JSON_EXTRACT_SCALAR(payload, '$._markup'))) AS button_type_info GROUP BY client, button_type ORDER BY pct_page_with_button_type DESC, client, freq DESC LIMIT 1000
Java
UTF-8
693
1.601563
2
[]
no_license
package jp.co.internous.ecsite.model.form; import java.io.Serializable; import java.util.List; //↓ //import antlr.collections.List; //↓ //import com.sun.xml.bind.v2.schemagen.xmlschema.List; //↓ //import java.awt.List; //↓ //import org.hibernate.mapping.List; public class CartForm implements Serializable { private static final long serialVersionUID = 1L; private long userId; private List<Cart> cartList; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public List<Cart> getCartList() { return cartList; } public void setCartList(List<Cart> cartList) { this.cartList = cartList; } }
Markdown
UTF-8
1,648
2.78125
3
[]
no_license
# Summary The concept of information sharing has been growing rapidly along with multiple common search engines such as Google and Yahoo; however, these generic web search platforms may not provide best results for the users who prefer to search within a narrow scope or without going to a third-party website. Our goal is to design and implement a tailored search engine application “UTask” for users from the University of Toronto Scarborough (UTSC) community. The tool will allow users to create and manage their personal accounts, efficiently search files/links with customized filters, and upload/download files to their private online drives to form a powerful information sharing and management platform. The key users of this application will be the instructors and students at UTSC. Our search application will significantly improve user experience under many scenarios, compared to the current search engines: for example, when instructors from UTSC are trying to upload their documents into a centralized drive and easily share them with students. Users can also refine their search using the advanced search tool to quickly locate relevant files from both personal and/or shared resources in their drive. Additionally, when students need to search useful links, such as the UTSC GPA calculator, or test banks for a particular course that are available online, UTask will provide them the most suitable search results narrowed down for the UTSC community by always prioritizing UTSC related contents and instructors’ uploads by default, combined with other filters that users specify, to ensure best search results efficiency.
Java
UTF-8
3,474
2.09375
2
[]
no_license
package cin.ufpe.br.energyprofiler.modes.abstracts; import android.content.Context; import android.os.Vibrator; import android.view.View; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import cin.ufpe.br.energyprofiler.MainActivity; import cin.ufpe.br.energyprofiler.Options; import cin.ufpe.br.energyprofiler.R; import cin.ufpe.br.energyprofiler.enums.EnumDashboard; import cin.ufpe.br.energyprofiler.enums.IActions; import cin.ufpe.br.energyprofiler.enums.EnumCollections; import cin.ufpe.br.energyprofiler.enums.exceptions.TimeThresholdException; import cin.ufpe.br.energyprofiler.listeners.FinishListener; import cin.ufpe.br.energyprofiler.modes.AppExecutor; /** * Created by welli on 03-Dec-17. */ public abstract class AMode { protected MainActivity activity; protected TextView mainText; protected TextView header; protected Vibrator v; protected AppExecutor executor; public IActions action; public abstract IActions getNextAction(); public abstract void initExecutor(String collecParam,IActions action); public abstract void execute(IActions str); public abstract void finishedLogging(); public abstract String getModeName(); protected AMode(MainActivity activity,String initParam){ this.activity = activity; mainText = (TextView) activity.findViewById(R.id.text); header = (TextView) activity.findViewById(R.id.header); v = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); if(initParam != null) { header.setVisibility(View.VISIBLE); header.setText(getModeName() + ":\n " + EnumCollections.exist(initParam).getName()); mainText.setText(""); } } protected void executeAndDashBoard(IActions action, EnumDashboard dashboardAction){ try { executor.execute(action); dashboardMsg(dashboardAction); } catch (InterruptedException e) { e.printStackTrace(); } } public void showOnScreen(String action, String text) { mainText.setText(new StringBuilder(mainText.getText()) .append(action) .append(" done!\n") .toString() ); } public boolean isReady() { return executor!=null; } public void endApp() { // header.setVisibility(View.INVISIBLE); if(Options.isVibrating) { v.vibrate(1000); } if(Options.isClosing) { activity.finish(); Runtime.getRuntime().gc(); // System.exit(0); } } public void dashboardMsg(EnumDashboard action) { // in the offlineMode, we can't collect // energy data, so the dashboardMsg does nothing if(!Options.offlineMode) { // submitting a request to iniciate the getNextAction action StringRequest stringRequest = new StringRequest(Request.Method.GET, action.toString(), new FinishListener(this), new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { mainText.setText("ERROR end:\n webservice not found"); } }); activity.queue.add(stringRequest); } } }
C++
UTF-8
15,038
2.65625
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Math/Bounds/Ray.hpp" #include "Math/Bounds/BoundsSphere.hpp" #include "Math/Bounds/BoundsAABB.hpp" #include "Math/Bounds/BoundsOBB.hpp" #include "Math/Geometry/Plane.hpp" //------------------------------------------------------------------------------------------ namespace Ocular { namespace Math { //---------------------------------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------------------------------- Ray::Ray(Vector3f const& origin, Vector3f const& direction) { m_Origin = origin; m_Direction = direction.getNormalized(); } Ray::Ray() { } Ray::~Ray() { } //---------------------------------------------------------------------------------- // PUBLIC METHODS //---------------------------------------------------------------------------------- void Ray::setOrigin(Vector3f const& origin) { m_Origin = origin; } void Ray::setDirection(Vector3f const& direction) { m_Direction = direction.getNormalized(); } Vector3f const& Ray::getOrigin() const { return m_Origin; } Vector3f const& Ray::getDirection() const { return m_Direction; } Vector3f Ray::getPointAlong(float const distance) const { return (m_Origin + (m_Direction * distance)); } //------------------------------------------------------------------------------ // Intersection and Containment Testing //------------------------------------------------------------------------------ bool Ray::intersects(Ray const& other) const { return true; } bool Ray::intersects(Point3f const& point) const { const float distance = m_Origin.distanceTo(point); const Point3f pointOnRay = getPointAlong(distance); return (point == pointOnRay); } bool Ray::intersects(Ray const& other, Point3f& point, float& distance) const { return true; } bool Ray::intersects(BoundsSphere const& bounds) const { bool result = false; const Vector3f l = bounds.getCenter() - m_Origin; const float s = l.dot(m_Direction); const float l2 = l.dot(l); const float rr = (bounds.getRadius() * bounds.getRadius()); if((s >= 0.0f) || (l2 < rr)) { const float m = l2 - (s * s); const float mm = m * m; if(mm <= rr) { result = true; } } return result; } bool Ray::intersects(BoundsSphere const& bounds, Point3f& point, float& distance) const { bool result = false; const Vector3f l = bounds.getCenter() - m_Origin; const float s = l.dot(m_Direction); const float l2 = l.dot(l); const float rr = (bounds.getRadius() * bounds.getRadius()); if((s >= 0.0f) || (l2 < rr)) { const float m = l2 - (s * s); const float mm = m * m; if(mm <= rr) { const float q = sqrtf(rr - mm); result = true; distance = (l2 > rr) ? (s - q) : (s + q); point = getPointAlong(distance); } } return result; } bool Ray::intersects(BoundsAABB const& bounds) const { // AABB intersection test using the slabs method. // Source: Real-Time Rendering, 3rd Ed. Page 743 // Nearly identical tto the OBB method except for the following: // - Calculation for e is changed // - Calculation for f is changed static const float epsilon = 0.000000000000001f; bool result = true; float tMin = FLT_MIN; float tMax = FLT_MAX; float t0 = 0.0f; float t1 = 0.0f; const Vector3f p = bounds.getCenter() - m_Origin; const Vector3f d = m_Direction; const Vector3f h = bounds.getExtents(); for(uint32_t i = 0; i < 3; i++) { float e = p[i]; float f = d[i]; if(fabs(f) > epsilon) { t0 = (e + h[i]) / f; t1 = (e - h[i]) / f; if(t0 > t1) { float tTemp = t0; t0 = t1; t1 = tTemp; } if(t0 > tMin) { tMin = t0; } if(t1 < tMax) { tMax = t1; } if(tMin > tMax) { result = false; break; // No intersection } if(tMax < 0.0f) { result = false; break; // No intersection } } else if(((-e - h[i]) > 0.0f) || (-e + h[i] < 0.0f)) { result = false; break; // No intersection } } return result; } bool Ray::intersects(BoundsAABB const& bounds, Point3f& point, float& distance) const { // AABB intersection test using the slabs method. // Source: Real-Time Rendering, 3rd Ed. Page 743 // Nearly identical tto the OBB method except for the following: // - Calculation for e is changed // - Calculation for f is changed static const float epsilon = 0.000000000000001f; bool result = true; float tMin = FLT_MIN; float tMax = FLT_MAX; float t0 = 0.0f; float t1 = 0.0f; const Vector3f p = bounds.getCenter() - m_Origin; const Vector3f d = m_Direction; const Vector3f h = bounds.getExtents(); for(uint32_t i = 0; i < 3; i++) { float e = p[i]; float f = d[i]; if(fabs(f) > epsilon) { t0 = (e + h[i]) / f; t1 = (e - h[i]) / f; if(t0 > t1) { float tTemp = t0; t0 = t1; t1 = tTemp; } if(t0 > tMin) { tMin = t0; } if(t1 < tMax) { tMax = t1; } if(tMin > tMax) { result = false; break; // No intersection } if(tMax < 0.0f) { result = false; break; // No intersection } } else if(((-e - h[i]) > 0.0f) || (-e + h[i] < 0.0f)) { result = false; break; // No intersection } } if(result) { distance = (tMin > 0.0f) ? tMin : tMax; point = getPointAlong(distance); } return result; } bool Ray::intersects(BoundsOBB const& bounds) const { // OBB intersection test using the slabs method. // Source: Real-Time Rendering, 3rd Ed. Page 743 static const float epsilon = 0.000000000000001f; bool result = true; float tMin = FLT_MIN; float tMax = FLT_MAX; float t0 = 0.0f; float t1 = 0.0f; const Vector3f a[3] = { bounds.getDirectionX(), bounds.getDirectionY(), bounds.getDirectionZ() }; const Vector3f p = bounds.getCenter() - m_Origin; const Vector3f d = m_Direction; const Vector3f h = bounds.getExtents(); for(uint32_t i = 0; i < 3; i++) { float e = a[i].dot(p); float f = a[i].dot(d); if(fabs(f) > epsilon) { t0 = (e + h[i]) / f; t1 = (e - h[i]) / f; if(t0 > t1) { float tTemp = t0; t0 = t1; t1 = tTemp; } if(t0 > tMin) { tMin = t0; } if(t1 < tMax) { tMax = t1; } if(tMin > tMax) { result = false; break; // No intersection } if(tMax < 0.0f) { result = false; break; // No intersection } } else if(((-e - h[i]) > 0.0f) || (-e + h[i] < 0.0f)) { result = false; break; // No intersection } } return result; } bool Ray::intersects(BoundsOBB const& bounds, Point3f& point, float& distance) const { // OBB intersection test using the slabs method. // Source: Real-Time Rendering, 3rd Ed. Page 743 static const float epsilon = 0.000000000000001f; bool result = true; float tMin = FLT_MIN; float tMax = FLT_MAX; float t0 = 0.0f; float t1 = 0.0f; const Vector3f a[3] = { bounds.getDirectionX(), bounds.getDirectionY(), bounds.getDirectionZ() }; const Vector3f p = bounds.getCenter() - m_Origin; const Vector3f d = m_Direction; const Vector3f h = bounds.getExtents(); for(uint32_t i = 0; i < 3; i++) { float e = a[i].dot(p); float f = a[i].dot(d); if(fabs(f) > epsilon) { t0 = (e + h[i]) / f; t1 = (e - h[i]) / f; if(t0 > t1) { float tTemp = t0; t0 = t1; t1 = tTemp; } if(t0 > tMin) { tMin = t0; } if(t1 < tMax) { tMax = t1; } if(tMin > tMax) { result = false; break; // No intersection } if(tMax < 0.0f) { result = false; break; // No intersection } } else if(((-e - h[i]) > 0.0f) || (-e + h[i] < 0.0f)) { result = false; break; // No intersection } } if(result) { distance = (tMin > 0.0f) ? tMin : tMax; point = getPointAlong(distance); } return result; } bool Ray::intersects(Plane const& plane) const { // Source: isect_line_plane_v3 // https://developer.blender.org/diffusion/B/browse/master/source/blender/blenlib/intern/math_geom.c bool result = false; const Vector3f line0 = m_Origin; const Vector3f line1 = getPointAlong(RAY_LINE_LENGTH); const Vector3f planePoint = plane.getPoint(); const Vector3f planeNormal = plane.getNormal(); const Vector3f u = line1 - line0; const Vector3f h = line0 - planePoint; const float dot = planeNormal.dot(u); if(fabsf(dot) > EPSILON_FLOAT) { result = true; } return result; } bool Ray::intersects(Plane const& plane, Vector3f& point, float& distance) const { // Source: isect_line_plane_v3 // https://developer.blender.org/diffusion/B/browse/master/source/blender/blenlib/intern/math_geom.c bool result = false; const Vector3f line0 = m_Origin; const Vector3f line1 = getPointAlong(RAY_LINE_LENGTH); const Vector3f planePoint = plane.getPoint(); const Vector3f planeNormal = plane.getNormal(); const Vector3f u = line1 - line0; const Vector3f h = line0 - planePoint; const float dot = planeNormal.dot(u); if(fabsf(dot) > EPSILON_FLOAT) { float lambda = -planeNormal.dot(h) / dot; point = line0 + (u * lambda); distance = m_Origin.distanceTo(point); result = true; } return result; } //---------------------------------------------------------------------------------- // PROTECTED METHODS //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- // PRIVATE METHODS //---------------------------------------------------------------------------------- } }
Java
UTF-8
104
1.710938
2
[ "BSD-3-Clause" ]
permissive
package org.firstinspires.ftc.teamcode.byrt; public enum SpinnerPosition { IN, HALF, OUT }
C++
UTF-8
1,127
3.125
3
[]
no_license
#include <string> #include <random> #include <iostream> #include <cstdlib> #include <ctime> using namespace std; string strGenerator() { char arrayOfChar[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '}; random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dis(0, 27); int count = 0; string str; bool flag = true; for (count = 0; count < 28; count++) { int random_number = dis(gen); str += arrayOfChar[random_number]; } cout << str << endl; return str; } int main() { string answer = "methinks it is like a weasel"; char arrayOfAns[] = {'m', 'e', 't','h','i','n','k','s',' ','i','t',' ','i','s',' ','l','i','k','e', ' ', 'a',' ','w','e','a','s','l','e'}; int count = 0; for (count = 0; count < 10000000; count++){ if (strGenerator() == answer){ cout << count << endl; return count; } else if (count == 999){ cout << "none found" << endl; } } return 0; }
Python
UTF-8
36
2.65625
3
[]
no_license
a = int(input()) print(a*123456789)
TypeScript
UTF-8
652
2.75
3
[ "MIT" ]
permissive
// CTR - Counter AES encryption import * as aes from 'aes-js'; const key = [ 3, 1, 1, 8, 1, 7, 6, 3, 3, 4, 9, 6, 8, 6, 7, 3, 7, 7, 6, 7, 0, 2, 2, 5, 6, 7, 0, 5, 8, 5, 0, 1 ]; function aesCtr() { return new aes.ModeOfOperation.ctr(key, new aes.Counter(7)); } export function encrypt(value) { const encryptedBytes = aesCtr().encrypt(aes.utils.utf8.toBytes(value)); return aes.utils.hex.fromBytes(encryptedBytes); } export function decrypt(hexValue) { const decryptedBytes = aesCtr().decrypt(aes.utils.hex.toBytes(hexValue)); return aes.utils.utf8.fromBytes(decryptedBytes); }
JavaScript
UTF-8
6,441
2.75
3
[ "Apache-2.0" ]
permissive
var GitHubApi = require("github"); var gutil = require("gulp-util"); var through2 = require("through2"); /** * Create a function that collects all elements from a multi-page response */ function collector(github, collect, done) { var r = function(err, res) { if (err) { done(err); return; } // check response status if (res.meta.status === undefined || /^200.*/.test(res.meta.status)) { // call collect method for each entry in the response res.forEach(collect); } else if (/^204.*/.test(res.meta.status)) { // no content } else { // handle error done(res.meta.status); return; } // request next page or finish if (github.hasNextPage(res)) { github.getNextPage(res, r); } else { done(); } }; return r; } /** * Get all repositories of an organization */ function getRepos(org, github, done) { var result = []; github.repos.getFromOrg({ org: org }, collector(github, function(e) { result.push(org + "/" + e.name); }, function(err) { if (err) { done(err); return; } done(null, result); })); } /** * Get repositories of all given organizations */ function getAllRepos(orgs, github, done) { var orgsClone = orgs.slice(0); var allRepos = []; var loop = function() { if (orgsClone.length === 0) { // no more organizations to query done(null, allRepos); return; } // get next organization to query var org = orgsClone.shift(); gutil.log(org + " ..."); getRepos(org, github, function(err, repos) { if (err) { done(err); return; } allRepos = allRepos.concat(repos); // query next organisation loop(); }); }; loop(); } /** * Get all people who contributed to a repository and return their login and * number of contributions */ function getContributors(org, repo, github, done) { var result = []; github.repos.getContributors({ user: org, repo: repo }, collector(github, function(e) { result.push({ login: e.login, contributions: e.contributions || 0 }); }, function(err) { if (err) { done(err); return; } done(null, result); })); } /** * Loop through the given repositories and get the usernames of all contributors * and the number of their contributions */ function getAllContributors(repos, github, done) { var reposClone = repos.slice(0); var allContributors = []; var loop = function() { if (reposClone.length === 0) { // no more repositories to query done(null, allContributors); return; } // get next repository to query var repo = reposClone.shift(); gutil.log(repo + " ..."); var sr = repo.split("/"); var org = sr[0]; repo = sr[1]; getContributors(org, repo, github, function(err, contributors) { if (err) { done(err); return; } // add all contributors of this repository to the result list contributors.forEach(function(c) { var found = false; for (var j = 0; j < allContributors.length; ++j) { if (allContributors[j].login === c.login) { allContributors[j].contributions += c.contributions; found = true; break; } } if (!found) { allContributors.push(c); } }); // query next repository in the list loop(); }); }; loop(); } /** * Get details for a given user */ function getUserDetails(user, github, done) { github.user.getFrom({ user: user }, function(err, data) { if (err) { done(err); return; } // generate details var details = { github_id: data.login, avatar: data.avatar_url + "&s=80", github: data.html_url, name: data.name || data.login }; // handle homepage if (data.blog) { details.homepage = data.blog; if (!/^[a-z]+:\/\//.test(details.homepage)) { details.homepage = "http://" + details.homepage; } } done(null, details); }); } /** * Get details of all given users */ function getAllUserDetails(users, github, done) { var usersClone = users.slice(0); var allUsers = []; var loop = function() { if (usersClone.length == 0) { // no more users to query done(null, allUsers); return; } // get next user to query var user = usersClone.shift(); gutil.log(user.login + " ..."); getUserDetails(user.login, github, function(err, details) { if (err) { done(err); return; } details.contributions = user.contributions; allUsers.push(details); // query next user loop(); }); }; loop(); } /** * Get all Vert.x contributors */ function getAll(github, done) { // get all repositories of the vert-x and vert-x3 organisations var orgs = ["vert-x", "vert-x3"]; gutil.log("Get all repositories ...") getAllRepos(orgs, github, function(err, repos) { if (err) { done(err); return; } // get contributors from the 'eclipse-vertx/vert.x' repository as well repos.unshift("eclipse-vertx/vert.x"); // get all contributors gutil.log("Get all contributors ...") getAllContributors(repos, github, function(err, contributors) { if (err) { done(err); return; } // query user details of all contributors gutil.log("Query user details ..."); getAllUserDetails(contributors, github, done); }); }) } module.exports = function(client_id, client_secret) { var github = new GitHubApi({ version: "3.0.0" }); if (client_id && client_secret) { github.authenticate({ type: "oauth", key: client_id, secret: client_secret }); } var result = through2.obj(function(file, enc, callback) { this.push(file); return callback(); }); // collect all contributors getAll(github, function(err, contributors) { if (err) { result.emit("error", err); return; } contributors.sort(function(a, b){return a['github_id'].localeCompare(b['github_id'])}); // write contributors to output stream var file = new gutil.File({ path: "contributors-gen.js", contents: new Buffer(JSON.stringify(contributors, undefined, 2), "utf-8") }); result.write(file); result.end(); }); return result; };
Go
UTF-8
394
3.515625
4
[]
no_license
package main import "fmt" func printRepeating4(data []int, intrange int) { size := len(data) count := make([]int, intrange) for i := 0; i < size; i++ { if count[data[i]] == 1 { fmt.Println(" ", data[i]) } else { count[data[i]]++ } } fmt.Println() } func main() { data := []int{1, 2, 3, 4, 5, 3, 2, 1} intrange := 6 printRepeating4(data, intrange) }
Markdown
UTF-8
6,260
3.03125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: How to use upstream sources in your Azure Artifacts feed description: Use upstream sources in Azure Artifacts to consume packages from public registries ms.technology: devops-artifacts ms.reviewer: amullans ms.date: 08/24/2021 monikerRange: '>= tfs-2017' "recommendations": "true" --- # Tutorial: How to use upstream sources Using upstream sources in your feed enables you to manage your application dependencies from a single feed. Using upstream sources makes it easy to consume packages from public registries while having protection against outages or compromised packages. You can also publish your own packages to the same feed and manage all your dependencies in one location. This tutorial will walk you though how to enable upstream sources on your feed and consume packages from public registries such as NuGet.org or npmjs.com. In this tutorial, you will: >[!div class="checklist"] > * Create a new feed and enable upstream sources. > * Set up your configuration file. > * Run an initial package restore to populate your feed. > * Check your feed to view the saved copy of the packages you consumed from the public registry. ## Create a feed and enable upstream sources ::: moniker range=">= azure-devops-2019" 1. Select **Artifacts**. :::image type="content" source="../media/goto-feed-hub-azure-devops-newnav.png" alt-text="Screenshot showing how to navigate to Azure Artifacts."::: ::: moniker-end ::: moniker range=">=tfs-2017 < azure-devops-2019" 1. Select **Build & Release**, and then select **Packages**. :::image type="content" source="../media/goto-feed-hub.png" alt-text="Screenshot showing how to navigate to Azure Artifacts - TFS."::: ::: moniker-end ::: moniker range=">= azure-devops-2019" 2. Select **Create Feed** to create a new feed. :::image type="content" source="../media/new-feed-button-azure-devops-newnav.png" alt-text="Screenshot showing the create feed button."::: ::: moniker-end ::: moniker range=">=tfs-2017 < azure-devops-2019" 2. Select **New Feed** to create a new feed. :::image type="content" source="../media/new-feed-button.png" alt-text="Screenshot showing the create feed button - TFS."::: ::: moniker-end ::: moniker range=">= azure-devops-2019" 3. Provide a name for your feed, and then select its visibility. Make sure your check the **Include packages from common public sources** checkbox to enable upstream sources. Select **Create** when you are done :::image type="content" source="../media/new-feed-dialog.png" alt-text="Screenshot showing the create a new feed window."::: ::: moniker-end ::: moniker range=">=tfs-2017 < azure-devops-2019" 3. Provide a name for your feed, and then select its visibility. Make sure your check the **Include packages from common public sources** checkbox to enable upstream sources. Select **Create** when you are done :::image type="content" source="../media/new-feed-dialog.png" alt-text="Screenshot showing the create a new feed window - TFS."::: ::: moniker-end ## Set up the configuration file Now that we created our feed, we need to update the config file to point to our feed. To do this we must: 1. Get the source's URL 1. Update the configuration file #### [npm](#tab/npm/) ::: moniker range=">= azure-devops-2019" 1. Select **Artifacts**, and then select **Connect to feed**. :::image type="content" source="../media/connect-to-feed-azure-devops-newnav.png" alt-text="Screenshot showing how to connect to a feed."::: 1. On the left side of the page, select the **npm** tab. 1. Follow the instructions in the **Project setup** section to set up your config file. :::image type="content" source="../media/connect-to-feed-npm-registry-azure-devops-newnav.png" alt-text="Screenshot showing how to set up your project."::: ::: moniker-end ::: moniker range=">=tfs-2017 < azure-devops-2019" 1. Select **Build & Release** > **Packages**, and then select **Connect to Feed**. :::image type="content" source="../media/connect-to-feed.png" alt-text="Screenshot showing how to connect to a feed - TFS"::: 1. Copy the highlighted snippet to add it to your config file. :::image type="content" source="../media/connect-to-feed-npm-registry.png" alt-text="Screenshot highlighting the snippet to be added to the config file - TFS"::: ::: moniker-end If you don't have a *.npmrc* file already, create a new one in the root of your project (in the same folder as your *package.json*). Open your new *.npmrc* file and paste the snippet you just copied in the previous step. #### [NuGet](#tab/nuget/) 1. Select **Artifacts**, and then select your feed. 1. Select **Connect to feed**, and then choose **NuGet.exe**. :::image type="content" source="../media/nuget-connect-to-feed.png" alt-text="Screenshot showing how to connect to NuGet feeds."::: 1. Copy the XML snippet in the **Project Setup** section. 1. Create a new file named *nuget.config* in the root of your project. 1. Paste the XML snippet in your config file. * * * ## Restore packages Now that you enabled upstream sources and set up your configuration file, we can run the package restore command to query the upstream source and retrieve the upstream packages. We recommend clearing your local cache first before running the *nuget restore*. Azure Artifacts will have a saved copy of any packages you installed from upstream. # [npm](#tab/npm) Remove the *node_modules* folder from your project and run the following command in an elevated command prompt window: ```Command npm install --force ``` > [!NOTE] > The `--force` argument will force pull remotes even if a local copy exists. Your feed now should contain any packages you saved from the upstream source. # [NuGet](#tab/nuget) - **Clear your local cache**: ```Command nuget locals -clear all ``` - **Restore packages**: ```Command nuget.exe restore ``` Your feed now should contain any packages you saved from the upstream source. * * * ## Related articles - [upstream sources overview](../concepts/upstream-sources.md) - [Upstream behavior](../concepts/upstream-behavior.md) - [Feed permissions](../feeds/feed-permissions.md) - [Publish packages to NuGet.org](../nuget/publish-to-nuget-org.md)
C#
UTF-8
406
2.671875
3
[]
no_license
// ... private IQueryable<BaseSearchResultItem> ApplyManufacturerQuery(IQueryable<BaseSearchResultItem> query, PhoneSearchParam searchParam) { /* query.AsEnumerable() .Select(phone => { (string)phone["manufacture"].ToLower() == searchParam.Manufacture.ToLower() }); */ query = query.Where( (phone) => phone["manufacturer"] == searchParam.Manufacture ); return query; } // ...
Java
UTF-8
3,773
2.015625
2
[]
no_license
package com.zfw.core.sys.service; import com.zfw.core.service.ICommonService; import com.zfw.core.sys.entity.Progress; import com.zfw.core.sys.entity.User; import com.zfw.dto.excel.PhotoExcel; import com.zfw.utils.StringUtilsEx; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.List; public interface IUserService extends ICommonService<User,Integer> { /** * 查询出所有上传照片的人员 * @return */ List<User> findByPhotoIsNotNull(); List<User> findByPhotoFlag(Integer photoFlag); User findTop1ByMiniOpenId(String miniOpenId); boolean existsByMiniOpenId(String miniOpenId); /** * 获取用户所具有的角色,以及权限 * @param userId * @return */ User getUserRole(Integer userId); String generateToken(); /** * 获取用户所具有的角色,以及权限 * @param user * @return */ User getUserRole(User user); /** * 获取用户的具有的所有菜单列表,并以tree封入user.setMenu中 * @param user * @return */ User getUserTreeMenu(User user); /** * 通过用户获取盐值密码 * @param user * @return */ String getSaltPassword(User user); /** * 注册用户 * @param user * @return 返回注册成功的用户 */ User registerUser(User user); /** * 修改密码 * @param userId * @param password * @return 返回修改成功的user实体 */ User changePassword(Integer userId, String password); User login(String userName, String password); void logout(User currentUser); /** * 通过id删除用户,同时删除user_role表中绑定的userId * @param id */ void deleteUser(Integer id); /** * 用于批量退宿接口 * @param id * @return */ boolean deleteUserAndBack(Integer id,Progress progress); /** * 通过user对象和request对象来获取登录日志 * @param user * @param request */ void saveLoginLog(User user, HttpServletRequest request); boolean existsByUserName(String userName); /** * 通过用户id重置email * @param userId * @param email */ void resetEmail(Integer userId, String email); /** * 通过用户名获取用户对象 * @param userName * @return */ User findByUserName(String userName); /** * 创建用户信息 * @param user * @return */ User createUser(User user); /** * 初始化密码 * @param user * @return */ default String initPassword(User user){ String password= StringUtilsEx.getMD5("000000") ; String idCard = user.getIdCard(); if (StringUtils.isNotBlank(idCard)){ password=StringUtilsEx.getMD5(StringUtils.substring(idCard,idCard.length()-6)); } return password; } /** * 修改用户信息 * @param user * @return */ User updateUser(User user); /** * 根据部门id判断数据是否存在 * @param deptId * @return */ boolean existsByDeptId(Integer deptId); List<User> findByDeptCodeIsStartingWith(String deptCode); /** * 导入照片 * @param files */ void importPhotos(List<File> files, List<PhotoExcel> excels,boolean isCheckFace) throws IOException; /** * 通过userName更改deptId,deptPath,deptCode * @param userName * @param deptId * @param deptPath * @param deptCode */ void updateDeptCode(String userName,Integer deptId,String deptPath,String deptCode) ; }
Java
UTF-8
1,617
2.1875
2
[ "Apache-2.0" ]
permissive
package org.yoqu.cms.plugin.serve.core.config; import org.apache.mina.core.session.IoSession; /** * @author yoqu * @date 2016/6/21 0021 * @description */ public class ClientSession { private Long id; private IoSession session; private String address; private String username; private String password; private boolean isActive; public ClientSession(IoSession session){ } public ClientSession(String username,String password,IoSession session){ this.username=username; this.password=password; this.session=session; } public IoSession getSession() { return session; } public void writeMessage(Object object){ session.write(object); } public void setSession(IoSession session) { this.session = session; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isActive() { return isActive; } public void setActive(boolean active) { isActive = active; } public Long getId() { return id; } public void setId(Long id) { id = id; } @Override public int hashCode() { return id.intValue(); } }
Java
UTF-8
373
1.617188
2
[ "MIT" ]
permissive
package uk.gov.companieshouse.api.accounts.repository; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import uk.gov.companieshouse.api.accounts.model.entity.CicReportApprovalEntity; @Repository public interface CicReportApprovalRepository extends MongoRepository<CicReportApprovalEntity, String> { }
Markdown
UTF-8
4,913
3.171875
3
[]
no_license
第四回 恼人的猪八戒(8) 牛大爷哈哈大笑,笑得连杯里剩下的一点酒都泼了出来,欧阳美一面笑,一面用眼角瞟着田思思。 田思思却莫名其妙,这些话她根本都不懂,她决定以后要问问那大头鬼,“婊子”究竟是干什么的。 牛大爷又笑道:“她既然是个白虎星,想必也不是什么好货色,凭什么架子要比别人大?” 季公子道:“这只因男人都是贱骨头,她架子越大,男人就越想跟她上床。” 牛大爷点着头笑道:“她这倒是摸透男人的心了,连我的心都好像已有点打动,等等说不定也得去试试看。” 欧阳美忽然拊掌道:“我想起来了。” 牛大爷道:“美公想起了什么?” 欧阳美道:“季公子说的,莫非是张好儿?” 季公子道:“正是她。” 牛大爷笑道:“张好儿?她哪点好?好在哪里?” 欧阳美道:“听说这张好儿不但是江湖第一名女子,而且还是个侠妓,非但床上的功夫高人一等,手底下的功夫也不弱的。” 牛大爷斜着眼,笑道:“如此说来,美公想必也动心了,却不知这张好儿今天晚上挑中的是谁?” 两人相视大笑,笑得却已有点勉强。 一沾上“钱”和“女人”,很多好朋友都会变成冤家。 何况他们根本就不是什么好朋友。 牛大爷的眼角又斜到季公子的脸上,道:“季公子既然连她那地方有草没草都知道,莫非已跟她有一腿?” 季公子嘿嘿地笑。 无论谁看到他这种笑,都会忍不住想往他脸上打一拳。 季公子冷笑着道:“奇怪的是,张好儿怎会光顾到这种地方来,难道她知道这里有牛兄这么样个好户头?” 牛大爷的笑也好像变成了冷笑,道:“我已准备出她五百两,想必该够了吧。” 季公子还是嘿嘿地笑,索性连话都不说了。 那“病鬼”已有很久没开口,此刻忍不住陪笑道:“她那地方就算是金子打的,五百两银子也足够买下来了,我这就替牛大爷准备洞房去。” 只要有马屁可拍,这种人是绝不会错过机会的。 牛大爷却又摇着头淡淡道:“慢着!就算她肯卖,我还未必肯买哩,五百两银子毕竟不是偷来的。” 有种人的马屁好像专门会拍到马腿上。 欧阳美大笑道:“你只管去准备,只要有新娘子,还怕找不到新郎?” 田思思实在忍不住,等这三人一走回雅房,就悄悄问道:“婊子是干什么的?难道就是新娘子?” 杨凡忍住笑,道:“有时候是的。” 田思思道:“是谁的新娘子?” 杨凡道:“很多人的。” 田思思道:“一个人怎么能做很多人的新娘子?” 杨凡上下看了她两眼,道:“你真的不懂?” 田思思撅起嘴,道:“我要是懂,为什么问你?” 杨凡叹了口气,道:“她当然可以做很多人的新娘子,因为她一天换一个新郎。” 开饭铺的人大多都遵守一个原则:“有钱的就是大爷。” 无论你是婊子也好,是孙子也好,只要你能吃得起二十两银子一桌的酒席,他们就会像伺候祖宗似的伺候你。 店里上上下下的人已全都忙了起来,摆碗筷的摆碗筷,擦凳子的擦凳子。 碗筷果然都是全新的,比田思思用的那副碗筷至少强五倍,连桌布都换上了做喜事用的红巾。 田思思的脸比桌布还红,她总算明白婊子是干什么的了。 那些人刚才说的话,到现在她才听懂。 她只希望自己还是没有听懂,只恨杨凡为什么要解释如此清楚。 “这猪八戒想必也不是个好东西,说不定也做过别人的一夜新郎。” 这猪八戒是不是好人,其实跟她一点关系都没有,但也不知为了什么,一想到这里,她忽然就生起气来,嘴撅得简直可以挂个酒瓶子。 “这张好儿究竟是个怎么样的人,究竟好在什么地方?” 她又觉得好奇。 千呼万唤始出来,姗姗来迟了的张好儿总算还是来了。 一辆四匹马拉着的车,已在门外停下。 刚走进雅座的几个人,立刻又冲了出来。 掌柜的和伙计早都已弯着腰,恭恭敬敬地等在门口,腰虽然弯得很低,眼角却又忍不住偷偷往上瞟。 最规矩的男人遇到最不规矩的女人时,也会忍不住要去偷偷去瞧两眼的。 过了很久,车门才打开,又过了很久,车门里才露出一双脚来。 一双纤纤瘦瘦的脚,穿着双软缎子的绣花鞋,居然没穿袜子。 只看到这双脚,男人的三魂六魄已经飞走一大半。 脚刚沾着地,又马上缩回。
Python
UTF-8
607
2.65625
3
[]
no_license
import sys from pymongo import Connection from pymongo.errors import ConnectionFailure import pymongo """ Connect to MongoDB """ try: c = Connection(host="localhost", port=27017, safe=True) print "Connected successfully" except ConnectionFailure, e: sys.stderr.write("Could not connect to MongoDB: %s" % e) sys.exit(1) # Get a Database handle to a database named "mydb" dbh = c["blog"] assert dbh.connection == c print "Successfully set up a database handle" def test(): cursor = dbh.posts.find().sort('date',pymongo.DESCENDING).limit(10) for i in cursor: print i test()
C#
UTF-8
777
2.640625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotate : MonoBehaviour { public float speed = 30f; public bool rl = false; public bool rr = false; public void Update() { if(rl){ RotateLeft(); } if (rr) { RotateRight(); } } public void RotateLeft() { rl = true; rr = false; this.gameObject.transform.Rotate(Vector3.up, speed * Time.deltaTime); } public void RotateRight() { rr = true; rl = false; this.gameObject.transform.Rotate(Vector3.down, speed * Time.deltaTime); } public void StopRotating(){ rr = false; rl = false; } }
Python
UTF-8
3,703
2.625
3
[ "MIT" ]
permissive
from resistance.game import Game from resistance.mct.mct_agent import MCTAgent from resistance.mct.li_agent import MAgent from resistance.random_agent import RandomAgent def test(n_game, players): scoreboard = {agent.name: {'spy': [0, 0], 'resistance': [ 0, 0], 'total': [0, 0]} for agent in players} # Loading pre-learned dictionary mctnodes = MCTAgent.load('mctnodes_dict.json',) # Not loading # mctnodes = {} for game_ind in range(n_game): print(game_ind, 'start') game = Game(players) for agent in game.agents: if type(agent) == MCTAgent: agent.mctNodes = mctnodes game.play() for agent in game.agents: if agent.name == "m1" or agent.name == "m2" or agent.name == "m3" or agent.name == "r1" or agent.name == "r2": if agent.is_spy(): scoreboard[agent.name]['spy'][1] += 1 scoreboard[agent.name]['total'][1] += 1 if game.missions_lost >= 3: scoreboard[agent.name]['spy'][0] += 1 scoreboard[agent.name]['total'][0] += 1 else: scoreboard[agent.name]['resistance'][1] += 1 scoreboard[agent.name]['total'][1] += 1 if game.missions_lost < 3: scoreboard[agent.name]['resistance'][0] += 1 scoreboard[agent.name]['total'][0] += 1 if agent.name == "b1": if agent.is_spy(): scoreboard[agent.name]['spy'][1] += 1 scoreboard[agent.name]['total'][1] += 1 if game.missions_lost >= 3: scoreboard[agent.name]['spy'][0] += 1 scoreboard[agent.name]['total'][0] += 1 else: scoreboard[agent.name]['resistance'][1] += 1 scoreboard[agent.name]['total'][1] += 1 if game.missions_lost < 3: scoreboard[agent.name]['resistance'][0] += 1 scoreboard[agent.name]['total'][0] += 1 if agent.name == "l1" or agent.name == 'l2' or agent.name == 'l3': if agent.is_spy: scoreboard[agent.name]['spy'][1] += 1 scoreboard[agent.name]['total'][1] += 1 if game.missions_lost >= 3: scoreboard[agent.name]['spy'][0] += 1 scoreboard[agent.name]['total'][0] += 1 else: scoreboard[agent.name]['resistance'][1] += 1 scoreboard[agent.name]['total'][1] += 1 if game.missions_lost < 3: scoreboard[agent.name]['resistance'][0] += 1 scoreboard[agent.name]['total'][0] += 1 print(agent.name, scoreboard[agent.name]) # Hybrid mode open # agents = [ # RandomAgent(name="r1"), # RandomAgent(name='r2'), # MCTAgent(name='m1', sharedMctNodes={}, isTest=True), # MCTAgent(name='m2', sharedMctNodes={}, isTest=True), # MCTAgent(name='m3', sharedMctNodes={}, isTest=True), # ] # Model based agent # agents = [ # RandomAgent(name="r1"), # RandomAgent(name='r2'), # MAgent(name="l1"), # MAgent(name="l2"), # MAgent(name="l3"), # ] # Hybrid close agents = [ RandomAgent(name="r1"), RandomAgent(name='r2'), MCTAgent(name='m1', sharedMctNodes={}, isTest=False), MCTAgent(name='m2', sharedMctNodes={}, isTest=False), MCTAgent(name='m3', sharedMctNodes={}, isTest=False), ] test(80000, agents)
Python
UTF-8
128
3.40625
3
[]
no_license
lin = input() l = lin.split(" ") a = int(l[0]) b = int(l[1]) c = int(l[2]) if a < b < c: print('Yes') else: print('No')
Java
UTF-8
570
2.375
2
[ "MIT" ]
permissive
package permutu.Models; public class StreamMessageModel { private String playerLogin; private String[] selectedBlocks; public StreamMessageModel(String playerLogin, String[] selectedBlocks) { this.selectedBlocks = selectedBlocks; this.playerLogin = playerLogin; } public String getPlayerLogin() { return playerLogin; } public String[] getselectedBlocks() { return selectedBlocks; } public void setselectedBlocks(String[] selectedBlocks) { this.selectedBlocks = selectedBlocks; } }
PHP
UTF-8
5,005
2.96875
3
[]
no_license
<?php /** * The contents of this source file is the sole property of Cream Union Ltd. * Unauthorized duplication or access is prohibited. * * * @package Cream * @author Cream Dev Team * @copyright Copyright (C) 2004-2012 Cream Union Ltd. * @license http://www.crea-m.com/user_guide/license.html * @link http://www.crea-m.com * @since Version 1.0 */ class Database { protected $user; protected $pass; protected $dbhost; protected $dbname; protected $conn; private $pre = ""; private $error = ""; private $errno = 0; private $affected_rows = 0; private $query_id = 0; public function __construct($server, $user, $pass, $database, $pre='') { $this->user = $user; $this->pass = $pass; $this->dbhost = $server; $this->dbname = $database; $this->pre = $pre; } public function connect($new_link=false) { $this->conn = @mysql_connect($this->dbhost,$this->user,$this->pass, $new_link); if (!is_resource($this->conn)) { $this->oops("Could not connect to server: <b>{$this->dbhost}</b>."); } if (!mysql_select_db($this->dbname, $this->conn)) { $this->oops("Could not open database: <b>{$this->dbname}</b>."); } } public function close() { if (!$this->conn) return false; if ($this->conn) { if (!@mysql_close($this->conn)) { $this->oops("Connection close failed."); } } $this->conn = false; return true; } public function escape($string) { if (get_magic_quotes_runtime()) $string = stripslashes($string); return @mysql_real_escape_string($string, $this->conn); } public function query($sql) { $this->query_id = @mysql_query($sql, $this->conn); if (!$this->query_id) { $this->oops("<b>MySQL Query fail:</b> $sql"); return 0; } $this->affected_rows = @mysql_affected_rows($this->conn); return $this->query_id; } public function fetch_array($query_id = -1) { if ($query_id != -1) { $this->query_id = $query_id; } if (isset($this->query_id)) { $record = @mysql_fetch_assoc($this->query_id); } else { $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched."); } return $record; } public function fetch_all_array($sql) { $query_id = $this->query($sql); $out = array(); while ($row = $this->fetch_array($query_id)) { $out[] = $row; } $this->free_result($query_id); return $out; } public function free_result($query_id = -1) { if ($query_id != -1) { $this->query_id = $query_id; } if ($this->query_id != 0 && !@mysql_free_result($this->query_id)) { $this->oops("Result ID: <b>$this->query_id</b> could not be freed."); } } public function query_first($query_string) { $query_id = $this->query($query_string); $out = $this->fetch_array($query_id); $this->free_result($query_id); return $out; } public function query_update($table, $data, $where='1') { $q="UPDATE `".$this->pre.$table."` SET "; foreach ($data as $key=>$val) { if (strtolower($val) == 'null') $q.= "`$key` = NULL, "; elseif (strtolower($val)=='now()') $q.= "`$key` = NOW(), "; elseif (preg_match("/^increment\((\-?\d+)\)$/i",$val,$m)) $q.= "`$key` = `$key` + $m[1], "; else $q.= "`$key`='".$this->escape($val)."', "; } $q = rtrim($q, ', ') . ' WHERE '.$where.';'; return $this->query($q); } public function query_insert($table, $data) { $q="INSERT INTO `".$this->pre.$table."` "; $v=''; $n=''; foreach ($data as $key=>$val) { $n.="`$key`, "; if (strtolower($val) == 'null') $v.="NULL, "; elseif (strtolower($val) == 'now()') $v.="NOW(), "; else $v.= "'".$this->escape($val)."', "; } $q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");"; if($this->query($q)) { return mysql_insert_id($this->conn); } else return false; } public function oops($msg='') { if(is_resource($this->conn)) { $this->error = mysql_error($this->conn); $this->errno = mysql_errno($this->conn); } else { $this->error = mysql_error(); $this->errno = mysql_errno(); } ?> <table align="center" border="1" cellspacing="0" style="background:white;color:black;width:80%;"> <tr> <th colspan=2>Database Error</th> </tr> <tr> <td align="right" valign="top">Message:</td> <td><?php echo $msg; ?></td> </tr> <?php if (!empty($this->error)) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>'.$this->error.'</td></tr>'; ?> <tr> <td align="right">Date:</td> <td><?php echo date("l, F j, Y \a\\t g:i:s A"); ?></td> </tr> <?php if (!empty($_SERVER['REQUEST_URI'])) echo '<tr><td align="right">Script:</td><td><a href="'.$_SERVER['REQUEST_URI'].'">'.$_SERVER['REQUEST_URI'].'</a></td></tr>'; ?> <?php if (!empty($_SERVER['HTTP_REFERER'])) echo '<tr><td align="right">Referer:</td><td><a href="'.$_SERVER['HTTP_REFERER'].'">'.$_SERVER['HTTP_REFERER'].'</a></td></tr>'; ?> </table> <?php } } ?>
Java
UTF-8
422
2.046875
2
[ "Apache-2.0" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pikater.core.ontology.subtrees.metadata.attributes; /** * * @author Kuba */ public class IntegerAttributeMetadata extends NumericalAttributeMetadata { private static final long serialVersionUID = 2610042360742781585L; @Override public String getType() { return "Integer"; } }
Java
UTF-8
2,322
2.453125
2
[]
no_license
package androidx.work; import androidx.work.WorkInfo; import java.util.ArrayList; import java.util.List; public final class WorkQuery { private final List<WorkInfo.State> mStates; private final List<String> mTags; private final List<String> mUniqueWorkNames; WorkQuery(Builder builder) { this.mUniqueWorkNames = builder.mUniqueWorkNames; this.mTags = builder.mTags; this.mStates = builder.mStates; } public List<String> getUniqueWorkNames() { return this.mUniqueWorkNames; } public List<String> getTags() { return this.mTags; } public List<WorkInfo.State> getStates() { return this.mStates; } public static final class Builder { List<WorkInfo.State> mStates = new ArrayList(); List<String> mTags = new ArrayList(); List<String> mUniqueWorkNames = new ArrayList(); private Builder() { } public static Builder fromUniqueWorkNames(List<String> list) { Builder builder = new Builder(); builder.addUniqueWorkNames(list); return builder; } public static Builder fromTags(List<String> list) { Builder builder = new Builder(); builder.addTags(list); return builder; } public static Builder fromStates(List<WorkInfo.State> list) { Builder builder = new Builder(); builder.addStates(list); return builder; } public Builder addUniqueWorkNames(List<String> list) { this.mUniqueWorkNames.addAll(list); return this; } public Builder addTags(List<String> list) { this.mTags.addAll(list); return this; } public Builder addStates(List<WorkInfo.State> list) { this.mStates.addAll(list); return this; } public WorkQuery build() { if (!this.mUniqueWorkNames.isEmpty() || !this.mTags.isEmpty() || !this.mStates.isEmpty()) { return new WorkQuery(this); } throw new IllegalArgumentException("Must specify uniqueNames, tags or states when building a WorkQuery"); } } }
Java
UTF-8
146
2.09375
2
[]
no_license
package Object; public class SmallHouse extends MapObject { public SmallHouse(int x, int y) { super(x, y); createRect(x, y, 92, 43); } }
Python
UTF-8
347
4.03125
4
[]
no_license
#input 1=" programming is fun" #input 2= "m" #output = [6,7] sentence = "I decided to learn how to program" letter= "m" output= [] #enumerate will allow you to track the current location or idx for current_location, current_letter in enumerate(sentence): if current_letter == letter: output.append(current_location) print (output)
C#
UTF-8
2,288
2.625
3
[]
no_license
/* * (c) 2008 MOSA - The Managed Operating System Alliance * * Licensed under the terms of the New BSD License. * * Authors: * Kai P. Reisert <kpreisert@googlemail.com> */ using System; using Mosa.Runtime.CompilerFramework; using NDesk.Options; namespace Mosa.Tools.Compiler { /// <summary> /// Selector proxy type for the architecture. /// </summary> public class ArchitectureSelector : IHasOptions { /// <summary> /// Holds the real stage implementation to use. /// </summary> private IArchitecture implementation; /// <summary> /// Initializes a new instance of the ArchitectureSelector class. /// </summary> public ArchitectureSelector() { this.implementation = null; } private IArchitecture SelectImplementation(string architecture) { switch (architecture.ToLower()) { case "x86": return Mosa.Platform.x86.Architecture.CreateArchitecture(Mosa.Platform.x86.ArchitectureFeatureFlags.AutoDetect); case "x64": default: throw new OptionException(String.Format("Unknown or unsupported architecture {0}.", architecture), "Architecture"); } } /// <summary> /// Adds the additional options for the parsing process to the given OptionSet. /// </summary> /// <param name="optionSet">A given OptionSet to add the options to.</param> public void AddOptions(OptionSet optionSet) { optionSet.Add( "a|Architecture=", "Select one of the MOSA architectures to compile for [{x86}].", delegate(string arch) { this.implementation = SelectImplementation(arch); } ); } /// <summary> /// Gets the selected architecture. /// </summary> public IArchitecture Architecture { get { CheckImplementation(); return this.implementation; } } /// <summary> /// Gets a value indicating whether an implementation is selected. /// </summary> /// <value> /// <c>true</c> if an implementation is selected; otherwise, <c>false</c>. /// </value> public bool IsConfigured { get { return (this.implementation != null); } } /// <summary> /// Checks if an implementation is set. /// </summary> private void CheckImplementation() { if (this.implementation == null) throw new InvalidOperationException(@"ArchitectureFormatSelector not initialized."); } } }
Python
UTF-8
1,198
3.0625
3
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from .entities import CimDataCollection class VesselPastStopsWrapper: """Wrapper to get vessel past stops, it will be padding with None if stops number less than configured one. Examples: .. code-block:: python # Get past stops of vessel 0. stops = data_cntr.vessel_past_stops[0] """ def __init__(self, data: CimDataCollection): self._stop_number = data.past_stop_number self._stops = data.vessels_stops def __getitem__(self, key): assert type(key) == tuple or type(key) == list assert len(key) == 3 vessel_idx = key[0] last_loc_idx = key[1] next_loc_idx = key[2] # ignore current port if parking start = next_loc_idx + (1 if last_loc_idx == next_loc_idx else 0) # avoid negative index start = max(next_loc_idx - self._stop_number, 0) past_stop_list = self._stops[vessel_idx][start: next_loc_idx] # padding with None for _ in range(self._stop_number - len(past_stop_list)): past_stop_list.insert(0, None) return past_stop_list
Python
UTF-8
3,249
3.171875
3
[]
no_license
import numpy as np import math import plotly.graph_objects as go def sphericalRelative(t1_rad, t2_rad, targetP, r): if t1_rad > 1.5707: #for semisphere t1_rad = t1_rad/2 # for reference https://mathinsight.org/spherical_coordinates x = targetP[0] + (r * math.sin(t1_rad) * math.cos(t2_rad)) y = targetP[1] + (r * math.sin(t1_rad) * math.sin(t2_rad)) z = targetP[2] + (r * math.cos(t1_rad)) quadrant = 0 if 0 >= t2_rad and t2_rad <= 1.5707963267948966: quadrant = 1 elif 1.5882496193148399 >= t2_rad and t2_rad <= 3.141592653589793: quadrant = 2 elif 3.1590459461097367 >= t2_rad and t2_rad <= 4.71238898038469: quadrant = 3 elif 4.729842272904633 >= t2_rad and t2_rad <= 6.283185307179586: quadrant = 4 return [[x,y,z],quadrant] def RotationMatrix(xtheta,ytheta): xmatrix = np.asarray([[1,0,0],[0,np.cos(xtheta),np.sin(xtheta)],[0,-np.sin(xtheta),np.cos(xtheta)]]) ymatrix = np.asarray([[np.cos(ytheta),0,-np.sin(ytheta)],[0,1,0],[np.sin(ytheta),0,np.cos(ytheta)]]) return xmatrix,ymatrix def getSphericalCoords(targetP, radius): stack = [] stack.append([[targetP[0],targetP[1],targetP[2]+radius],0]) for i in [35,50,60]: for j in [15,45,120,180,300,360]: val = sphericalRelative(math.radians(i), math.radians(j), targetP, radius) stack.append(val) return stack def getSphericalCoords1(targetP, radius,xdeg,ydeg): stack = [] targetP1 =[targetP[0],targetP[1],targetP[2]+radius] stack.append([targetP1,0]) stack.append([[targetP[0]+radius,targetP[1],targetP[2]],0]) stack.append([[targetP[0],targetP[1]+radius,targetP[2]],0]) vector = np.subtract(targetP1,targetP) unit_v = vector/np.linalg.norm(vector) print(unit_v) rx,ry = RotationMatrix(np.radians(xdeg),np.radians(ydeg)) R = rx*ry print(rx,ry) print(R) rotvecx = np.dot(rx,unit_v) rotvecy = np.dot(ry,rotvecx) print("vector1",rotvecy) vecrot = np.dot(R,unit_v) point = targetP + radius*rotvecy print(point) stack.append([point,0]) return stack def AnglebtwnVecs(vec1,vec2): angle = np.arccos(np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))) # print("Angle : {}".format((angle*180)/math.pi)) return math.degrees(angle) if __name__ == '__main__': rad = 10 InpPoint = [433,221,332] tmpStack = np.asarray(getSphericalCoords1(InpPoint, rad,45,180)) # Choose some random 3d point for InpPoint allpnts = np.asarray(tmpStack[:,0]) xp = [] yp = [] zp = [] fig = go.Figure() for i in range(len(allpnts)-1): xp.append(allpnts[i][0]) yp.append(allpnts[i][1]) zp.append(allpnts[i][2]) data = go.Scatter3d(x=[InpPoint[0],allpnts[i][0]],y=[InpPoint[1],allpnts[i][1]],z=[InpPoint[2],allpnts[i][2]]) fig.add_trace(data) dist = np.linalg.norm((np.subtract(InpPoint,allpnts[3]))) data1 = go.Scatter3d(x=[InpPoint[0],allpnts[3][0]],y=[InpPoint[1],allpnts[3][1]],z=[InpPoint[2],allpnts[3][2]],marker=dict(size=[50,50],color = ('rgb(22, 96, 167)'))) fig.add_trace(data1) print(dist) print(allpnts[3]) fig.show()
Shell
UTF-8
5,834
3.203125
3
[]
no_license
# ~/.bashrc: executed by bash(1) for non-login shells. # see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) # for examples export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/mnt/c/Users/crobinson13/AppData/Local/Programs/"Microsoft VS Code"/bin:/usr/bin/lua; export DOCKER_HOST=tcp://localhost:2375 export FZF_DEFAULT_COMMAND='rg --files --follow --no-ignore-vcs --hidden -g "!{node_modules/*,.git/*,vendor/*}"' #If not running interactively, don't do anything case $- in *i*) ;; *) return;; esac # don't put duplicate lines or lines starting with space in the history. # See bash(1) for more options HISTCONTROL=ignoreboth # append to the history file, don't overwrite it shopt -s histappend # for setting history length see HISTSIZE and HISTFILESIZE in bash(1) HISTSIZE=1000 HISTFILESIZE=2000 # check the window size after each command and, if necessary, # update the values of LINES and COLUMNS. shopt -s checkwinsize # If set, the pattern "**" used in a pathname expansion context will # match all files and zero or more directories and subdirectories. #shopt -s globstar # make less more friendly for non-text input files, see lesspipe(1) [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" # set variable identifying the chroot you work in (used in the prompt below) if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then debian_chroot=$(cat /etc/debian_chroot) fi # set a fancy prompt (non-color, unless we know we "want" color) case "$TERM" in xterm-color|*-256color) color_prompt=yes;; esac # uncomment for a colored prompt, if the terminal has the capability; turned # off by default to not distract the user: the focus in a terminal window # should be on the output of commands, not on the prompt #force_color_prompt=yes if [ -n "$force_color_prompt" ]; then if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then # We have color support; assume it's compliant with Ecma-48 # (ISO/IEC-6429). (Lack of such support is extremely rare, and such # a case would tend to support setf rather than setaf.) color_prompt=yes else color_prompt= fi fi black="\e[0;30m" red="\e[1;31m" green="\e[0;32m" yellow="\e[0;33m" blue="\e[0;34m" purple="\e[0;35m" cyan="\e[0;36m" white="\e[0;37m" if [ "$color_prompt" = yes ]; then #PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u\[\033[00m\]:\[\033[01;34m\]\w\[\033[10m\]\$ ' PS1='\[\033[91m\]<\[\033[96m\]W\[\033[32m\]S\[\033[33m\]L\[\033[01;91m\]>\[\033[0m\]:\[\033[95m\]\w\[\033[96m\]\$\[\033[0m\] ' else PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' fi unset color_prompt force_color_prompt # If this is an xterm set the title to user@host:dir case "$TERM" in xterm*|rxvt*) PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1" ;; *) ;; esac # enable color support of ls and also add handy aliases if [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' #alias dir='dir --color=auto' #alias vdir='vdir --color=auto' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' fi # colored GCC warnings and errors #export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01' # some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' alias lr='source ranger' alias up='sudo apt-get update' alias br='cd /home/force;vim .bashrc' alias todo='cd /home/force;vim todo' alias reward='cd /home/force;vim reward' alias sbr='cd /home/force;source .bashrc' alias ping='ping -c 5' alias yd='youtube-dl -x --audio-format mp3' alias :q='exit' alias uzt='cd /home/force/Transport;unzip Transport.zip' alias f='firefox &' alias c='code .' # Navagation alias gu='cd /home/force/Documents' alias gituser='xdg-open https://github.com/Lambparade' alias ..='cd ..' # WebAlaises # WebAlaises alias wk='xdg-open https://10fastfingers.com/typing-test/english &' alias gituser='xdg-open https://github.com/Lambparade' # WebAlaises # Computer Info alias cpudetail='sudo dmidecode -t 4' alias cpuinfo='screenfetch' # Computer Info # i3 Config alias i3='cd /home/force/.config/i3;vim config' alias i3duel='xrandr --output VGA1 --auto --left-of LVDS1' # i3 Config alias filesize='du -sh' # Wifi alias wifi='nmtui' # Wifi # Wallpaper alias wp='nitrogen' alias trans='compton &' # Wallpaper # For Work alias work='cd /mnt/c/Workspace' alias vweb='cd /mnt/c/Workspace/web/web && vim' alias curlfix='sudo ip link set dev eth0 mtu 1400' # For Work # ServiceUtil alias slist='service --status-all' # alias vim='nvim' # Add an "alert" alias for long running commands. Use like so: # sleep 10; alert alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' # Alias definitions. # You may want to put all your additions into a separate file like # ~/.bash_aliases, instead of adding them here directly. # See /usr/share/doc/bash-doc/examples in the bash-doc package. if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
C#
UTF-8
477
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOPTutorial.Vehicles { public class Truck : Vehicle,IVehicle { public string BedLength { get; set; } public string DescribeVehicle() { return "truck"; } public string DescribeEngine() { return Engine.Horsepower.ToString(); } } }
C++
UTF-8
37,539
2.546875
3
[]
no_license
#include <stdio.h> #include <iostream> #include "STP.h" #include <cassert> //#include <random> #include <cstdlib> #include <ctime> #include <time.h> #include <string.h> #include "Timer.h" #include <deque> #include <queue> #include <functional> #include <fstream> #include "IDAStar.h" #include "DFID.h" #include <iostream> #include <iosfwd> #include <string> #include <sstream> #include "PDB.h" #include "BFS.h" #include "ManhattanDistance.h" #include "InefficientAStar.h" #include "GridWorld.h" #include "AStar.h" #include "OctileHeuristic.h" #include "DifferentialHeuristic.h" #include "MaxHeuristic.h" #include "CanonicalAStar.h" //#define _CRT_SECURE_NO_WARNINGS STPState RandomWalk2(STP game, STPState state, uint64_t n); void userPlay(); // A random walk that doesn't go back to the parent state. // should in theory get harder to solve as the number of steps increases. STPState RandomWalkMoreDifficult(STP game, STPState state, uint64_t n); void printPath(std::vector<STPSlideDir>& path); void applyAndPrintOperators(STPState originalState, STP game, std::vector<STPSlideDir>& parentPath); void STPTimeTests(); int manhattanDistance(STP& game, STPState & s) { //printf("calculating heurisitc\n"); // calculate num moves for each num to get to its goal. // Need to know the goal location for each number. // how do without hard code in the numbers // would be nice to have a map from number to goal (x,y) // so could have a map to an array[2]; // now, just loop through the board and easy. bool ignoreBlank = true; int score = 0; for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { // score will = abs(dx) + abs(dy) // so dy = row - map[#].y // so going to ignore the blank if (ignoreBlank && s.board[row][col] == 0) { continue; } int dx = abs(col - game.goals[s.board[row][col]].x); int dy = abs(row - game.goals[s.board[row][col]].y); score += (dx + dy); } } return score; } //template<typename T> void print_queue(T q) { // while (!q.empty()) { // std::cout << q.top() << " "; // q.pop(); // } // std::cout << '\n'; //} std::ostream& operator<<(std::ostream& out, const aStarStruct& s) { // and why not print out the costs // out << "----Printing aStartState ----- \n"; out << "Fcost: " << s.fcost << ", hcost: " << s.hcost << ", gcost: " << s.gcost << "\n"; //s.state.printState(); for (int y = 0; y < ROWS; y++) { for (int x = 0; x < COLS; x++) { if (s.state.board[y][x] < 10) out << s.state.board[y][x] << " "; else out << s.state.board[y][x] << " "; } out << "\n"; } return out; } std::vector<DifferentialHeuristic> setupRandomDiffHeuristic(GridWorld& gridWorld) { int randx = 0; int randy = 0; // setting pivot 1 while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); printf("randx: %d, randy: %d\n", randx, randy); if (gridWorld.isValid({ randx, randy })) { break; } } GridWorldState ssss(randx, randy); printf("dh1\n"); DifferentialHeuristic dh1(gridWorld, ssss); // setting pivot 2 while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); printf("randx: %d, randy: %d\n", randx, randy); if (gridWorld.isValid({ randx, randy })) { break; } } ssss.curX = randx; ssss.curY = randy; printf("dh2\n"); DifferentialHeuristic dh2(gridWorld, ssss); //gridWorld.setPivot(ssss); //gridWorld.printWorldStateSpecific(startState, goalState); while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); //printf("randx: %d, randy: %d\n", randx, randy); if (gridWorld.isValid({ randx, randy })) { break; } } ssss.curX = randx; ssss.curY = randy; printf("dh3\n"); DifferentialHeuristic dh3(gridWorld, ssss); while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); //printf("randx: %d, randy: %d\n", randx, randy); if (gridWorld.isValid({ randx, randy })) { break; } } ssss.curX = randx; ssss.curY = randy; printf("dh4\n"); DifferentialHeuristic dh4(gridWorld, ssss); gridWorld.setPivot(ssss); while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); //printf("randx: %d, randy: %d\n", randx, randy); if (gridWorld.isValid({ randx, randy })) { break; } } ssss.curX = randx; ssss.curY = randy; printf("dh5\n"); DifferentialHeuristic dh5(gridWorld, ssss); gridWorld.setPivot(ssss); // this method seems to work. std::vector<DifferentialHeuristic> dhs; for (int i = 0; i < 5; i++) { while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); //printf("randx: %d, randy: %d\n", randx, randy); if (gridWorld.isValid({ randx, randy })) { ssss.curX = randx; ssss.curY = randy; dh5 = DifferentialHeuristic(gridWorld, ssss); dhs.push_back(dh5); gridWorld.setPivot(dh5.getPivot()); break; } } } /*dhs.push_back(dh1); dhs.push_back(dh2); dhs.push_back(dh3); dhs.push_back(dh4); dhs.push_back(dh5); gridWorld.setPivot(dh1.getPivot()); gridWorld.setPivot(dh2.getPivot()); gridWorld.setPivot(dh3.getPivot()); gridWorld.setPivot(dh4.getPivot());*/ return dhs; } std::vector<DifferentialHeuristic> setUpOptimalDifferentialHeuristic(GridWorld& gridWorld) { // pick 20 random(valid) points. These will be test points. int numTestPoints = 20; std::vector<GridWorldState> testPoints; int randx; int randy; for (int i = 0; i < numTestPoints; i++) { while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); //printf("randx: %d, randy: %d\n", randx, randy); // want to add a check to make sure dont add the same point twice. GridWorldState s(randx, randy); if (gridWorld.isValid({ randx, randy }) && (std::find(testPoints.begin(), testPoints.end(), s) == testPoints.end())) { // Think should be able to just make one in here. //GridWorldState s(randx, randy); testPoints.push_back(s); break; } } /*printf("i : %d: ", i); testPoints[i].printState();*/ } // So that works. now, need to pick 20 new random points as potential pivot points. // then build the DH for each one., then for each pivot point, check the sum of the heuristic to all pairs of test points. // which ever sum is the largest, pick that pivot, then repeat 5 times. std::vector<DifferentialHeuristic> dhs; MaxHeuristic<GridWorldState> differentialHeuristic; // need to calc the maxHeuristic q sum, which will be previous q + the best pivot int numDiffHeurs = 5; DifferentialHeuristic dheurs[5]; for (int j = 0; j < numDiffHeurs; j++) { //printf("Starting pivot pick.\n"); // now need to do the picking pivot points. std::vector<GridWorldState> potentialPivots; std::vector<DifferentialHeuristic> potDhs; int maxSum = 0; int maxIndex = 0; for (int i = 0; i < numTestPoints; i++) { while (true) { randx = rand() % (gridWorld.WORLDWIDTH - 1); randy = rand() % (gridWorld.WORLDHEIGHT - 1); //printf("randx: %d, randy: %d\n", randx, randy); // want to add a check to make sure dont add the same point twice. GridWorldState s(randx, randy); if (gridWorld.isValid({ randx, randy }) && (std::find(testPoints.begin(), testPoints.end(), s) == testPoints.end()) && (std::find(potentialPivots.begin(), potentialPivots.end(), s) == potentialPivots.end())) { // guess just make the differential heurisitc DifferentialHeuristic dh(gridWorld, s); potDhs.push_back(dh); potentialPivots.push_back(s); break; } } } // now should have 20 differential heuristics. // then for each one.. calculate the heuristic between all pairs of points in the test points(a double loop, i=0;i<n-1 - j = i; j<n for (int i = 0; i < potDhs.size(); i++) { //printf("i(%d) Pivot: ", i); //potDhs[i].getPivot().printState(); // here make a maxHeuristic of the final one, and adding in this DiffHeur // think need a case if on the first iteration. MaxHeuristic<GridWorldState> tempHeur; if (j != 0) { //printf("adding previous heuristic j:%d\n", j); //tempHeur.addHeuristic(&differentialHeuristic); //printf("Added previous heuristic\n"); //for (int z = 0; z < dhs.size(); z++) { // tempHeur.addHeuristic(&dhs[i]); //} // even this way crashes it.... for (int z = 0; z < j; z++) { tempHeur.addHeuristic(&dheurs[z]); } } tempHeur.addHeuristic(&potDhs[i]); //printf("added potential\n"); int sum = 0; for (int m = 0; m < testPoints.size() - 1; m++) { //printf("About to use heuristic\n"); for (int q = m; q < testPoints.size(); q++) { // here then, want to use the previous max of differential heuristics, with the ith potDh, and do that max. //sum += potDhs[i].h(testPoints[m], testPoints[q]); //if (j == 1) { // //sum += dhs[1].h(testPoints[m], testPoints[1]); // this fails, so for some reason now, holding that heuristic is invalid... // sum += dheurs[0].h(testPoints[m], testPoints[1]); // this fails, so for some reason now, holding that heuristic is invalid... //} //else { // sum += tempHeur.h(testPoints[m], testPoints[q]); // so this call causes a problem... //} sum += tempHeur.h(testPoints[m], testPoints[q]); // this now works when using the array. //std::cout << "added for 1 point\n" << std::endl; //printf("Added the heuristic m: %d, q: %d\n", m, q); } //printf("finished comparision of 1 point.\n"); } //printf("i(%d) heuristic sum: %d \n", i, sum); if (sum > maxSum) { maxSum = sum; maxIndex = i; } } //printf("Best Heuristic index: %d\n", maxIndex); // then want to add the maxIndex Diff Heur to the final list of Dh's //dhs.push_back(potDhs[maxIndex]); // this should work. dheurs[j] = potDhs[maxIndex]; //differentialHeuristic.addHeuristic(&potDhs[maxIndex]); //printf("added something to the final heuristic finished j:%d \n", j); //getchar(); } // then maybe go thru the diff heurs and make sure they are actually there... for (int i = 0; i < 5; i++) { dhs.push_back(dheurs[i]); } printf("The optimal Pivot Locations: \n"); for (int i = 0; i < dhs.size(); i++) { dhs[i].getPivot().printState(); } //getchar(); return dhs; } void testMapBenchmarks(std::string mapPath, std::string benchProblemsPath) { GridWorld gridWorld(mapPath); Timer timer; //gridWorld.printWorld(); //printf("=========\n"); ManhattanDistance<GridWorldState> manDist; OctileHeuristic octileHeuristic; std::vector<GridWorldMovements> opPath; const int numHsss = 1; Heuristic<GridWorldState> *heuristiclistastar[numHsss] = { &octileHeuristic }; MaxHeuristic<GridWorldState> maxDifferentialHeuristic; std::vector<DifferentialHeuristic> dhs = setupRandomDiffHeuristic(gridWorld); for (int i = 0; i < dhs.size(); i++) { maxDifferentialHeuristic.addHeuristic(&dhs[i]); } MaxHeuristic<GridWorldState> maxOctileDH; maxOctileDH.addHeuristic(&maxDifferentialHeuristic); maxOctileDH.addHeuristic(&octileHeuristic); AStar < GridWorld, GridWorldState, GridWorldMovements> astar; CanonicalAStar<GridWorld, GridWorldState, GridWorldMovements> canonicalAstar; gridWorld.setCanGoDiagonal(true); // is true by default. //astar. int totalProblems = 0; double efficientOctileTotalTime = 0; double efficientDHTotalTime = 0; double DHOctileTotalTime = 0; double canoncicalDHOctileTotalTime = 0; double jumpPointTotalTime = 0; uint64_t DHNodesExpanded = 0; uint64_t OctileNodesExpanded = 0; uint64_t DHOctileNodesExpanded = 0; uint64_t CanonicalNodesExpanded = 0; uint64_t JumpPointNodesExpanded = 0; // maybe get gcost of the goal to check if found it with right cost... // here need to read the file, there are 430 lines in this file. // set the start and the goal for each, then repeat. std::ifstream benchProblems(benchProblemsPath); //"orz301d.map.scen" if (!benchProblems) { printf("asldkfjasldfjalesfjalsdkfj\n"); exit(2); } std::string line; if (benchProblems.is_open()) { int j = 0; int m = 0; benchProblems >> line; benchProblems >> line; while (benchProblems >> line) { while (m < 3) { benchProblems >> line; m++; } m = 0; int startX; int startY; int goalX; int goalY; benchProblems >> startX; benchProblems >> startY; benchProblems >> goalX; benchProblems >> goalY; std::cout << "(startX, startY): (" << startX << "," << startY << ") goalX, goalY: (" << goalX << "," << goalY << ")\n"; //std::cout << line << "\n"; benchProblems >> line; // Now use those coordinates to path find. yay GridWorldState startState(startX, startY); GridWorldState goalState(goalX, goalY); int count = 0; astar.setHeuristicWeight(1); gridWorld.clearOpenClosed(); //printf("A star my openlist.\n"); timer.StartTimer(); astar.GetPath3(gridWorld, startState, goalState, &octileHeuristic, true, kgNOTHING); timer.EndTimer(); double effTime = timer.GetElapsedTime(); opPath = astar.getDirections(); int a = opPath.size(); float optimalGcost = astar.getGCost(goalState); printf("Octile::\t\t\t A star my openlist elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %d, Optimal Gcost: %f\n", timer.GetElapsedTime(), astar.GetNodesExpanded(), a, optimalGcost); OctileNodesExpanded += astar.GetNodesExpanded(); efficientOctileTotalTime += effTime; // now with differential heuristic. gridWorld.clearOpenClosed(); timer.StartTimer(); astar.GetPath3(gridWorld, startState, goalState, &maxDifferentialHeuristic, true, kgNOTHING); timer.EndTimer(); effTime = timer.GetElapsedTime(); opPath = astar.getDirections(); a = opPath.size(); optimalGcost = astar.getGCost(goalState); printf("Differential Heuristic::\t A star my openlist elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %d, Optimal G cost: %f\n", timer.GetElapsedTime(), astar.GetNodesExpanded(), a, optimalGcost); DHNodesExpanded += astar.GetNodesExpanded(); efficientDHTotalTime += effTime; // now using max of octile and the diffheuristics. gridWorld.clearOpenClosed(); timer.StartTimer(); astar.GetPath3(gridWorld, startState, goalState, &maxOctileDH, true, kgNOTHING); timer.EndTimer(); effTime = timer.GetElapsedTime(); opPath = astar.getDirections(); a = opPath.size(); optimalGcost = astar.getGCost(goalState); printf("Differential Heuristic & Octile::A star my openlist elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %d, Optimal Gcost: %f\n", timer.GetElapsedTime(), astar.GetNodesExpanded(), a, optimalGcost); DHOctileNodesExpanded += astar.GetNodesExpanded(); DHOctileTotalTime += effTime; // Canonical A star. gridWorld.clearOpenClosed(); timer.StartTimer(); canonicalAstar.GetPath3(gridWorld, startState, goalState, &maxOctileDH, true, kgNOTHING); timer.EndTimer(); effTime = timer.GetElapsedTime(); opPath = canonicalAstar.getDirections(); a = opPath.size(); optimalGcost = canonicalAstar.getGCost(goalState); printf("Canonical A Star::A star my openlist elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %d, Optimal Gcost: %f\n", timer.GetElapsedTime(), canonicalAstar.GetNodesExpanded(), a, optimalGcost); CanonicalNodesExpanded += canonicalAstar.GetNodesExpanded(); canoncicalDHOctileTotalTime += effTime; // Jump Point Search. gridWorld.clearOpenClosed(); timer.StartTimer(); canonicalAstar.JumpPointSearch(gridWorld, startState, goalState, &maxOctileDH, true, kgNOTHING); //canonicalAstar.JumpPointSearch(gridWorld, startState, goalState, &octileHeuristic, true, kgNOTHING); // a different part of the code crashes when i use this instead... timer.EndTimer(); effTime = timer.GetElapsedTime(); opPath = canonicalAstar.getDirections(); a = opPath.size(); optimalGcost = canonicalAstar.getGCost(goalState); printf("Jump Point Search::A star my openlist elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %d, Optimal Gcost: %f\n", timer.GetElapsedTime(), canonicalAstar.GetNodesExpanded(), a, optimalGcost); JumpPointNodesExpanded += canonicalAstar.GetNodesExpanded(); jumpPointTotalTime += effTime; totalProblems++; j++; //getchar(); } printf("Total Problems: %d\n", totalProblems); // also can get the avg time per puzzle. double avgOctileTime = efficientOctileTotalTime / (totalProblems*1.0); double avgDHTime = efficientDHTotalTime / (totalProblems*1.0); double avgDHOctileTime = DHOctileTotalTime / (totalProblems*1.0); double avgCanonicalTime = canoncicalDHOctileTotalTime / (totalProblems*1.0); double avgJumpTime = jumpPointTotalTime / (totalProblems*1.0); uint64_t avgOctileNodesExpanded = OctileNodesExpanded / totalProblems; uint64_t avgDHNodesExpanded = DHNodesExpanded / totalProblems; uint64_t avgDHOctileNodesExpanded = DHOctileNodesExpanded / totalProblems; uint64_t avgCanonicalNodesExpanded = CanonicalNodesExpanded / totalProblems; uint64_t avgJumpPointNodesExpanded = JumpPointNodesExpanded / totalProblems; printf("Octile avg time: %f, avg nodes: %llu\n", avgOctileTime, avgOctileNodesExpanded); printf("Differential avg time: %f, avg nodes: %llu\n", avgDHTime, avgDHNodesExpanded); printf("Differential & Octile avg time: %f, avg nodes: %llu\n", avgDHOctileTime, avgDHOctileNodesExpanded); printf("Canonical A Star average time: %f, avg nodes: %llu\n", avgCanonicalTime, avgCanonicalNodesExpanded); printf("Jump Point Search average time: %f, avg nodes: %llu\n", avgJumpTime, avgJumpPointNodesExpanded); printf("Done.\n"); } else { printf("ASDKFLAJSDLKFJASDLKFJADSF\n"); exit(5); } getchar(); } void testMapStuff(bool optimalDH) { //std::string mapPath = "orz301d.map"; // "lak303d.map"; std::string mapPath = "lak303d.map"; GridWorld gridWorld(mapPath); Timer timer; //gridWorld.printWorld(); printf("=========\n"); // to pick start and goal, start with basic just top half and bottom half. //int startSRow = 98;//120;// 120;// 113;//121;//gridWorld.WORLDHEIGHT * 0.55; printf("WORLD HEIGHT: %d\n", gridWorld.WORLDHEIGHT); //printf("startSRow: %d\n", startSRow); //int startSCol = 31;// 1;// 10;// 0;// 0; // these are for lak int startSRow = 59;// 176;//59; int startSCol = 10;// 100;//10; while (!gridWorld.isValid({ startSCol, startSRow })) { startSCol = (startSCol + 1) % gridWorld.WORLDWIDTH; if (startSCol == gridWorld.WORLDWIDTH - 1) { startSRow += 1; if (startSRow >= gridWorld.WORLDHEIGHT - 1) { startSRow = 0; } } } //startSCol = 30; //startSRow = 98; GridWorldState startState(startSCol, startSRow); // 8,10 // 50, 124 printf("start state: "); startState.printState(); startSRow = 126;//116;// 126;// 100;//138; startSCol = 32;// 33;// 32;// 29;//59;// 0; // for lak startSRow = 40;// 83;// 154;//83; startSCol = 80;// 4;// 82;//4; while (!gridWorld.isValid({ startSCol, startSRow })) { startSCol = (startSCol + 1) % gridWorld.WORLDWIDTH; if (startSCol == gridWorld.WORLDWIDTH - 1) { startSRow += 1; if (startSRow >= gridWorld.WORLDHEIGHT - 1) { startSRow = gridWorld.WORLDHEIGHT/2; startSCol = gridWorld.WORLDWIDTH / 2; } } } GridWorldState goalState(startSCol, startSRow); printf("goal state: "); goalState.printState(); gridWorld.printWorldStateSpecific(startState, goalState); ManhattanDistance<GridWorldState> manDist; OctileHeuristic octileHeuristic; std::vector<GridWorldMovements> opPath; const int numHsss = 1; Heuristic<GridWorldState> *heuristiclistastar[numHsss];// = { &octileHeuristic };// { &manDist }; heuristiclistastar[0] = &octileHeuristic; MaxHeuristic<GridWorldState> maxheur; MaxHeuristic<GridWorldState> maxDiffHeur; //maxheur.addHeuristic(&octileHeuristic); GridWorldState sss(32, 126); //DifferentialHeuristic dh(gridWorld, sss); // but this doesn't cause a crash. -- would crash when would pass the gridworld by copy and not by reference. //gridWorld.setPivot(sss); //maxheur.addHeuristic(&dh); //DifferentialHeuristic dh(gridWorld, sss); // no idea why this makes it crash.. its like a left pointer or something //heuristiclistastar[1] = &dh; // so think this makes this crash... // but this way works yay. //std::vector<DifferentialHeuristic> dhs; // so these are empty for some reason... std::vector<DifferentialHeuristic> dhs = setUpOptimalDifferentialHeuristic(gridWorld); std::vector<DifferentialHeuristic> dhs1 = setupRandomDiffHeuristic(gridWorld); /*if (optimalDH) { dhs = setUpOptimalDifferentialHeuristic(gridWorld); } else { dhs = setupRandomDiffHeuristic(gridWorld); }*/ printf("Optimal Pivot Spots: \n"); for (int i = 0; i < dhs.size(); i++) { printf(" diff pivot: "); dhs[i].getPivot().printState(); maxheur.addHeuristic(&dhs[i]); } printf("Random Pivot Spots: \n"); MaxHeuristic<GridWorldState> maxRandomPivots; //maxRandomPivots.addHeuristic(&octileHeuristic); for (int i = 0; i < dhs1.size(); i++) { printf(" diff rrandom pivot: "); dhs1[i].getPivot().printState(); maxRandomPivots.addHeuristic(&dhs1[i]); } //std::vector<DifferentialHeuristic> difHs; //// looping aint working. //for (int i = 0; i < numHsss; i++) { // // need to figure outa random point. // // guess randomX and randomY and keep going until not -1 // printf("i: %d\n", i); // while (true) { // randx = rand() % (gridWorld.WORLDWIDTH - 1); // randy = rand() % (gridWorld.WORLDHEIGHT - 1); // printf("randx: %d, randy: %d\n", randx, randy); // if (gridWorld.isValid({ randx, randy })) { // GridWorldState ss(randx, randy); // // scoping issue. // DifferentialHeuristic ddh; // ddh.setUpHeuristic(gridWorld, ss); // gridWorld.setPivot(ss); // //ddh.setUpHeuristic(ss); // printf("all set\n"); // //heuristiclistastar[i] = &ddh; // difHs.push_back(ddh); // //maxheur.addHeuristic(&ddh); // break; // } // } // maxheur.addHeuristic(&difHs[i]); //} printf("finished picking pivots\n"); gridWorld.printWorldStateSpecific(startState, goalState); InefficientAStar<GridWorld, GridWorldState, GridWorldMovements> inAstar; AStar < GridWorld, GridWorldState, GridWorldMovements> astar; CanonicalAStar<GridWorld, GridWorldState, GridWorldMovements> canonicalAstar; //astar.setHeuristicWeight(0); gridWorld.setCanGoDiagonal(true); //astar.setStopAtGoal(false); int count = 0; //astar.setHeuristicWeight(1); //gridWorld.clearOpenClosed(); printf("A star my openlist.\n"); timer.StartTimer(); //astar.GetPath(gridWorld, startState, goalState, heuristiclistastar, numHsss, true, kgNOTHING); astar.GetPath3(gridWorld, startState, goalState, &maxheur, true, kgNOTHING); timer.EndTimer(); printf("A star my openlist elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %u\n", timer.GetElapsedTime(), astar.GetNodesExpanded(), astar.getDirections().size()); //gridWorld.printWorldStateSpecific(startState, goalState); // canonical A Star will still have roughly the same nodes expanded, but the same nodes wont be genereated as much. // so cause this removes duplicates, could you do a ida* or something in this domain now? gridWorld.clearOpenClosed(); printf("Canonical A Star\n"); timer.StartTimer(); canonicalAstar.GetPath3(gridWorld, startState, goalState, &maxheur, true, kgNOTHING); timer.EndTimer(); printf("Canonical A star elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %u\n", timer.GetElapsedTime(), canonicalAstar.GetNodesExpanded(), canonicalAstar.getDirections().size()); gridWorld.printWorldStateSpecific(startState, goalState); gridWorld.clearOpenClosed(); printf("Canonical A StarRandom Pivots\n"); timer.StartTimer(); canonicalAstar.GetPath3(gridWorld, startState, goalState, &maxRandomPivots, true, kgNOTHING); timer.EndTimer(); printf("Canonical A star RandomPivots elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %u\n", timer.GetElapsedTime(), canonicalAstar.GetNodesExpanded(), canonicalAstar.getDirections().size()); gridWorld.printWorldStateSpecific(startState, goalState); //canonicalAstar.setHeuristicWeight(0); //gridWorld.clearOpenClosed(); //printf("Jump Point Search A Star\n"); //timer.StartTimer(); //canonicalAstar.JumpPointSearch(gridWorld, startState, goalState, &maxheur, true, kgNOTHING); ////canonicalAstar.JumpPointSearch(gridWorld, startState, goalState, &octileHeuristic, true, kgNOTHING); //timer.EndTimer(); //printf("Jump Point Search elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %u\n", timer.GetElapsedTime(), canonicalAstar.GetNodesExpanded(), canonicalAstar.getDirections().size()); //gridWorld.printWorldStateSpecific(startState, goalState); //// ONLY THING with Jump point, is that the path only contains jump points... but I mean you simply follow the canonical ordering between jump points. // then for a dijkstras, hueristic weight is 0 and don't stop at the goal.. // will do regular first. //astar.setHeuristicWeight(0); //astar.setStopAtGoal(false); //printf("Dijkstra's.\n"); //timer.StartTimer(); //astar.GetPath3(gridWorld, startState, goalState, &maxheur, true, kgNOTHING); //timer.EndTimer(); //printf("Dijkstra's elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %u\n", timer.GetElapsedTime(), astar.GetNodesExpanded(), astar.getDirections().size()); //gridWorld.printWorldStateSpecific(startState, goalState); //canonicalAstar.setHeuristicWeight(0); //canonicalAstar.setStopAtGoal(false); //gridWorld.clearOpenClosed(); //printf("Canonical Dijkstra's\n"); //timer.StartTimer(); //canonicalAstar.GetPath3(gridWorld, startState, goalState, &maxheur, true, kgNOTHING); //timer.EndTimer(); //printf("Canonical Dijkstra's elapsed time: %f, Nodes Expanded: %llu, Optimal Moves: %u\n", timer.GetElapsedTime(), canonicalAstar.GetNodesExpanded(), canonicalAstar.getDirections().size()); //gridWorld.printWorldStateSpecific(startState, goalState); // not sure how to get the gcosts, or how to demonstrate that... // so just going to use the path cause those are states that i have. printf("Gcost along path: "); printf("%f ,", astar.getGCost(startState)); printf("\n"); for (auto o : astar.getDirections()) { std::cout << "dir: " << o; // apply the operator and print out the gcost. gridWorld.ApplyOperator(startState, o); printf(" %f ,", astar.getGCost(startState)); //gridWorld.printOperator(o); startState.printState(); } printf("\n"); // also could just print gcost of every state in the grid, cause why not //printf("ALL G Costs\n"); //for (int i = 0; i < gridWorld.WORLDHEIGHT; i++) { // for (int j = 0; j < gridWorld.WORLDWIDTH; j++) { // //printf("astats\n"); // GridWorldState s(j, i); // printf("%.1f|", astar.getGCost(s)); // } // printf("\n"); //} //printf("\n"); getchar(); } /* Think ill need to put all the old searches into their own files because of the operator of NOTHING */ int main(int argc, char** argv) { bool WANT_PRINT_BOARDS = false; STP game; Timer timer; STPState goalState; ManhattanDistance<STPState> manDist; /* WORKS IN RELASEASE MODE BUT NOT IN DEBug MODE>>>>....... WHYYYYY */ DFID dfid; BFS nbfs; IDAStar idaStar(manhattanDistance); IDAStar idaStarPDB(manhattanDistance); //InefficientAStar<STP, STPState, STPSlideDir> inaStar; int count = 0; STPState astartstate = RandomWalk2(game, goalState, 100); srand(time(NULL)); testMapStuff(true); //testMapStuff(false); //freopen("README.txt", "w", stdout); std::string mapPath = "lak303d.map";// "orz301d.map"; //testMapBenchmarks(mapPath, mapPath + ".scen"); // needed on windows for visual studios to get the terminal to stay up. printf("End\n"); getchar(); } void STPTimeTests() { bool WANT_PRINT_BOARDS = false; STP game; Timer timer; STPState goalState; ManhattanDistance<STPState> manDist; int count = 0; DFID dfid; BFS nbfs; IDAStar idaStar(manhattanDistance); IDAStar idaStarPDB(manhattanDistance); InefficientAStar<STP, STPState, STPSlideDir> inaStar; const int numHsss = 1; // check how to get heuristic to work for any enviroment, or if i need to make a new heuristic per enviroment.... // or in each heuristic, just override for each type. Heuristic<STPState> *heuristiclistastar[numHsss] = { &manDist }; // so does that mean i need to put the arrays on the heap? -- it works then. do i have to delete that pointer? // The patterns. std::vector<int> patt2 = { 0,9,10,11,12,13,14 }; std::vector<int> patt = { 0, 1, 2, 3, 4, 5 }; // {0}; printf("starting patterndatabase...\n"); // Make the PDB's timer.StartTimer(); PDB pdb(patt, false); timer.EndTimer(); printf("Pattern 1 database took: %f\n", timer.GetElapsedTime()); //getchar(); timer.StartTimer(); PDB pdb2(patt2, false); timer.EndTimer(); printf("Pattern 2 database took: %f\n", timer.GetElapsedTime()); //getchar(); // add the heuristics to the list of ones to use. /*std::vector<Heuristic*> huers; huers.push_back(&pdb); huers.push_back(&pdb2); huers.push_back(&manDist);*/ const int numHs = 3; Heuristic<STPState> *huers[numHs] = { &pdb, &pdb2, &manDist }; // took out pdb2 // creating an array of bool that can be used to toggle each different search version. // DFID Path, IDA*Sort, IDA*, A*, BFSv4, NDFID, DFIDNoPath, NBFS, IDAPDB bool whichPrinting[9] = { false, false, true, false, false, false, false, false, true }; // { true, true, false, true, false, true }; // { true, false, false, false, false, true }; // could make a table, like cols = (shufflenum, IDA*1 time, // so like push times onto a vector, then just print that out // at top go over which printing, and if it is true, print corresponding name. // this way, could output the table to like a csv then could graph and stuff. std::vector<float> algTimes; std::vector<uint64_t> algNodes; bool wantPrintTable = false; char separator = '|'; if (wantPrintTable) { printf("NumShuff %c", separator); if (whichPrinting[1]) { printf(" IDASort %c", separator); } if (whichPrinting[2]) { printf(" IDA*(MD) %c", separator); } if (whichPrinting[3]) { printf(" A* %c", separator); } if (whichPrinting[4]) { printf(" BFS %c", separator); } if (whichPrinting[5]) { printf(" NDFID %c", separator); } if (whichPrinting[6]) { printf(" DFID"); } if (whichPrinting[8]) { printf(" IDA (MD+PDB) %c", separator); } printf("\n"); } int maxShuffle = 200; for (int i = 5; i < maxShuffle; i++) { if (!wantPrintTable) { printf("------------------Current num shuffle: %d---------------\n", i); } STPState startstate = RandomWalk2(game, goalState, i); //STPState startstate = RandomWalkMoreDifficult(game, goalState, i); if (!wantPrintTable) { startstate.printState(); } algTimes.clear(); algNodes.clear(); int counter = 0; if (whichPrinting[0]) { // DFID counter = 0; timer.StartTimer(); //startRecDFSPath(startstate, false, counter); timer.EndTimer(); printf("DFID no closed list time:\t\t\t %f, Expanded Nodes: %d\n", timer.GetElapsedTime(), counter); algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(counter); } if (whichPrinting[1]) { // DFID counter = 0; timer.StartTimer(); //idaStar.getPathSortChildren(game, startstate, goalState); dfid.GetPath(game, startstate, goalState); timer.EndTimer(); if (!wantPrintTable) { //printf("IDAStar(MD) Sort Children time:\t\t %f, Expanded Nodes: %d\n", timer.GetElapsedTime(), idaStar.getExpandedNodes()); printf("DFID in class time:\t\t %f, Expanded Nodes: %d\n", timer.GetElapsedTime(), dfid.GetNodesExpanded()); } algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(dfid.GetNodesExpanded()); } if (whichPrinting[2]) { // IDA* (MD) counter = 0; timer.StartTimer(); idaStar.getPath(game, startstate, goalState); timer.EndTimer(); if (!wantPrintTable) { printf("IDAStar(MD) Recursive class time:\t %f, Expanded Nodes: %d\n", timer.GetElapsedTime(), idaStar.getExpandedNodes()); // print the path std::vector<STPSlideDir> path = idaStar.getDirections(); //printPath(path); } algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(idaStar.getExpandedNodes()); } if (whichPrinting[3]) { // AStar counter = 0; timer.StartTimer(); //basicAStar(game, startstate, goalState, manhattanDistance, counter, false); timer.EndTimer(); if (!wantPrintTable) { printf("AStar time:\t\t\t %f, Expanded Nodes: %d\n", timer.GetElapsedTime(), counter); } algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(counter); } if (whichPrinting[4]) { // BFS counter = 0; timer.StartTimer(); //BFSv4(game, startstate, counter); timer.EndTimer(); printf("BFSv4 operators, no closed list: time:\t\t %f, Expanded Nodes: %d\n", timer.GetElapsedTime(), counter); algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(counter); } if (whichPrinting[5]) { // NDFID timer.StartTimer(); dfid.GetPath(game, startstate, goalState); timer.EndTimer(); if (!wantPrintTable) { printf("Nathans DFID, time: \t\t\t %f, expanded Nodes: %d\n", timer.GetElapsedTime(), dfid.GetNodesExpanded()); } algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(dfid.GetNodesExpanded()); } if (whichPrinting[6]) { // DFID no path timer.StartTimer(); //startRecDFS(game, startstate, goalState, counter); timer.EndTimer(); if (!wantPrintTable) { printf("DFID No path, time: \t\t\t %f, expandedNodes: %d\n", timer.GetElapsedTime(), counter); } algTimes.push_back(timer.GetElapsedTime()); } if (whichPrinting[7]) { // NBFS timer.StartTimer(); nbfs.GetPath(game, startstate, goalState); timer.EndTimer(); if (!wantPrintTable) { printf("NBFS, time: \t\t\t %f, expandedNodes: %d\n", timer.GetElapsedTime(), nbfs.GetNodesExpanded()); } algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(nbfs.GetNodesExpanded()); } if (whichPrinting[8]) { // IDA PDB timer.StartTimer(); idaStarPDB.getPathHeurClass(game, startstate, goalState, huers, numHs); /// THIS STILL NEEDS WORK.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!KGGADKSJFKLG;FJSDAGKFWHGDFBFDJKTYFNARNGFABDNFL/K //idaStarPDB.getPathHeurClass(game, startstate, goalState, huers); timer.EndTimer(); if (!wantPrintTable) { printf("IDA (PDB+MD), time: \t\t\t %f, expandedNodes: %d\n", timer.GetElapsedTime(), idaStarPDB.getExpandedNodes()); } algTimes.push_back(timer.GetElapsedTime()); algNodes.push_back(idaStarPDB.getExpandedNodes()); } // then can print out the table. if (wantPrintTable) { /*printf("%d\t %c ", i, separator); for (int j = 0; j < algTimes.size(); j++) { printf("%f %c ", algTimes[j], separator); }*/ // if printing expanded nodes or times. printf("%d\t %c ", i, separator); for (int j = 0; j < algNodes.size(); j++) { printf("%llu %20c ", algNodes[j], separator); } } printf("\n"); //getchar(); } // needed on windows for visual studios to get the terminal to stay up. getchar(); } void applyAndPrintOperators(STPState originalState, STP game, std::vector<STPSlideDir>& parentPath) { originalState.printState(); // then I could solve it by applying each operator. // think need to go in reverse. for (int i = parentPath.size() - 1; i >= 0; i--) { game.ApplyOperator(originalState, parentPath[i]); originalState.printState(); } } void printPath(std::vector<STPSlideDir>& path) { // Need to go in reverse order. // I know that so it works. I could just reverse the vector but why waste time. for (int i = path.size() - 1; i >= 0; i--) { if (path[i] == UP) { printf("Up, "); } else if (path[i] == DOWN) { printf("Down, "); } else if (path[i] == LEFT) { printf("Left, "); } else if (path[i] == RIGHT) { printf("Right, "); } else { printf("Nothing, "); } } printf("\n"); } STPState RandomWalk2(STP game, STPState state, uint64_t n) { state = STPState(); std::vector<STPSlideDir> directions; uint64_t i = 0; while (n > i++) { // get the operators game.GetOperators(state, directions); // get a random direction. int r = rand() % directions.size(); game.ApplyOperator(state, directions[r]); } return state; } STPState RandomWalkMoreDifficult(STP game, STPState state, uint64_t n) { state = STPState(); std::vector<STPSlideDir> directions; uint64_t i = 0; STPSlideDir previousDir = UP;// NOTHING; while (n > i++) { // get the operators game.GetOperators(state, directions); // get a random direction. int r = rand() % directions.size(); while (game.getOppositeDir(directions[r]) == previousDir) { r = rand() % directions.size(); } game.ApplyOperator(state, directions[r]); previousDir = directions[r]; } return state; } void userPlay() { STP slideGame; // test user input. char input; std::cin >> input; printf("input: %c\n", input); STPState gameState; while (input != 'q') { gameState.printState(); std::cin >> input; if (input == 'w') { slideGame.ApplyOperator(gameState, UP); } else if (input == 's') { slideGame.ApplyOperator(gameState, DOWN); } else if (input == 'a') { slideGame.ApplyOperator(gameState, LEFT); } else if (input == 'd') { slideGame.ApplyOperator(gameState, RIGHT); } else { printf("ERROR\n"); break; } } }
Java
UTF-8
1,313
2.6875
3
[ "Apache-2.0" ]
permissive
package Model; import java.util.List; import java.util.Objects; public class TweetSentiment { private double mFinalPositiveness = 0; public void setTweetPositiveness() { final List<Tweet> tweetList = TweetList.getInstance().getTweetList(); for (final Tweet aTweetList : tweetList) { final String tweetText = aTweetList.getTweetText(); final String[] parts = tweetText.split("[^a-zA-z']+"); double positiveness = 0; int countEntities = 0; for (final String part : parts) { for (int j = 0; j < SentimentsList.getInstance().getSentimentList().size(); j++) { final String buf = SentimentsList.getInstance().getSentimentList().get(j).getWord(); if (Objects.equals(part, buf)) { positiveness += SentimentsList.getInstance().getSentimentList().get(j).getPositiveness(); countEntities++; } } if (countEntities != 0) { mFinalPositiveness = positiveness / countEntities; } else { mFinalPositiveness = 0; } } aTweetList.setPositiveness(mFinalPositiveness); } } }
C#
UTF-8
639
2.84375
3
[]
no_license
Regex spaceRegex = new Regex("\\s{2,}"); //Only replace subsequent spaces, not all spaces. For example, //" " (three spaces) becomes " &nbsp;&nbsp;" (1 space, 2 non-breaking spaces). MatchEvaluator matchEvaluator = delegate(Match match) { StringBuilder spaceStringBuilder = new StringBuilder(" "); for (int i = 0; i < match.Value.Length - 1; i++) { spaceStringBuilder.Append("&nbsp;"); } return spaceStringBuilder.ToString(); }; return spaceRegex.Replace(server.HtmlEncode(value), matchEvaluator); }
Markdown
UTF-8
2,881
2.953125
3
[]
no_license
# API Reference ### coolsms.c 먼저 User\_opt struct 을 생성합니다. 생성한 구조체를 initialize 하는 user\_opt\_init\(\) 함수를 불러줍니다. ```text #include "coolsms.h" int main() { char * api_key = "키 입력"; char * api_secret = "비밀키 입력"; user_opt user_info = user_opt_init(api_key, api_secret); ``` ### \_send ```text response_struct _send (const user_opt *user_info, const send_opt *send_info) ``` send 메서드는 문자메시지를 보내는 함수로서 user\_opt 포인터와 send\_opt 포인터를 parameter 로 받고 response\_struct 의 값을 리턴합니다. **send\_opt send\_info 설정하기** send option 을 설정할때는 coolsms\_formset 함수가 사용됩니다. ```text send_opt send_info = send_opt_init(); coolsms_formset(&send_info, COOLSMS_TO, "01000000000"); coolsms_formset(&send_info, COOLSMS_FROM, "01000000000"); coolsms_formset(&send_info, COOLSMS_TEXT, "msg from c"); result = _send(&user_info, &send_info); coolsms_formfree(&send_info); ``` options : * COOLSMS\_TO 받는사람 * COOLSMS\_FROM 보내는 사람 * COOLSMS\_TEXT 문자 메시지 * COOLSMS\_TYPE 문자 타입 \(SMS, LMS, MMS\) * COOLSMS\_IMAGE 사진 \(\* 사진 추가시 타입은 MMS 로만 해야함\) * COOLSMS\_REFNAME 문자를 기억하기 쉽게 표시하는 이름\( ex. 광고문자\) * COOLSMS\_DATETIME 예약발송 설정시 입력 \(format : YYYYMMDDHHMISS\) * COOLSMS\_SUBJECT 문자제목\(LMS 와 MMS 만 해당\) * COOLSMS\_SRK SRK 키 설정\([수익 배분프로그램 참고\)](http://www.coolsms.co.kr/sp) * COOLSMS\_EXTENSION 확장 문자\([사용법](http://doc.coolsms.co.kr/?page_id=1104)\) 문자를 보낸후에는 coolsms\_formfree\(\) 함수를 호출하여 send\_opt 에 할당된 메모리를 해제 시켜줍니다. ```text void coolsms_formfree(send_opt *send_info) ``` ### \_sent ```text response_struct _sent(const user_opt *user_info, const sent_opt *send_info) ``` 발송 되었던 문자에 대한 정보를 가져옵니다. sent\_opt sent\_info 를 설정합니다. ```text typedef struct { char * count, *page, *s_rcpt, *s_start, *s_end, *mid, *gid; }send_opt; ``` #### ### \_balance ```text response_struct _balance(const user_opt *user_info) ``` 자신의 계정의 남은 잔액과 포인트를 가져옵니다. 설정된 user\_opt 포인터를 parameter 로 넣으면 서버에서 잔액정보를 가지고옵니다. ### \_cancel ```text response_struct _cancel(const user_opt *user_info, const cancel_opt *cancel_info) ``` 예약문자를 취소한다. ```text typedef struct { char * mid, *gid; }cancel_opt; ```
Swift
UTF-8
808
2.53125
3
[]
no_license
// // FilterMediaStatusPicker.swift // Movie DB // // Created by Jonas Frey on 14.03.23. // Copyright © 2023 Jonas Frey. All rights reserved. // import SwiftUI struct FilterMediaStatusPicker: View { @EnvironmentObject private var filterSetting: FilterSetting var body: some View { FilterMultiPicker( selection: $filterSetting.statuses, label: { Text($0.rawValue) }, values: MediaStatus.allCases.sorted(on: \.rawValue, by: <), title: Text(Strings.Library.Filter.mediaStatusLabel) ) } } struct FilterMediaStatusPicker_Previews: PreviewProvider { static var previews: some View { FilterMediaStatusPicker() .environmentObject(FilterSetting(context: PersistenceController.createDisposableContext())) } }
Java
UTF-8
242
1.929688
2
[]
no_license
package net.tinybrick.security.authentication; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public interface IAuthenticationToken<T> { @XmlElement public T getUsername(); }
SQL
UTF-8
1,618
3.53125
4
[]
no_license
SELECT R.ORDER_FISCAL_YR , R.ORDER_ID , R.ORDER_LINE_NBR , R.SCHED_LINE_NBR , R.PRIOR_DY_RESCHD_DT , R.RESCHD_DT , R.RESCHD_TM , R.ORDER_TYPE_ID , R.AVAIL_CHK_GRP_CD , R.DOC_TYP_CD , R.TRANS_UPD_CD , R.SRC_UPD_USR_ID , R.SHIP_TO_CUST_ID , C.CUST_NAME , C.OWN_CUST_ID , C.OWN_CUST_NAME , R.MATL_ID , M.DESCR , M.PBU_NBR , M.PBU_NAME , M.MKT_AREA_NBR , M.MKT_AREA_NAME , M.MKT_GRP_NBR , M.MKT_GRP_NAME , M.PROD_LINE_NBR , M.PROD_LINE_NAME , R.RESCHD_IND , R.DELIV_DT_CHG_CD , R.PLN_DELIV_DT , R.RESCHD_DELIV_DT , R.DELIV_DT_VAR_QTY , R.CNFRM_QTY_CHG_CD , R.CNFRM_QTY , R.RESCHD_CNFRM_QTY , R.CNFRM_VAR_QTY , R.PLN_MATL_AVAIL_DT , R.RESCHD_MATL_AVAIL_DT , R.MATL_AVAIL_DT_VAR_QTY FROM NA_BI_vWS.ORD_RESCHD R INNER JOIN NA_BI_vWS.ORDER_DETAIL OD ON OD.ORDER_FISCAL_YR = R.ORDER_FISCAL_YR AND OD.ORDER_ID = R.ORDER_ID AND OD.ORDER_LINE_NBR = R.ORDER_LINE_NBR AND OD.SCHED_LINE_NBR = 1 AND OD.EXP_DT = CAST('5555-12-31' AS DATE) INNER JOIN GDYR_BI_vWS.NAT_CUST_HIER_DESCR_EN_cURR C ON C.SHIP_TO_CUST_ID = R.SHIP_TO_CUST_ID INNER JOIN GDYR_BI_VWS.NAT_MATL_HIER_DESCR_EN_CURR M ON M.MATL_ID = R.MATL_ID WHERE R.PRIOR_DY_RESCHD_DT BETWEEN DATE '2015-07-01' AND CURRENT_DATE-1 AND R.MATL_ID IN ('000000000000204189', '000000000000218254', '000000000000061902') ORDER BY R.ORDER_FISCAL_YR , R.ORDER_ID , R.ORDER_LINE_NBR , R.SCHED_LINE_NBR , R.PRIOR_DY_RESCHD_DT
Markdown
UTF-8
1,509
2.625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
# Contributing ## Developing in the Open Developing in the open creates a healthier working environment, a more collaborative process, and just better software. We welcome contributions. The aws-cft-tools team handles development of this project in the open. As such, we use Github to keep track of project development. We may not accept contributions if they introduce operational complexity or don't align with the goals of the project. All contributions are subject to the license and in no way imply compensation for contributions. ## Feedback To provide feedback on the code, please create an issue on GitHub. For other issues, please contact the [Certify Help Desk](mailto:help@certify.sba.gov). ## How to Contribute To contribute, simple create a pull request: 1. Fork this repository 2. Create a feature branch on which to work (`git checkout -b my-new-feature`) 3. Commit your work (we like commits that explain your thought process) 4. Submit a pull request 5. If there is an issue associated with your pull request, then link that issue. For documentation changes, you can edit the file directly on GitHub and select the option to create a pull request with your own branch. ## Tests and Continuous Integration All pull requests must pass our continuous integration (CI) tests in order to be accepted. We use [rubocop](https://github.com/bbatsov/rubocop) with a style guide to enforce style on Ruby projects as part of the CI tests. The agency reserves the right to change this policy at any time.
Rust
UTF-8
316
2.59375
3
[]
no_license
use serde::Serializer; pub(crate) fn serialize_as_csv<S, T>( iter: impl IntoIterator<Item = T>, serializer: S, ) -> Result<S::Ok, S::Error> where T: Into<&'static str>, S: Serializer, { let out: Vec<_> = iter.into_iter().map(Into::into).collect(); serializer.serialize_str(&out.join(",")) }
Java
UTF-8
60,442
2.203125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Ventanas; import Clases.Arbol; import Clases.Graph; import Clases.ColorGUI; import Clases.Controlador; import Clases.DijkstraAlgorithm; import Clases.PrimAlgorithm; import Clases.lienzoarbol; import Clases.RESOURCE_LIST; import Clases.TASK; import Clases.TASKNODE; import Clases.TASKSLIST; import java.awt.Color; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author fredy_000 */ public class MainWindow extends javax.swing.JFrame { TASKSLIST taskList = new TASKSLIST(); RESOURCE_LIST resourceList = new RESOURCE_LIST(); TASKSLIST subTasks = new TASKSLIST(); TASKSLIST aux = new TASKSLIST(); /** * Creates new form VentanaPincipal */ ColorGUI pintar =new ColorGUI(); Graph arboles = new Graph(); public static void R_repaint(int tope, Graph arboles){//pinta lo q esta antes en el panel for (int j = 0; j < tope; j++) { for (int k = 0; k < tope; k++) { if(arboles.getmAdyacencia(j, k) == 1) ColorGUI.pintarLinea(jPanel1.getGraphics(),arboles.getCordeX(j),arboles.getCordeY(j), arboles.getCordeX(k), arboles.getCordeY(k),arboles.getmCoeficiente(j, k)); } } for (int j = 0; j < tope; j++) ColorGUI.pintarCirculo(jPanel1.getGraphics(), arboles.getCordeX(j),arboles.getCordeY(j),String.valueOf(arboles.getNombre(j))); } public static int ingresarNodoOrigen(String nodoOrige, String noExiste,int tope){ int nodoOrigen = 0; try{ nodoOrigen = Integer.parseInt(JOptionPane.showInputDialog(""+nodoOrige)); if(nodoOrigen>=tope){ JOptionPane.showMessageDialog(null,""+noExiste+"\nDebe de ingresar un Nodo existente"); nodoOrigen = ingresarNodoOrigen(nodoOrige,noExiste, tope); } }catch(Exception ex){ nodoOrigen = ingresarNodoOrigen(nodoOrige,noExiste,tope); } return nodoOrigen; } public int ingresarTamano(String tama){ int tamano = 0; try{ tamano = Integer.parseInt(JOptionPane.showInputDialog(""+tama)); if(tamano<1){ JOptionPane.showMessageDialog(null,"Debe Ingresar un Tamaño Aceptado.."); tamano = ingresarTamano(tama);//no es nesario hacer esto } }catch(Exception ex){ tamano = ingresarTamano(tama); } return tamano; } public boolean cicDerechoSobreNodo(int xxx,int yyy){ for (int j = 0; j < tope; j++) {// consultamos si se ha sado click sobre algun nodo if((xxx+2) > arboles.getCordeX(j) && xxx < (arboles.getCordeX(j)+13) && (yyy+2) > arboles.getCordeY(j) && yyy<(arboles.getCordeY(j)+13) ) { if(n==0){ id = j; R_repaint(tope,arboles); ColorGUI.clickSobreNodo(jPanel1.getGraphics(), arboles.getCordeX(j), arboles.getCordeY(j), null,Color.orange); n++; } else{ id2=j; n++; ColorGUI.clickSobreNodo(jPanel1.getGraphics(), arboles.getCordeX(j), arboles.getCordeY(j), null,Color.orange); if(id==id2){// si id == id2 por q se volvio a dar click sobre el mismos nodo, se cancela el click anterio n=0; ColorGUI.pintarCirculo(jPanel1.getGraphics(),arboles.getCordeX(id), arboles.getCordeY(id),String.valueOf(arboles.getNombre(id))); id=-1; id2=-1; } } nn=0; return true; } } return false; } public void clicIzqSobreNodo(int xxx, int yyy){ // ACA se puede poner una funcion para visualizar las tareas asociadas a un nodo (tarea madre) for (int j = 0; j <tope; j++) { if((xxx+2) > arboles.getCordeX(j) && xxx < (arboles.getCordeX(j)+13) && (yyy+2) > arboles.getCordeY(j) && yyy<(arboles.getCordeY(j)+13) ) { if(nn==0){ permanente =j; R_repaint(tope, arboles); } else{ nodoFin = j;} nn++; n=0; id =-1; // JUSTAMENTE ACA HACER ALGUN SHOW DE UNA LISTA CON LAS TAREAS O ALGO SIMILAR ColorGUI.clickSobreNodo(jPanel1.getGraphics(), arboles.getCordeX(j), arboles.getCordeY(j), null,Color.GREEN); break; } } } public void adactarImagen(File file){ try{ BufferedImage read = ImageIO.read(file); Image scaledInstance = read.getScaledInstance(jmapa.getWidth(),jmapa.getHeight(), Image.SCALE_DEFAULT); jmapa.setIcon(new ImageIcon(scaledInstance)); }catch(Exception ex){ JOptionPane.showMessageDialog(null,"Error al cargar la imagen"); } } public MainWindow() { initComponents(); // jPanel2.setVisible(false); jDialog1.setLocationRelativeTo(null); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jDialog1 = new javax.swing.JDialog(); jFileChooser2 = new javax.swing.JFileChooser(); jPanel2 = new javax.swing.JPanel(); jFrame1 = new javax.swing.JFrame(); jPanel3 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jTextField8 = new javax.swing.JTextField(); jComboBox2 = new javax.swing.JComboBox<>(); jLabel14 = new javax.swing.JLabel(); jComboBox3 = new javax.swing.JComboBox<>(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jFrame2 = new javax.swing.JFrame(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jTextField9 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jTextField11 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jTextField13 = new javax.swing.JTextField(); jTextField14 = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); jLabel22 = new javax.swing.JLabel(); jComboBox4 = new javax.swing.JComboBox<>(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jFrame3 = new javax.swing.JFrame(); jLabel23 = new javax.swing.JLabel(); jComboBox5 = new javax.swing.JComboBox<>(); jButton9 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jPanel1 = new javax.swing.JPanel(); jmapa = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox<>(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); jMenuItem13 = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); jMenuItem2 = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JPopupMenu.Separator(); jMenuItem5 = new javax.swing.JMenuItem(); jMenuItem7 = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); jMenuItem1 = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JPopupMenu.Separator(); jMenuItem8 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem10 = new javax.swing.JMenuItem(); jMenuItem9 = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); jMenuItem12 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jDialog1.setMinimumSize(new java.awt.Dimension(700, 450)); jDialog1.setResizable(false); jDialog1.getContentPane().setLayout(null); jFileChooser2.setMaximumSize(new java.awt.Dimension(21475, 21474)); jFileChooser2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jFileChooser2ActionPerformed(evt); } }); jDialog1.getContentPane().add(jFileChooser2); jFileChooser2.setBounds(10, 20, 670, 390); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 309, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); jLabel3.setFont(new java.awt.Font("Dialog", 0, 20)); // NOI18N jLabel3.setText("SUB TASKS"); jLabel9.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel9.setText("ID"); jLabel10.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel10.setText("Description"); jLabel11.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel11.setText("Effort"); jLabel12.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel12.setText("Manager"); jLabel13.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel13.setText("Type"); jTextField5.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField6.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField7.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField8.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jComboBox2.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Operational Task", "Approval Task", "Signing of Contracts", "Management Task", "Changes" })); jLabel14.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel14.setText("Main task"); jComboBox3.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton4.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton4.setText("SET"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton5.setText("DONE"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton6.setText("CLOSE"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jFrame1Layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextField5, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField6, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField7, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField8, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboBox2, javax.swing.GroupLayout.Alignment.LEADING, 0, 258, Short.MAX_VALUE) .addComponent(jComboBox3, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jFrame1Layout.createSequentialGroup() .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton6))) .addContainerGap(262, Short.MAX_VALUE)) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3) .addGap(52, 52, 52) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton4) .addComponent(jButton5) .addComponent(jButton6)) .addContainerGap(49, Short.MAX_VALUE)) ); jLabel15.setFont(new java.awt.Font("Dialog", 0, 20)); // NOI18N jLabel15.setText("RESOURCES"); jLabel16.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel16.setText("ID"); jLabel17.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel17.setText("Name"); jLabel18.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel18.setText("Type"); jLabel19.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel19.setText("Resource capacity"); jLabel20.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel20.setText("Manager"); jLabel21.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel21.setText("Stock"); jTextField9.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField10.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField11.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField12.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField13.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jTextField14.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel22.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel22.setText("Resources list"); jComboBox4.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboBox4, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel22, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(131, 131, 131)))) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel22) .addGap(18, 18, 18) .addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(205, Short.MAX_VALUE)) ); jButton7.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton7.setText("SET"); jButton8.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton8.setText("CLOSE"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane()); jFrame2.getContentPane().setLayout(jFrame2Layout); jFrame2Layout.setHorizontalGroup( jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame2Layout.createSequentialGroup() .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jFrame2Layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel15) .addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField14, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField13, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(43, 43, 43) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jFrame2Layout.createSequentialGroup() .addGap(261, 261, 261) .addComponent(jButton7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton8))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jFrame2Layout.setVerticalGroup( jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame2Layout.createSequentialGroup() .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jFrame2Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jFrame2Layout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(jLabel15) .addGap(45, 45, 45) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel17) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel18) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel19) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20) .addComponent(jTextField13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(jTextField14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(18, 18, 18) .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton7) .addComponent(jButton8)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel23.setFont(new java.awt.Font("Dialog", 0, 20)); // NOI18N jLabel23.setText("WBS"); jComboBox5.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton9.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton9.setText("SHOW"); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); javax.swing.GroupLayout jFrame3Layout = new javax.swing.GroupLayout(jFrame3.getContentPane()); jFrame3.getContentPane().setLayout(jFrame3Layout); jFrame3Layout.setHorizontalGroup( jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame3Layout.createSequentialGroup() .addGap(52, 52, 52) .addGroup(jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton9) .addGroup(jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel23) .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(123, Short.MAX_VALUE)) ); jFrame3Layout.setVerticalGroup( jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame3Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jLabel23) .addGap(37, 37, 37) .addComponent(jComboBox5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton9) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(74, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle(":::::::::Grafos::::::::::"); setResizable(false); getContentPane().setLayout(null); jPanel1.setBackground(new java.awt.Color(141, 141, 141)); jPanel1.setBorder(javax.swing.BorderFactory.createMatteBorder(5, 5, 5, 5, new java.awt.Color(0, 102, 102))); jPanel1.setMinimumSize(new java.awt.Dimension(770, 522)); jPanel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jPanel1MouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jPanel1MousePressed(evt); } }); jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { jPanel1MouseMoved(evt); } }); jPanel1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jPanel1KeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { jPanel1KeyReleased(evt); } }); jPanel1.setLayout(null); jPanel1.add(jmapa); jmapa.setBounds(10, 10, 580, 500); getContentPane().add(jPanel1); jPanel1.setBounds(380, 10, 600, 520); jLabel1.setFont(new java.awt.Font("AngsanaUPC", 2, 18)); // NOI18N getContentPane().add(jLabel1); jLabel1.setBounds(220, 530, 400, 20); jLabel2.setFont(new java.awt.Font("Dialog", 0, 20)); // NOI18N jLabel2.setText("CREATE MAIN TASK"); getContentPane().add(jLabel2); jLabel2.setBounds(10, 30, 200, 26); jLabel4.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel4.setText("ID"); getContentPane().add(jLabel4); jLabel4.setBounds(10, 100, 90, 24); jLabel5.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel5.setText("Description"); getContentPane().add(jLabel5); jLabel5.setBounds(10, 150, 110, 24); jLabel6.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel6.setText("Effort"); getContentPane().add(jLabel6); jLabel6.setBounds(10, 200, 100, 24); jLabel7.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel7.setText("Manager"); getContentPane().add(jLabel7); jLabel7.setBounds(10, 250, 100, 24); jLabel8.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel8.setText("Type"); getContentPane().add(jLabel8); jLabel8.setBounds(10, 300, 90, 24); jTextField1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N getContentPane().add(jTextField1); jTextField1.setBounds(120, 249, 230, 30); jTextField2.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N getContentPane().add(jTextField2); jTextField2.setBounds(120, 99, 230, 30); jTextField3.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N getContentPane().add(jTextField3); jTextField3.setBounds(120, 149, 230, 30); jTextField4.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N getContentPane().add(jTextField4); jTextField4.setBounds(120, 199, 230, 30); jComboBox1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Operational Task", "Approval Task", "Signing of Contract", "Management Task", "Changes" })); getContentPane().add(jComboBox1); jComboBox1.setBounds(120, 300, 230, 30); jButton1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton1.setText("SUB TASKS"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(30, 430, 150, 30); jButton2.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton2.setText("SET"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(30, 380, 150, 30); jButton3.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jButton3.setText("VIEW TASKS"); getContentPane().add(jButton3); jButton3.setBounds(190, 380, 150, 30); jMenu1.setText("Functions"); jMenu1.add(jSeparator1); jMenuItem13.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem13.setText("Shortest path"); jMenuItem13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem13ActionPerformed(evt); } }); jMenu1.add(jMenuItem13); jMenu1.add(jSeparator3); jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem2.setText("New edge"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenu1.add(jSeparator2); jMenuItem5.setText("Matrix of coefficients"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); jMenu1.add(jMenuItem5); jMenuItem7.setText("Adjacency matrix"); jMenuItem7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem7ActionPerformed(evt); } }); jMenu1.add(jMenuItem7); jMenu1.add(jSeparator4); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.ALT_MASK)); jMenuItem1.setText("New project"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenu1.add(jSeparator5); jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem8.setText("Exit"); jMenuItem8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem8ActionPerformed(evt); } }); jMenu1.add(jMenuItem8); jMenuBar1.add(jMenu1); jMenu2.setText("Remove"); jMenuItem10.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.ALT_MASK)); jMenuItem10.setText(" Delete node"); jMenuItem10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem10ActionPerformed(evt); } }); jMenu2.add(jMenuItem10); jMenuItem9.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem9.setText("Delete edge"); jMenuItem9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem9ActionPerformed(evt); } }); jMenu2.add(jMenuItem9); jMenuBar1.add(jMenu2); jMenu3.setText("Extra"); jMenu3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenu3ActionPerformed(evt); } }); jMenuItem12.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0)); jMenuItem12.setText("Resources"); jMenuItem12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem12ActionPerformed(evt); } }); jMenu3.add(jMenuItem12); jMenuItem3.setText("WBS"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu3.add(jMenuItem3); jMenuBar1.add(jMenu3); setJMenuBar(jMenuBar1); setSize(new java.awt.Dimension(1019, 619)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MousePressed System.out.println("Aqui"); int xxx, yyy; xxx=evt.getX(); yyy=evt.getY(); if(evt.isMetaDown()){ clicIzqSobreNodo(xxx, yyy ); if(nn==2){ nn=0; DijkstraAlgorithm Dijkstra = new DijkstraAlgorithm(arboles,tope,permanente, nodoFin); Dijkstra.dijkstra(); // jtacumulado.setText(""+Dijkstra.getAcumulado()); } } else{ if(!cicDerechoSobreNodo(xxx,yyy)){// si clik sobre nodo es falso entra if(tope<50){ arboles.setCordeX(tope,xxx); arboles.setCordeY(tope,yyy); arboles.setNombre(tope, tope); //arboles.setNombre(tope, 37); ColorGUI.pintarCirculo(jPanel1.getGraphics(),arboles.getCordeX(tope), arboles.getCordeY(tope),String.valueOf(arboles.getNombre(tope))); tope++; } else JOptionPane.showMessageDialog(null,"Se ha llegado al Maximo de nodos.."); } if(n==2 ){ n=0; int ta = ingresarTamano("Ingrese Tamaño"); if(aristaMayor < ta) aristaMayor=ta; arboles.setmAdyacencia(id2, id, 1); arboles.setmAdyacencia(id, id2, 1); arboles.setmCoeficiente(id2, id,ta ); arboles.setmCoeficiente(id, id2, ta); ColorGUI.pintarLinea(jPanel1.getGraphics(),arboles.getCordeX(id), arboles.getCordeY(id), arboles.getCordeX(id2), arboles.getCordeY(id2), ta); ColorGUI.pintarCirculo(jPanel1.getGraphics(),arboles.getCordeX(id), arboles.getCordeY(id),String.valueOf(arboles.getNombre(id))); ColorGUI.pintarCirculo(jPanel1.getGraphics(),arboles.getCordeX(id2), arboles.getCordeY(id2),String.valueOf(arboles.getNombre(id2))); id=-1; id2=-1; } } }//GEN-LAST:event_jPanel1MousePressed private void jPanel1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPanel1KeyPressed // TODO add your handling code here: }//GEN-LAST:event_jPanel1KeyPressed private void jPanel1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPanel1KeyReleased }//GEN-LAST:event_jPanel1KeyReleased private void jPanel1MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseMoved // TODO add your handling code here: }//GEN-LAST:event_jPanel1MouseMoved private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed if(tope>=2){ this.setEnabled(false); new DeleteEdge(pintar,arboles,tope,this).setVisible(true); jPanel1.paint(jPanel1.getGraphics()); R_repaint(tope,arboles); } else JOptionPane.showMessageDialog(null,"No Hay Nodos Enlazados... "); }//GEN-LAST:event_jMenuItem9ActionPerformed private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed int Eliminar= ingresarNodoOrigen("Ingrese Nodo a Eliminar ","Nodo No existe",tope); if(Eliminar<=tope && Eliminar>=0 && tope>0){ for (int j = 0; j < tope; j++) { for (int k = 0; k < tope; k++){ if(j==Eliminar ||k==Eliminar){ arboles.setmAdyacencia(j, k, -1); } } } for (int l = 0; l < tope-1; l++) { for (int m = 0; m < tope; m++) { if(arboles.getmAdyacencia(l, m)==-1){ arboles.setmAdyacencia(l, m,arboles.getmAdyacencia(l+1, m)); arboles.setmAdyacencia(l+1, m,-1); arboles.setmCoeficiente(l, m,arboles.getmCoeficiente(l+1, m)); } } } for (int l = 0; l < tope; l++) { for (int m = 0; m < tope-1; m++) { if(arboles.getmAdyacencia(l, m)==-1){ arboles.setmAdyacencia(l, m,arboles.getmAdyacencia(l, m+1)); arboles.setmAdyacencia(l, m+1,-1); arboles.setmCoeficiente(l, m,arboles.getmCoeficiente(l, m+1)); } } } arboles.setCordeX(Eliminar,-10); arboles.setCordeY(Eliminar,-10); arboles.setNombre(Eliminar, -10); for (int j = 0; j < tope; j++) { for (int k = 0; k < tope-1; k++) { if(arboles.getCordeX(k)==-10){ arboles.setCordeX(k, arboles.getCordeX(k+1)); arboles.setCordeX(k+1, -10); arboles.setCordeY(k, arboles.getCordeY(k+1)); arboles.setCordeY(k+1, -10); arboles.setNombre(k, arboles.getNombre(k+1)); arboles.setNombre(k+1,-10); } } } for (int j = 0; j < tope; j++) arboles.setNombre(j,j);// renombramos // eliminamos los -1 y los -10 for (int j = 0; j < tope+1; j++) { for (int k = 0; k < tope+1; k++) { if( arboles.getmAdyacencia(j, k)!=-1) arboles.setmAdyacencia(j, k, arboles.getmAdyacencia(j, k)); else arboles.setmAdyacencia(j, k, 0); if(arboles.getmCoeficiente(j, k) !=-10) arboles.setmCoeficiente(j, k, arboles.getmCoeficiente(j, k)); else arboles.setmCoeficiente(j, k, 0); } } tope--; jPanel1.paint(jPanel1.getGraphics()); R_repaint(tope,arboles); } }//GEN-LAST:event_jMenuItem10ActionPerformed private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed // jPanel2.setVisible(true);// TODO add your handling code here: }//GEN-LAST:event_jMenuItem12ActionPerformed private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked // TODO add your handling code here: }//GEN-LAST:event_jPanel1MouseClicked private void jFileChooser2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser2ActionPerformed JFileChooser selectorArchios = (JFileChooser) evt.getSource(); String comando = evt.getActionCommand(); if(comando.equals(JFileChooser.APPROVE_SELECTION)){ File archiSeleccionado = selectorArchios.getSelectedFile(); adactarImagen(archiSeleccionado); jDialog1.setVisible(false); //JOptionPane.showMessageDialog(null, ""+archiSeleccionado+" nOMBRE"+archiSeleccionado.getName()); }// TODO add your handling code here: }//GEN-LAST:event_jFileChooser2ActionPerformed private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed System.exit(0); }//GEN-LAST:event_jMenuItem8ActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed for (int j = 0; j < tope; j++) { arboles.setCordeX(j,0); arboles.setCordeY(j,0); arboles.setNombre(j,0); } for (int j = 0; j < tope; j++) { for (int k = 0; k < tope; k++) { arboles.setmAdyacencia(j, k, 0); arboles.setmCoeficiente(j, k, 0); } } tope=00; jPanel1.repaint(); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed if(tope==0) JOptionPane.showMessageDialog(null,"Aun no se ha credo un nodo : "); else{ this.setEnabled(false); new Matrixs(tope,arboles,1,this).setVisible(true); } }//GEN-LAST:event_jMenuItem7ActionPerformed private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed if(tope==0) JOptionPane.showMessageDialog(null,"Aun no se ha credo un nodo : "); else{ this.setEnabled(false); new Matrixs(tope,arboles,2,this).setVisible(true); } }//GEN-LAST:event_jMenuItem5ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed if(tope<=1) JOptionPane.showMessageDialog(null,"Cree nuevo nodo : "); else{ this.setEnabled(false); new EdgeWindow(arboles,pintar,tope,this).setVisible(true); jPanel1.paint(jPanel1.getGraphics()); R_repaint(tope,arboles); } }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem13ActionPerformed if(tope>=2){ permanente = ingresarNodoOrigen("Ingrese Nodo Origen..","nodo Origen No existe",tope);// hacemos el llamano de la funcion nodoFin = ingresarNodoOrigen("Ingrese Nodo Fin..","nodo fin No existe",tope); DijkstraAlgorithm Dijkstra = new DijkstraAlgorithm(arboles,tope,permanente,nodoFin); Dijkstra.dijkstra(); //jtacumulado.setText(""+Dijkstra.getAcumulado()); } else JOptionPane.showMessageDialog(null,"Se deben de crear mas nodos ... "); }//GEN-LAST:event_jMenuItem13ActionPerformed private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu3ActionPerformed jFrame2.setVisible(true); jFrame2.setSize(783, 458); jFrame2.setLocationRelativeTo(null); }//GEN-LAST:event_jMenu3ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed taskList.sort(); Arbol arbol = new Arbol(); TASKNODE node = taskList.Head; while(node != null){ arbol.insertar(node); node = node.getNext(); } lienzoarbol objLienzo = new lienzoarbol(); Controlador objControl = new Controlador(objLienzo, arbol); objControl.iniciar(); JFrame ventana = new JFrame(); ventana.setVisible(true); ventana.setSize(1001, 572); ventana.setLocationRelativeTo(null); ventana.getContentPane().add(objLienzo); ventana.setDefaultCloseOperation(3); TASKNODE node1 = taskList.Head; while (node1 != null) { jComboBox5.addItem(Integer.toString(node1.VERTEX.getIDTK())); node1 = node1.getNext(); } jFrame3.setVisible(true); jFrame3.setSize(1001, 572); jFrame3.setLocation(500, 500); }//GEN-LAST:event_jMenuItem3ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed TASKNODE node = taskList.Head; while (node != null){ jComboBox3.addItem(node.getVERTEX().getDESCRIPTION()); node = node.getNext(); } jFrame1.setVisible(true); jFrame1.setSize(451, 527); jFrame1.setLocationRelativeTo(null); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed TASK task = new TASK(); TASKSLIST taskL = new TASKSLIST(); task.setSUBTASKLIST(taskL); task.setIDTK(Integer.parseInt(jTextField2.getText())); task.setDESCRIPTION(jTextField3.getText()); task.setCOMPLEXITY(jTextField4.getText()); task.setTKMANAGER(jTextField1.getText()); task.setTKTYPE(jComboBox1.getSelectedItem().toString()); taskList.insert(task); jTextField1.setText(""); jTextField2.setText(""); jTextField3.setText(""); jTextField4.setText(""); }//GEN-LAST:event_jButton2ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed jFrame2.setVisible(false); }//GEN-LAST:event_jButton8ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed jFrame1.setVisible(false); }//GEN-LAST:event_jButton6ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed TASK subTask = new TASK(); subTask.setIDTK(Integer.parseInt(jTextField5.getText())); subTask.setDESCRIPTION(jTextField6.getText()); subTask.setCOMPLEXITY(jTextField7.getText()); subTask.setTKMANAGER(jTextField8.getText()); subTask.setTKTYPE((String)jComboBox2.getSelectedItem()); TASK selected = taskList.findData((String)jComboBox3.getSelectedItem()); TASKSLIST auxi = selected.getSUBTASKLIST(); auxi.insert(subTask); }//GEN-LAST:event_jButton5ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed TASKSLIST subTaskList = new TASKSLIST(); subTaskList = aux; subTaskList.seelist(); TASK selected = taskList.findData((String)jComboBox3.getSelectedItem()); selected.setSUBTASKLIST(subTaskList); //subTasks.clear(); }//GEN-LAST:event_jButton4ActionPerformed private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed TASK task1 = taskList.findIDK(Integer.parseInt((String)jComboBox5.getSelectedItem())); TASKSLIST subtask1 = task1.getSUBTASKLIST(); //subtask1.seelist(); TASKNODE node2 = subtask1.Head; while (node2 != null) { jTextArea1.append(node2.VERTEX.getDESCRIPTION() + "\n"); node2 = node2.getNext(); } }//GEN-LAST:event_jButton9ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { } private int tope=0;// lleva el # de nodos creado private int nodoFin; private int permanente; int n=0,nn=0,id,id2;// permite controlar que se halla dado click sobre un nodo private int aristaMayor; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JComboBox<String> jComboBox3; private javax.swing.JComboBox<String> jComboBox4; private javax.swing.JComboBox<String> jComboBox5; private javax.swing.JDialog jDialog1; private javax.swing.JFileChooser jFileChooser2; private javax.swing.JFrame jFrame1; private javax.swing.JFrame jFrame2; private javax.swing.JFrame jFrame3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem10; private javax.swing.JMenuItem jMenuItem12; private javax.swing.JMenuItem jMenuItem13; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem5; private javax.swing.JMenuItem jMenuItem7; private javax.swing.JMenuItem jMenuItem8; private javax.swing.JMenuItem jMenuItem9; public static javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JPopupMenu.Separator jSeparator4; private javax.swing.JPopupMenu.Separator jSeparator5; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; private javax.swing.JTextField jTextField13; private javax.swing.JTextField jTextField14; private javax.swing.JTextField jTextField2; public static javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; private javax.swing.JLabel jmapa; // End of variables declaration//GEN-END:variables }
C++
UTF-8
274
3.375
3
[]
no_license
class Solution { public: string toLowerCase(string str) { string ans = ""; for (char c : str) { if (65 <= c && c <= 90) ans += (char)(c + 32); else ans += c; } return ans; } };
C#
UTF-8
5,260
2.703125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSquared { public abstract class Primary<T, J> : IPrimary, IInitializable, ICastable<CSquaredString>, ICastable<CSquaredBoolean> where J : Primary<T, J>, new() { public virtual T Value { get; set; } public static J From(T value) { return new J { Value = value }; } public virtual IExpression Initialize(CSquaredEnvironment environment) { return new J { Value = this.Value }; } public virtual IExpression Evaluate(CSquaredEnvironment environment) { return this; } CSquaredString ICastable<CSquaredString>.CastTo() { return CSquaredString.From(this.ToString()); } CSquaredBoolean ICastable<CSquaredBoolean>.CastTo() { return CSquaredBoolean.From(!(this is Null)); } public virtual IPrimary Add(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted addition of an unsupported type: " + this.GetType()); } public virtual IPrimary Subtract(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted subtraction of an unsupported type: " + this.GetType()); } public virtual IPrimary Multiply(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted multiplication of an unsupported type: " + this.GetType()); } public virtual IPrimary Divide(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted division of an unsupported type: " + this.GetType()); } public virtual CSquaredBoolean LessThanOrEqual(CSquaredEnvironment environment, IExpression expression) { return CSquaredBoolean.From(this.LessThan(environment, expression).Value || this.Equal(environment, expression).Value); } public virtual CSquaredBoolean GreaterThanOrEqual(CSquaredEnvironment environment, IExpression expression) { return CSquaredBoolean.From(this.GreaterThan(environment, expression).Value || this.Equal(environment, expression).Value); } public virtual CSquaredBoolean LessThan(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted logical less than of an unsupported type: " + this.GetType()); } public virtual CSquaredBoolean GreaterThan(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted logical greater than of an unsupported type: " + this.GetType()); } public virtual CSquaredBoolean Equal(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted logical equivilance of an unsupported type: " + this.GetType()); } public virtual CSquaredBoolean And(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted logical and of an unsupported type: " + this.GetType()); } public virtual CSquaredBoolean Or(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted logical or of an unsupported type: " + this.GetType()); } public virtual CSquaredBoolean NotEqual(CSquaredEnvironment environment, IExpression expression) { return CSquaredBoolean.From(!this.Equal(environment, expression).Value); } public virtual CSquaredBoolean Not(CSquaredEnvironment environment) { throw new NotSupportedException("Attempted take the logical negation of an unsupported type: " + this.GetType()); } public virtual IExpression Access(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted to access a member of an unsupported type: " + this.GetType()); } public virtual IExpression InsertLeft(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted to insert left on an unsupported type: " + this.GetType()); } public virtual IExpression InsertRight(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted to insert right on an unsupported type: " + this.GetType()); } public virtual IExpression Index(CSquaredEnvironment environment, IExpression expression) { throw new NotSupportedException("Attempted to index an unsupported type: " + this.GetType()); } public override string ToString() { return this.Value.ToString(); } } }
Python
UTF-8
902
3.796875
4
[]
no_license
import unittest from src.card import Card from src.card_game import CardGame class CardGameTest(unittest.TestCase): def setUp(self): self.card = Card("Spades", 1) self.card_2 = Card("Hearts", 2) self.cards = [self.card, self.card_2] self.game = CardGame() def test_check_for_ace_true(self): actual = self.game.checkforAce(self.card) self.assertTrue(actual) def test_check_for_ace_false(self): actual = self.game.checkforAce(self.card_2) self.assertFalse(actual) def test_card_2_is_higher_than_card_1_return_card_1(self): expected = self.card_2 actual = self.game.highest_card(self.card_2, self.card) self.assertEqual(expected, actual) def test_card_has_total_of_2(self): actual = self.game.cards_total(self.cards) self.assertEqual("You have a total of 2", actual)
C#
UTF-8
425
3.453125
3
[]
no_license
using System; using System.Threading; namespace Tester { public class Loop50Times : ITester { public void Run() { for (int i = 0; i < 50; i++) { Console.WriteLine("Loop " + i); Thread.Sleep(1000); } } public string Description { get { return "Loop 50 times and sleep 1 second for each loop."; } } } }
Go
UTF-8
487
3.34375
3
[]
no_license
package v1 type quickUnion struct { nodes []int } func NewQuickUnion(n int) *quickUnion { qu := quickUnion{nodes: make([]int, n)} for i := range qu.nodes { qu.nodes[i] = i } return &qu } func (qu *quickUnion) Connected(p,q int) bool { return qu.root(p) == qu.root(q) } func (qu *quickUnion) Union(p,q int) { pRoot := qu.root(p) qRoot := qu.root(q) qu.nodes[qRoot] = pRoot } func (qu *quickUnion) root(i int) int { for qu.nodes[i] != i { i = qu.nodes[i] } return i }
C
UTF-8
579
3.21875
3
[]
no_license
#include <stdio.h> #include <time.h> int main(void) { struct tm t; time_t t_of_day; t_of_day = time(NULL); printf("Time retunred from functions is %ld\n",t_of_day); if (t_of_day >= 1572546600 && t_of_day <=1580581799) { printf("PASSED! You reset the time successfully!\n") ; } else { printf("Your valdiation is expired\n") ; } printf("Calling second time time function:\n"); t_of_day = time(NULL); printf("Time retunred from functions is %ld\n",t_of_day); }
Java
UTF-8
465
2.328125
2
[]
no_license
package tomato.editor; import java.awt.BorderLayout; import javax.swing.JColorChooser; import javax.swing.JFrame; import javax.swing.JPanel; public class Window { private JFrame frame; private JPanel blocks; public Window() { frame = new JFrame(); blocks = new JPanel(); frame.getContentPane().add(BorderLayout.EAST, blocks); blocks.add(new JColorChooser()); frame.setSize(300, 300); frame.setVisible(true); } }
Markdown
UTF-8
3,442
2.78125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: 'CA1051: Do not declare visible instance fields' ms.date: 03/11/2019 ms.topic: reference f1_keywords: - CA1051 - DoNotDeclareVisibleInstanceFields helpviewer_keywords: - CA1051 - DoNotDeclareVisibleInstanceFields ms.assetid: 2805376c-824c-462c-81d1-c51aaf7cabe7 author: mikejo5000 ms.author: mikejo manager: jillfra ms.workload: - multiple --- # CA1051: Do not declare visible instance fields ||| |-|-| |TypeName|DoNotDeclareVisibleInstanceFields| |CheckId|CA1051| |Category|Microsoft.Design| |Breaking change|Breaking| ## Cause A type has a non-private instance field. By default, this rule only looks at externally visible types, but this is [configurable](#configurability). ## Rule description The primary use of a field should be as an implementation detail. Fields should be `private` or `internal` and should be exposed by using properties. It's as easy to access a property as it is to access a field, and the code in the accessors of a property can change as the features of the type expand without introducing breaking changes. Properties that just return the value of a private or internal field are optimized to perform on par with accessing a field; the performance gain from using externally visible fields instead of properties is minimal. *Externally visible* refers to `public`, `protected`, and `protected internal` (`Public`, `Protected`, and `Protected Friend` in Visual Basic) accessibility levels. Additionally, public fields cannot be protected by [Link demands](/dotnet/framework/misc/link-demands). For more information, see [CA2112: Secured types should not expose fields](../code-quality/ca2112.md). (Link demands are not applicable to .NET Core apps.) ## How to fix violations To fix a violation of this rule, make the field `private` or `internal` and expose it by using an externally visible property. ## When to suppress warnings Only suppress this warning if you're certain that consumers need direct access to the field. For most applications, exposed fields do not provide performance or maintainability benefits over properties. Consumers may need field access in the following situations: - in ASP.NET Web Forms content controls - when the target platform makes use of `ref` to modify fields, such as model-view-viewmodel (MVVM) frameworks for WPF and UWP ## Configurability If you're running this rule from [FxCop analyzers](install-fxcop-analyzers.md) (and not with legacy analysis), you can configure which parts of your codebase to run this rule on, based on their accessibility. For example, to specify that the rule should run only against the non-public API surface, add the following key-value pair to an .editorconfig file in your project: ```ini dotnet_code_quality.ca1051.api_surface = private, internal ``` You can configure this option for just this rule, for all rules, or for all rules in this category (Design). For more information, see [Configure FxCop analyzers](configure-fxcop-analyzers.md). ## Example The following example shows a type (`BadPublicInstanceFields`) that violates this rule. `GoodPublicInstanceFields` shows the corrected code. [!code-csharp[FxCop.Design.TypesPublicInstanceFields#1](../code-quality/codesnippet/CSharp/ca1051-do-not-declare-visible-instance-fields_1.cs)] ## Related rules - [CA2112: Secured types should not expose fields](../code-quality/ca2112.md) ## See also - [Link Demands](/dotnet/framework/misc/link-demands)
JavaScript
UTF-8
11,671
3.15625
3
[ "MIT" ]
permissive
var resultTextEl = document.querySelector('#result-text'); var resultContentEl = document.querySelector('#result-content'); var searchFormEl = document.querySelector('#search-form'); var searchHistoryEl = document.querySelector('.history'); var cityList = [{ name: "", lat: "", lon: "" }]; function getLocalStorage(){ // We want to get the cities from the local storage, if there are any // This also populates the data object cityList = JSON.parse(localStorage.getItem("cityList")); if (cityList.length !== 0) { // cityEl holds all of the divs with the class of "description" var historyEl = document.querySelector('.history'); var cityEl = []; // Add the data to the list for (var i = 0; i < cityList.length; i++) { // The children of these particular divs need to be clickable elements cityEl[i] = document.createElement('button'); cityEl[i].classList.add('btn', 'btn-info', 'btn-block', 'bg-secondary'); cityEl[i].setAttribute('data-name',cityList[i].name); cityEl[i].setAttribute('data-lat',cityList[i].lat); cityEl[i].setAttribute('data-lon',cityList[i].lon); cityEl[i].textContent = cityList[i].name; historyEl.append(cityEl[i]); } } } // Save the data after the list is updated function handleSaveData(city) { var found = false; if (cityList.length ===1 & cityList[0].name === ""){ // CityList just has the empty placeholder, replace with city cityList = [city]; } else { // cityList has real cities in it, check if the current city is one of them for (var i = 0; i < cityList.length; i++){ if (cityList[i].name === city.name){ found = true; } } // If the current city was not found in the history list, add it to the array and sort the array if (!found) { cityList.push(city); cityList.sort((a,b) => (a.name > b.name) ? 1 : -1); } } // Store the list localStorage.setItem("cityList", JSON.stringify(cityList)); } function printTodayResults(city, resultObj) { // We have a <div class='result-content'> with two children // We have a <div class='current'> for the current days weather // We have a ,div class='five-day'> for the five day forecast // set up `<div>` to hold result content var currentEl = document.querySelector('.current'); while (currentEl.firstChild) { currentEl.removeChild(currentEl.firstChild); } currentEl.classList.add('card', 'w-100', 'bg-light', 'text-dark', 'mb-3', 'p-3'); // Create the current weather header var currentHeader = document.createElement('div'); currentHeader.classList.add('card-header', 'bg-light', 'text-dark', 'p-3'); var date = moment.unix(resultObj.current.dt + resultObj.timezone_offset).format(" (M/D/YYYY) "); var mediaContent = document.createElement('div'); mediaContent.classList.add('media'); mediaBody = document.createElement('div'); mediaBody.classList.add('media-body'); var titleHeader = document.createElement('h2'); titleHeader.textContent = city.name + date; mediaBody.append(titleHeader); var titleIcon = document.createElement('img'); titleIcon.classList.add('img-thumbnail', 'mr-3'); titleIcon.src = "http://openweathermap.org/img/wn/"+resultObj.current.weather[0].icon+"@2x.png"; mediaContent.append(mediaBody, titleIcon); currentHeader.append(mediaContent); currentEl.append(currentHeader); // Create the current weather card content var resultBody = document.createElement('ul'); resultBody.classList.add('list-group','list-group-flush', 'list-unstyled'); var tempList = document.createElement('li'); tempList.classList.add('list-group-item)', 'p-1'); tempList.textContent = "Temp: " + resultObj.current.temp + " °F"; var windList = document.createElement('li'); windList.classList.add('list-group-flush', 'p-1'); windList.textContent = "Wind: " + resultObj.current.wind_speed + " MPH"; var humidList = document.createElement('li'); humidList.classList.add('list-group-flush', 'p-1'); humidList.textContent = "Humidity: " + resultObj.current.humidity + " %"; var uvList = document.createElement('li'); uvList.classList.add('list-group-flush', 'p-1'); var uvi = resultObj.current.uvi; var uviClass = uvRating(uvi); uvBlock = document.createElement('span'); uvBlock.classList.add(uviClass); uvBlock.textContent = uvi; uvList.textContent = "UV Index: "; uvList.append(uvBlock); resultBody.append(tempList, windList, humidList, uvList); currentEl.append(resultBody); // Publish the five day forecast var fivedayEl = document.querySelector('.five-day'); while (fivedayEl.firstChild) { fivedayEl.removeChild(fivedayEl.firstChild); } fivedayEl.classList.add('card', 'w-100', 'bg-light', 'text-dark', 'mb-3', 'p-3'); // Create the heading for the five day forecast block var fivedayHeader = document.createElement('div'); fivedayHeader.classList.add('card-header', 'bg-light', 'text-dark', 'p-3'); var fivedayHeading = document.createElement('h4'); fivedayHeading.textContent = "5-Day Forecast:"; fivedayHeader.append(fivedayHeading); // Create the container for the five forecast cards var fiveGroupEl = document.createElement('div'); fiveGroupEl.classList.add('row'); for (var i = 1; i <= 5; i++){ // Create and populate each card var fiveCard = document.createElement('div'); fiveCard.classList.add( 'card', 'w-20', 'bg-dark', 'text-light', 'p-3', 'm-3') // Create the date header var date = moment.unix(resultObj.daily[i].dt + resultObj.timezone_offset).format("M/D/YYYY"); cardHeader = document.createElement('div'); cardHeader.classList.add('card-header', 'bg-dark', 'text-light', 'p-1', 'm-1'); cardHeader.textContent = date; fiveCard.append(cardHeader); // Create the card content var fivedayBody = document.createElement('ul'); fivedayBody.classList.add('list-group','list-group-flush', 'list-unstyled'); var imgList = document.createElement('li'); imgList.classList.add('list-group-item', 'p-1', 'bg-dark'); var imgThumb = document.createElement('img'); imgThumb.classList.add('img-thumbnail', 'mr-3'); imgThumb.src = "http://openweathermap.org/img/wn/"+resultObj.daily[i].weather[0].icon+"@2x.png"; imgList.append(imgThumb); var tempList = document.createElement('li'); tempList.classList.add('list-group-item)', 'p-1'); tempList.textContent = "Temp: " + resultObj.daily[i].temp.day + " °F"; var windList = document.createElement('li'); windList.classList.add('list-group-flush', 'p-1'); windList.textContent = "Wind: " + resultObj.daily[i].wind_speed + " MPH"; var humidList = document.createElement('li'); humidList.classList.add('list-group-flush', 'p-1'); humidList.textContent = "Humidity: " + resultObj.daily[i].humidity + " %"; var uvList = document.createElement('li'); uvList.classList.add('list-group-flush', 'p-1'); var uvi = resultObj.daily[i].uvi; var uviClass = uvRating(uvi); uvBlock = document.createElement('span'); uvBlock.classList.add(uviClass); uvBlock.textContent = uvi; uvList.textContent = "UV Index: "; uvList.append(uvBlock); fivedayBody.append(imgList, tempList, windList, humidList, uvList); //add the five forecast cards to the fiveGroupEl container fiveCard.append(fivedayBody); fiveGroupEl.append(fiveCard); } // Add the fiveGroupContainer to the five day forecast container fivedayEl.append(fivedayHeader, fiveGroupEl); } function uvRating(uvi){ // Determine severity of UV Index switch (Math.round(uvi)){ case 0: case 1: case 2: uviClass = 'uvi-low'; break; case 3: case 4: case 5: uviClass = 'uvi-moderate'; break; case 6: case 7: uviClass = 'uvi-high'; break; case 8: case 9: case 10: uviCLass = 'uvi-veryHigh'; break; default: uviClass = 'uvi-extreme'; } return uviClass; } function searchApi(query) { // This function takes the city name as the input and // calls the openweathermap API to get today's data // API Documentation: // api.openweathermap.org/data/2.5/weather?q={city name}&appid=ae645017a7275733894562a7a4d6f737 // Start to building the URL shown above var locQueryUrl = 'https://api.openweathermap.org/data/2.5/weather'; // This is Barry's appid, please don' share it var apiKey = '&units=imperial&appid=ae645017a7275733894562a7a4d6f737'; // defining an object named city to hold the city name and location // This info is necessary if you want to have multiday forecast var city = { name: "", lat: "", lon: "" }; // This combines the start of the URL from above with the // city name that the function receives in 'query' and // appends the apiKey (which includes a request for Imperial units) locQueryUrl = locQueryUrl + '?q=' + query + apiKey; //The fetch function calls the API with the URL that was built above fetch(locQueryUrl) .then(function (response) { if (!response.ok) { throw response.json(); } return response.json(); }) .then(function (locRes) { // The if statement checks to see if a city name has been returned // If not, it prints a message to the log and can add a message to a page if you set that up. if (!locRes.name.length) { console.log('No results found!'); //resultContentEl.innerHTML = '<h3>No results found, search again!</h3>'; } else { // If a result was returned, the result for lat and long can be // to the onecall api to get the current weather and the five day // Must use this call to get the UV Index data. city.name = locRes.name; city.lat = locRes.coord.lat; city.lon = locRes.coord.lon; handleSaveData(city); getWeather(city); } }) .catch(function (error) { console.error(error); }); } function getWeather(city){ // api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude={part}&appid=ae645017a7275733894562a7a4d6f737 var locOnecallQueryUrl = 'https://api.openweathermap.org/data/2.5/onecall?'; var apiKey = '&units=imperial&appid=ae645017a7275733894562a7a4d6f737'; // Buiuld the URL for the onecall query, excluding minutely, hourly and alert data (so just currrent and daily) locOnecallQueryUrl = locOnecallQueryUrl + 'lat=' + city.lat + '&lon=' + city.lon + '&exclude=minutely,hourly,alerts' + apiKey; fetch(locOnecallQueryUrl) .then(function (response) { if (!response.ok) { throw response.json(); } return response.json(); }) .then(function (locRes) { if (locRes.daily.length == 0) { console.log('No results found!'); resultContentEl.innerHTML = '<h3>No results found, search again!</h3>'; } else { printTodayResults(city, locRes); } }) .catch(function (error) { console.error(error); }); } function handleSearchFormSubmit(event) { event.preventDefault(); var searchInputVal = document.querySelector('#search-input').value; if (!searchInputVal) { console.error('You need a search input value!'); return; } searchApi(searchInputVal); } function handleSearchHistorySubmit(event) { event.preventDefault(); var element = event.target; if (element.matches("button")) { var city = element.getAttribute("data-name"); } searchApi(city); } getLocalStorage(); searchFormEl.addEventListener('submit', handleSearchFormSubmit); searchHistoryEl.addEventListener('click', handleSearchHistorySubmit);
Python
UTF-8
2,436
3.203125
3
[ "GPL-3.0-only", "LGPL-3.0-only" ]
permissive
# Copyright (c) 2019 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from datetime import datetime, timezone from typing import TypeVar, Dict, List, Any, Type, Union # Type variable used in the parse methods below, which should be a subclass of BaseModel. T = TypeVar("T", bound="BaseModel") class BaseModel: def __init__(self, **kwargs) -> None: self.__dict__.update(kwargs) self.validate() # Validates the model, raising an exception if the model is invalid. def validate(self) -> None: pass ## Checks whether the two models are equal. # \param other: The other model. # \return True if they are equal, False if they are different. def __eq__(self, other): return type(self) == type(other) and self.toDict() == other.toDict() ## Checks whether the two models are different. # \param other: The other model. # \return True if they are different, False if they are the same. def __ne__(self, other) -> bool: return type(self) != type(other) or self.toDict() != other.toDict() ## Converts the model into a serializable dictionary def toDict(self) -> Dict[str, Any]: return self.__dict__ ## Parses a single model. # \param model_class: The model class. # \param values: The value of the model, which is usually a dictionary, but may also be already parsed. # \return An instance of the model_class given. @staticmethod def parseModel(model_class: Type[T], values: Union[T, Dict[str, Any]]) -> T: if isinstance(values, dict): return model_class(**values) return values ## Parses a list of models. # \param model_class: The model class. # \param values: The value of the list. Each value is usually a dictionary, but may also be already parsed. # \return A list of instances of the model_class given. @classmethod def parseModels(cls, model_class: Type[T], values: List[Union[T, Dict[str, Any]]]) -> List[T]: return [cls.parseModel(model_class, value) for value in values] ## Parses the given date string. # \param date: The date to parse. # \return The parsed date. @staticmethod def parseDate(date: Union[str, datetime]) -> datetime: if isinstance(date, datetime): return date return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
JavaScript
UTF-8
3,015
2.6875
3
[]
no_license
import Wave from './wave'; import options from '../options'; import { optionGetter } from '../utils'; export default class Waves { constructor(params = {}) { const optionOr = optionGetter(params); this.cols = optionOr('cols', 10); this.rows = optionOr('rows', 10); this.speed = optionOr('speed', 10); this.frameCount = 0; this.time = 0; // Keeps track of recurring waves. this.recurring = {}; // Keeps track of all waves. this.registry = {}; // Triggers - callbacks for specific nodes. this.triggers = {}; } splash(col, row) { if (!this.registry.hasOwnProperty(Waves._hash(col, row, this.time))) { const waveIndex = Object.keys(this.registry).length; if (waveIndex < options.waves.maxWaves) { this.registry[Waves._hash(col, row, this.time)] = new Wave(this, { originX: col, originY: row, index: waveIndex }); } console.log(`Wave created: ${Waves._hash(col, row, this.time)}`); } } unsplash(col, row) { for (let wave in this.registry) { if (this.registry[wave].insideWave(col, row)) { delete this.registry[wave]; break; } } } // Create a wave if a certain node is hit splash_if(col, row, repeat = true) { this.setTrigger(col, row, () => { this.splash(col, row); }, "wave", repeat); } // Like triggers, except we keep them conceptually separate setListener(col, row, fn) { this.setTrigger(col, row, fn, "listener", true); } // When a wave hits this col, row, fn gets called. setTrigger(col, row, fn, type = "wave", repeat = true) { this.triggers[Waves._triggerHash(col, row)] = { repeat: repeat, action: fn, type: type, x: col, y: row }; } // Retrieve a trigger getTrigger(col, row) { if (this.triggers.hasOwnProperty(Waves._triggerHash(col, row))) { return this.triggers[Waves._triggerHash(col, row)]; } else { return null; } } deleteTrigger(col, row) { if (this.triggers.hasOwnProperty(Waves._triggerHash(col, row))) { delete this.triggers[Waves._triggerHash(col, row)]; } } // Does a trigger exist? armed(col, row) { return this.triggers.hasOwnProperty(Waves._triggerHash(col, row)); } // Remove a trigger disarm(col, row) { delete this.triggers[Waves._triggerHash(col, row)]; } update() { let toDelete = []; this.frameCount++; if (this.frameCount % this.speed == 0) { this.time++; for (let wave in this.registry) { this.registry[wave].update(this); if (!this.registry[wave].inGrid()) { toDelete.push(wave) }; } } for (let wave of toDelete) { delete this.registry[wave]; } } static _hash(col, row, frameCreated) { return `${col}-${row}-${frameCreated}`; } static _triggerHash(col, row) { return `${col}-${row}`; } *[Symbol.iterator]() { for (let wave in this.registry) { yield this.registry[wave]; } } } const makeOptionGrabber = (paramObject) => { return (paramName, deflt) => { return paramObject.hasOwnProperty(paramName) ? paramObject[paramName] : deflt; } }
C#
UTF-8
776
2.625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HealthSystem : MonoBehaviour { public int maxHealth = 5; public static int currentHealth; public Healthbar healthBar; private void Start() { currentHealth = maxHealth; healthBar.SetMaxHealth(maxHealth); } void Update() { if (currentHealth > maxHealth) currentHealth = maxHealth; if (currentHealth <= 0) { currentHealth = 0; FindObjectOfType<GameManager>().EndGame(); } } public static void HurtPlayer(int damageToGive) { currentHealth -= damageToGive; PlayerPrefs.SetInt("PlayerCurrentHealth", currentHealth); } }
Java
UTF-8
410
2.90625
3
[]
no_license
package com.yan.design.mode.interpreter.demo2; /** * @author : 楠GG * @date : 2017/12/23 9:19 * @description : 抽象的算术运算解释器,为所有解释器共性的提取 */ public abstract class ArithmeticExpression { /** * 抽象的解析方法 * 具体的解析逻辑由具体的子类实现 * @return 解析得到具体的值 */ public abstract int interpret(); }
Python
UTF-8
892
3.578125
4
[]
no_license
voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222} for county, voters in counties_dict.items(): # print(county + " county has " + str(voters) + " registered voters.") print(f"{county} county has {voters} registered voters.") candidate_votes = int(input("How many votes did the candidate get in the election? ")) total_votes = int(input("What is the total number of votes in the election? ")) message_to_candidate = ( f"You received {candidate_votes} number of votes. " f"The total number of votes in the election was {total_votes:,}. " f"You received {candidate_votes / total_votes * 100:.3f}% of the total votes.") print(message_to_candidate)
Python
UTF-8
1,943
2.546875
3
[]
no_license
from flask import Flask from flask import Response from flask import request from flask import render_template import logging as log from cloud import generate_text_wordcloud app = Flask(__name__) def standard_page(html_file,title): content = '' content = content + render_template('header.html', title=title) with open(html_file) as index: content = content + index.read() #content = content + render_template('footer.html') return content def get_results(): text = request.form['input_text'] if len(text) < 2: results = '<div class="alert alert-danger" role="alert">There were not enough words</div>' return results bgcolor = request.form['bgcolor'] width = request.form['width'] if width == '': width = 400 height = request.form['height'] if height == '': height = 200 if 'file' in request.files: mask = request.files['file'] else: mask = None image_path = generate_text_wordcloud(text, bgcolor, width, height, mask) results = '<img src="{}" alt="{}">'.format(image_path, image_path) return results @app.route('/') def index(): content = standard_page('index.html', "Home") return Response(content, mimetype='text/html') @app.route('/generate.html', methods=['POST', 'GET']) def generate(): if 'POST' == request.method: results = get_results() else: results = '<p>Results will display here!</p>' content = '' content = content + render_template('header.html', title='Generate') content = content + render_template('generate.html', results=results) #content = content + render_template('footer.html') return Response(content, mimetype='text/html') @app.route('/about.html') def about(): content = standard_page('about.html', 'About') return Response(content, mimetype='text/html') if __name__ == '__main__': app.run()
Python
UTF-8
3,326
2.8125
3
[]
no_license
#encoding:utf8 import tensorflow as tf import pandas as pd import numpy as np import re import os from sklearn import metrics DATA_PATH = "D:\\AllCode\\Datas\\NLP\\Sentiment\\twitter\\" EMBEDDING_PATH = DATA_PATH + "data\\GoogleNews-vectors-negative300.bin" def clean_str(string): """ Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py """ string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) string = re.sub(r"\'re", " \'re", string) string = re.sub(r"\'d", " \'d", string) string = re.sub(r"\'ll", " \'ll", string) string = re.sub(r",", " , ", string) string = re.sub(r"!", " ! ", string) string = re.sub(r"\(", " \( ", string) string = re.sub(r"\)", " \) ", string) string = re.sub(r"\?", " \? ", string) string = re.sub(r"\s{2,}", " ", string) return string.strip().lower() def get_data(datapath): x_tmp = [] y_tmp = [] label_dic = {'negative': -1, 'neutral': 0, 'positive': 1} files = os.listdir(datapath) for file in files: if not os.path.isdir(file): lines = open(datapath + file, 'r', encoding='UTF8').readlines() for line in lines: twi_list = line.split('\t') if len(twi_list) >= 3: x_tmp.append(clean_str(twi_list[2].strip())) y_tmp.append(label_dic[twi_list[1]]) x = pd.Series(np.asarray(x_tmp)) y = pd.Series(np.asarray(y_tmp)) return x, y #build model EMBEDDING_SIZE = 70 def bag_of_words_model(features, target): """A bag-of-words model. Note it disregards the word order in the text.""" target = tf.one_hot(target, 15, 1, 0) features = tf.contrib.layers.bow_encoder(features, vocab_size=n_words, embed_dim=EMBEDDING_SIZE) logits = tf.contrib.layers.fully_connected(features, 15,activation_fn=None) loss = tf.contrib.losses.softmax_cross_entropy(logits, target) train_op = tf.contrib.layers.optimize_loss(loss, tf.contrib.framework.get_global_step(),optimizer='Adam', learning_rate=0.01) return ( {'class': tf.argmax(logits, 1), 'prob': tf.nn.softmax(logits)}, loss, train_op ) if __name__ == '__main__': # prepare train and test data x_train, y_train = get_data(DATA_PATH + "train\\") x_test, y_test = get_data(DATA_PATH + "test\\") print(x_train.shape, y_train.shape, x_test.shape, y_test.shape) # process vacab MAX_DOCUMENT_LENGTH = 70 vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(MAX_DOCUMENT_LENGTH) x_train = np.array(list(vocab_processor.fit_transform(x_train))) x_test = np.array(list(vocab_processor.transform(x_test))) n_words = len(vocab_processor.vocabulary_) print(x_train[100]) #train and test classifier = tf.contrib.learn.Estimator(model_fn=bag_of_words_model) # Train and predict classifier.fit(x_train, y_train, steps=1) y_predicted = [p['class'] for p in classifier.predict(x_test, as_iterable=True)] score = metrics.accuracy_score(y_test, y_predicted) print('Accuracy: {0:f}'.format(score))
PHP
UTF-8
1,348
2.578125
3
[]
no_license
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class M_videos extends CI_Model { public function __construct() { parent::__construct(); } public function create($data) { if (!$data) return false; $this->db->insert('videos', $data); $video_id = $this->db->insert_id(); return $video_id; } public function update($id, $data) { if (!$data || !$id) return false; $id = (int)$id; $this->db->update('videos', $data, array('id'=>$id)); return true; } public function getItem($id = 0) { $id = (int)$id; if (!$id) return array(); $this->db->where('id', $id); $query = $this->db->get('videos', 1); $video = $query->row_array(); if (!$video) return false; return $video; } public function getItems($where = array(), $order = array()) { $where['is_deleted'] = 0; if (!$order) $order['id'] = 'desc'; $this->db->where($where); if ($order){ foreach($order as $o_key=>$o_val) { $this->db->order_by($o_key, $o_val); } } $query = $this->db->get('videos', 16); $videos=$query->result_array(); return $videos; } }
C++
UTF-8
963
2.703125
3
[]
no_license
#include "explosion.hpp" explosion::explosion( const float radius, const float force ) : radius(radius) , force(force) {} void explosion::explode( const b2Vec2 pos, b2World* world ) { ExplodeAABBCallback callback; b2AABB aabb; aabb.lowerBound = b2Vec2(pos.x - radius, pos.y - radius); aabb.upperBound = b2Vec2(pos.x + radius, pos.y + radius); world->QueryAABB(&callback, aabb); for(auto && m : callback.bodies) { const b2Vec2 mpos = m->GetPosition(); const float d = dist(pos.x, pos.y, mpos.x, mpos.y); if(d >= radius) { continue; } const float f = map_val( d, 0.0f, radius, force, 0.0f ); b2Vec2 force_vec(mpos.x - pos.x, mpos.y - pos.y); force_vec.Normalize(); force_vec *= f; m->ApplyForce( force_vec, m->GetWorldCenter(), true ); } }
JavaScript
UTF-8
4,093
2.53125
3
[]
no_license
import React, {Component} from "react"; import { Link} from "react-router-dom"; import BlogPost from './BlogPost'; import nopostimg from './img/noposts.png'; import ErrorPage from "./ErrorPage"; class PostLoader extends Component { constructor(props) { super(props); var fetchUrl = ''; if (this.props.match === undefined) { fetchUrl = '/'; } else if (this.props.match.params.search) { fetchUrl = '/search_all/' + this.props.match.params.search; } else if (!isNaN(this.props.match.params.id)) { fetchUrl = '/' + this.props.match.params.id; } this.listAllBlogPosts = this.listAllBlogPosts.bind(this); this.updatePosts = this.updatePosts.bind(this); this.state = {fetchUrl: fetchUrl , arrayOfBlogPosts: [] , fetchedBlogPosts: [] , isFetching: false , postsFrom: 0 , postsTo: 5 }; } componentDidMount() { this.setState({isFetching: true}); let fetchURL = '/api/blogposts' + this.state.fetchUrl; fetch(fetchURL).then((httpResponse) => httpResponse.json()).then((json) => this.setState({fetchedBlogPosts: json})).then(() => this.updatePosts()); } updatePosts() { this.setState({isFetching: false}); this.listAllBlogPosts(); //fetch('/api/blogposts/').then((httpResponse) => httpResponse.json()).then(this.listAllBlogPosts); } listAllBlogPosts() { let helperArray = []; if(this.state.fetchedBlogPosts.status) { helperArray.push(<ErrorPage key={1} message={"Blog post not found 404"}/>) } else if(this.state.fetchedBlogPosts.length === undefined) { helperArray.push(<BlogPost key={this.state.fetchedBlogPosts.id} post={this.state.fetchedBlogPosts} ownPage={true} />); } else { for (let post of this.state.fetchedBlogPosts) { helperArray.push(<BlogPost key={post.id} post={post} ownPage={false}/>); } } this.setState({arrayOfBlogPosts: helperArray}); } loadOlderPosts = () => { let newPostsFrom = this.state.postsFrom + 5; let newPostsTo = this.state.postsTo + 5; this.setState({postsFrom: newPostsFrom , postsTo: newPostsTo}); } loadNewerPosts = () => { let newPostsFrom = this.state.postsFrom - 5; let newPostsTo = this.state.postsTo - 5; this.setState({postsFrom: newPostsFrom , postsTo: newPostsTo}); } render() { return ( <div> {this.state.isFetching ? <p>Loading....</p> : this.state.arrayOfBlogPosts.length <= 0 ? <div> <h1 className={"newpostTitle"}>No blog posts :'(</h1> <img className={"nopostsimg"} src={nopostimg} alt={"Crying potoo"}></img> </div> : this.state.arrayOfBlogPosts.length > 5 ? <div> {this.state.arrayOfBlogPosts.slice(this.state.postsFrom, this.state.postsTo)} {(this.state.postsFrom + 5) < this.state.arrayOfBlogPosts.length && <button className={"postsSpan"} onClick={this.loadOlderPosts}><i className='fas fa-arrow-alt-circle-left'></i>Older posts &nbsp;</button> } {(this.state.postsFrom-5) >= 0 && <button className={"postsSpan"} onClick={this.loadNewerPosts}><i className='fas fa-arrow-alt-circle-right'></i>Newer posts &nbsp;</button> } </div> : this.state.arrayOfBlogPosts } </div> ); } } export default PostLoader;
Java
UTF-8
1,711
2.140625
2
[]
no_license
package br.com.jortec.mide; import android.*; import android.content.pm.PackageInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class SobreActivity extends AppCompatActivity { private Toolbar toolbar; private TextView tvSobre; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sobre); iniciarView(); } public void iniciarView(){ toolbar = (Toolbar) findViewById(R.id.tb_sobre); toolbar.setTitle("Sobre"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); tvSobre = (TextView) findViewById(R.id.tv_sobre); tvSobre.setText("Projeto MIDE v"+BuildConfig.VERSION_NAME); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_sobre, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } }
Java
UTF-8
16,149
2.25
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quiz; import javax.swing.JOptionPane; /** * * @author Sabrina Correia */ public class ventana3 extends javax.swing.JFrame { private final ventana1 v1; private final LinkedList lista; /** * Creates new form ventana3 */ public ventana3(ventana1 v1, LinkedList lista) { initComponents(); this.v1 = v1; this.lista = lista; v1.setVisible(false); this.setLocationRelativeTo(null); this.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTextField10 = new javax.swing.JTextField(); i1 = new javax.swing.JTextField(); i2 = new javax.swing.JTextField(); i3 = new javax.swing.JTextField(); i4 = new javax.swing.JTextField(); i5 = new javax.swing.JTextField(); i6 = new javax.swing.JTextField(); i7 = new javax.swing.JTextField(); i8 = new javax.swing.JTextField(); i9 = new javax.swing.JTextField(); i10 = new javax.swing.JTextField(); i11 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); agregar = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jTextField10.setText("jTextField10"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); i1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { i1ActionPerformed(evt); } }); i4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { i4ActionPerformed(evt); } }); i9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { i9ActionPerformed(evt); } }); jLabel1.setText("AGREGAR:"); agregar.setText("AGREGAR"); agregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { agregarActionPerformed(evt); } }); jButton1.setText("ATRAS"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel2.setText("nombre"); jLabel3.setText("cedula"); jLabel4.setText("carnet"); jLabel5.setText("apellido"); jLabel6.setText("quiz1"); jLabel7.setText("parcial1"); jLabel8.setText("proyecto1"); jLabel9.setText("quiz2"); jLabel10.setText("parcial2"); jLabel11.setText("proyecto2"); jLabel12.setText("total"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(78, 78, 78) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel2) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel8) .addComponent(jLabel9) .addComponent(jLabel10) .addComponent(jLabel11) .addComponent(jLabel12)))) .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(i4) .addComponent(i5) .addComponent(i6) .addComponent(i7) .addComponent(i8) .addComponent(i9) .addComponent(i10) .addComponent(i11) .addComponent(i1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(i2) .addComponent(i3)) .addGap(115, 115, 115)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(jButton1) .addGap(96, 96, 96) .addComponent(agregar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(i11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(agregar) .addComponent(jButton1)) .addContainerGap(10, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void i9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_i9ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_i9ActionPerformed private void i1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_i1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_i1ActionPerformed private void i4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_i4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_i4ActionPerformed private void agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarActionPerformed try { Alumno nue = new Alumno(Integer.parseInt(i1.getText()), i2.getText(), i3.getText(), i4.getText(), Float.parseFloat(i5.getText()), Float.parseFloat(i6.getText()), Float.parseFloat(i7.getText()), Float.parseFloat(i8.getText()), Float.parseFloat(i9.getText()), Float.parseFloat(i10.getText()), Float.parseFloat(i11.getText())); lista.addLast(nue); JOptionPane.showMessageDialog(null, "Agregado exitosamente"); }catch(Exception e){ JOptionPane.showMessageDialog(null, "Error, es posible que puso una letra donde va un numero o dejo un campo vacio"); } }//GEN-LAST:event_agregarActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed v1.setVisible(true); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ventana3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ventana3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ventana3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ventana3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { //new ventana3().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton agregar; private javax.swing.JTextField i1; private javax.swing.JTextField i10; private javax.swing.JTextField i11; private javax.swing.JTextField i2; private javax.swing.JTextField i3; private javax.swing.JTextField i4; private javax.swing.JTextField i5; private javax.swing.JTextField i6; private javax.swing.JTextField i7; private javax.swing.JTextField i8; private javax.swing.JTextField i9; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JTextField jTextField10; // End of variables declaration//GEN-END:variables }
C++
UTF-8
1,917
2.984375
3
[]
no_license
#pragma once #include "stdafx.h" #include <unistd.h> #include <map> using namespace std; class CMImageDataPool { public: //current Key,when create a new memory,it will add 1 static unsigned long long s_nIndex; //memory map,access the memory by appropriate key typedef map<unsigned long long, cv::Mat> MapMemory; static MapMemory s_mapMemory; static bool m_bLock; static int m_nSleepTime; static void Lock() { while(m_bLock) { #ifdef _WINDOWS_ Sleep(m_nSleepTime); #else sleep(m_nSleepTime); #endif continue; } m_bLock = true; } static void UnLock() { m_bLock = false; } //return the Key of memory static int Add(cv::Mat src) { Lock(); s_nIndex ++; /*if(s_nIndex > ULONG_MAX) { s_nIndex = 0; }*/ s_mapMemory.insert(pair<unsigned long long, cv::Mat>(s_nIndex,src)); UnLock(); return s_nIndex; }; //if success to delet appropriate memory,return 1,else return 0 static int Delete(unsigned long long nIndex) { Lock(); map<unsigned long long, cv::Mat>::iterator find = s_mapMemory.find(nIndex); if(find != s_mapMemory.end()) { pair<unsigned long long, cv::Mat> value = *find; value.second.release(); } int n = s_mapMemory.erase(nIndex); UnLock(); return n; } //if success to access appropriate memory,return available object of map,else return unavailable object static Mat Access(unsigned long long nIndex) { Mat dst; Lock(); map<unsigned long long, cv::Mat>::iterator find = s_mapMemory.find(nIndex); if(find != s_mapMemory.end()) { pair<unsigned long long, cv::Mat> value = *find; dst = value.second; } UnLock(); return dst; } static map<unsigned long long, cv::Mat> CreateMap() { map<unsigned long long, cv::Mat> mapData; return mapData; } };
Markdown
UTF-8
9,298
3.234375
3
[]
no_license
# 作业自动化 ## 实验介绍 ### 实验内容 在使用数据库的过程中,通常会有一些重复的事情,比如备份操作,检查错误,启动数据库等等。如果每次都手动操作,不仅有可能忘记而且很麻烦,如果创建一个作业,让系统自动处理会很方便。本节实验主要介绍两个用来实现作业自动化的程序: - `Oracle Scheduler` :这个是 Oracle 提供的。 - `cron` :这个是 Linux 系统本身就有的。 ### 实验知识点 + 使用 Oracle Scheduler 实现作业自动化 + 使用 crontab 实现作业自动化 ## Oracle Scheduler 这里以定期备份表空间 system 为例。 ### 创建脚本 创建一个 bash 脚本,执行作业的时候会执行这个脚本,以实现备份。 ```bash $ touch /home/oracle/backup_system.sh ``` 输入如下内容: ```bash #!/bin/bash rman target / <<EOF backup tablespace system; EOF exit 0 ``` ### 连接实例 ```bash $ sqlplus system/Syl12345 ``` ### 创建作业 创建作业需要用到 `DBMS_SCHEDULER` 软件包的 `CREATE_JOB` 过程,它需要的参数可以使用 `desc DBMS_SCHEDULER` 查看到,参数详情可以参阅 [DBMS_SCHEDULER](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/arpls/DBMS_SCHEDULER.html#GUID-73622B78-EFF4-4D06-92F5-E358AB2D58F3) 。 下面就创建一个作业,实现在每周的星期五备份表空间 system。 注:下面命令在 SQL 命令行输入 ```plsql BEGIN DBMS_SCHEDULER.CREATE_JOB( job_name => 'BACKUP_SYSTEM', job_type => 'EXECUTABLE', job_action => '/home/oracle/backup_system.sh', repeat_interval => 'FREQ=WEEKLY;BYDAY=FRI;BYHOUR=4', start_date => to_date('04-03-2018','dd-mm-yyyy'), job_class => '"DEFAULT_JOB_CLASS"', auto_drop => FALSE, comments => 'backup system tablespace', enabled => TRUE ); END; / ``` > `=>` 右边的值会传入左边的参数。 参数解释: | 参数 | 说明 | | --------------- | ------------------------------------------------------------ | | job_name | 作业名。 | | job_type | 作业类型。这里是调用的 bash 脚本,所以为 `EXECUTABLE` 。它还有其他值,可以调用 sql 脚本,plsql 语句块等等。 | | job_action | 作业执行的动作。这里是执行 `backup_system.sh` 这个 bash 脚本。 | | repeat_interval | 这里指在每周五早上 4 点执行备份操作。 | | start_date | 开始日期。 | | job_class | 作业类。这里使用的是默认的作业类。 | | auto_drop | 这里设为 FALSE ,表示不会在作业完成后自动删除。 | | comments | 这个作业的描述。 | | enabled | 指示作业是否应在创建后立即启用。这里是立即启用。 | 创建好了作业,我们可以通过如下命令查询到作业: ```sql SQL> select job_name,repeat_interval from dba_scheduler_jobs where job_name='BACKUP_SYSTEM'; ``` ### 查看作业执行的历史记录 作业执行时,会生成一条执行作业的历史记录,我们可以通过如下命令查询: ```sql SQL> select job_name,log_date,operation,status from dba_scheduler_job_log where job_name='BACKUP_SYSTEM'; ``` 日志纪录的默认保留天数是 30 天。这个时间是可以修改,例如把时间修改为 29 天: ```sql SQL> exec dbms_scheduler.set_scheduler_attribute('log_history',29); ``` ### 修改作业 可以调用 `DBMS_SCHEDULER` 包的一些过程实现修改作业,启动,暂停,停止作业等操作。 例一:把作业的执行时间更改为每天一次。 ```plsql exec DBMS_SCHEDULER.set_attribute(- name => 'BACKUP_SYSTEM',- attribute => 'repeat_interval',- value => 'FREQ=DAILY' ); ``` 例二:停止作业。 ```plsql exec DBMS_SCHEDULER.stop_job(job_name='BACKUP_SYSTEM'); ``` > 还有一些其他过程: > > - `enable` :启动作业 > - `disable` :暂停作业 > - `copy_job` :复制作业 > > 不止列举的这些,还有很多其他可调用的过程,可参阅 [DBMS_SCHEDULER](https://docs.oracle.com/en/database/oracle/oracle-database/12.2/arpls/DBMS_SCHEDULER.html#GUID-73622B78-EFF4-4D06-92F5-E358AB2D58F3) 。 ### 删除作业 例如删除我们新建的 `BACKUP_SYSTEM` 这个作业。 ```plsql exec DBMS_SCHEDULER.drop_job(job_name='BACKUP_SYSTEM'); ``` ## crontab `crontab` 命令常见于 Unix 和类 Unix 的操作系统之中(Linux 就属于类 Unix 操作系统),用于设置周期性被执行的指令。它通过守护进程 `cron` 使得任务能够按照固定的时间间隔在后台自动运行。`cron` 利用的是一个被称为 “cron 表”(cron table)的文件,这个文件中存储了需要执行的脚本或命令的调度列表以及执行时间。 当使用者使用 `crontab` 后,该项工作会被记录到`/var/spool/cron/` 里。不同用户执行的任务记录在不同用户的文件中。 通过 `crontab` 命令,我们可以在固定的间隔时间或指定时间执行指定的系统指令或脚本。时间间隔的单位可以是分钟、小时、日、月、周的任意组合。 这里我们看一看 `crontab` 的格式 ```bash # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * command to be executed ``` 其中特殊字符的意义: | 特殊字符 | 意义 | | :------- | :----------------------------------------------------------- | | * | 任何时刻 | | , | 分隔时段,例如`0 7,9 * * * command`代表7:00和9:00 | | - | 时间范围,例如`30 7-9 * * * command` 代表7点到9点之间每小时的30分 | | /n | 每隔n单位间隔,例如`*/10 * * * *` 每10分钟 | ### crontab 准备 `crontab` 在本实验环境中需要做一些特殊的准备,首先我们会启动 `rsyslog`,以便我们可以通过日志中的信息来了解我们的任务是否真正的被执行了(在本实验环境中需要手动启动,而在自己本地中 Ubuntu 会默认自行启动不需要手动启动) ```bash sudo service rsyslog start ``` 在本实验环境中 `crontab` 也是不被默认启动的,同时不能在后台由 `upstart` 来管理,所以需要我们手动启动它(同样在本实验环境中需要手动启动,自己的本地 Ubuntu 的环境中也不需要手动启动) ```bash sudo cron -f & ``` ### crontab 使用 使用 crontab 的基本语法如下: ```bash crontab [-u username] [-l|-e|-r] ``` 其常用的参数有: | 选项 | 意思 | | :--- | :----------------------------------------------------------- | | `-u` | 只有root才能进行这个任务,帮其他使用者创建/移除crontab工作调度 | | `-e` | 编辑crontab工作内容 | | `-l` | 列出crontab工作内容 | | `-r` | 移除所有的crontab工作内容 | 我们这里还是以定期备份表空间为例。首先执行如下命令以添加一个任务计划: ```bash $ crontab -e ``` 第一次启动会出现这样一个画面,这是让我们选择编辑的工具,选择第一个基本的 vim 就可以了 ![实验楼](https://dn-simplecloud.qbox.me/1135081468201990806-wm) 选择后我们会进入一个添加计划的界面,按 `i` 键便可编辑文档,在文档的最后一行加上这样一行命令,实现每周日 9 点执行备份操作。 ```bash 00 09 * * 0 /home/oracle/BACKUP_SYSTEM.sh ``` ![实验楼](https://dn-simplecloud.shiyanlou.com/87971518343930371-wm) 输入完成后按 `esc` 再输入 `:wq` 保存并退出。 添加成功后我们会得到 `installing new crontab` 的一个提示 。 为了确保我们任务添加的正确与否,我们会查看添加的任务详情: ``` $ crontab -l ``` 虽然我们添加了任务,但是如果 `cron` 的守护进程并没有启动,当然也就不会帮我们执行,我们可以通过以下 2 种方式来确定我们的 cron 是否成功的在后台启动,若是没有则需要启动一次。 ```bash $ ps aux | grep cron #或者使用下面 $ pgrep cron ``` 另外,可以通过如下命令查看执行任务命令之后在日志中的信息反馈: ```bash $ sudo tail -f /var/log/syslog ``` 当我们并不需要某个任务的时候我们可以通过 `-e` 参数去配置文件中删除相关命令,若是我们需要清除所有的计划任务,我们可以使用这么一个命令去删除任务: ```bash $ crontab -r ``` ## 总结 ![图片描述](https://dn-simplecloud.shiyanlou.com/uid/8797/1518350221958.png-wm)
C++
UTF-8
1,887
2.96875
3
[]
no_license
#ifndef DVMARCHINGCUBE_H #define DVMARCHINGCUBE_H ///< System header files #include "dvCommon.h" #include "dvMarchingTable.h" #include "dvVolumeData.h" /*! \brief a class for Edge */ class Edge { public: pair<int, int> m_edge[2]; inline Edge &operator =(const Edge &rhs) { m_edge[0] = rhs.m_edge[0]; m_edge[1] = rhs.m_edge[1]; return *this; } }; /*! \brief a class for Point3D */ class DvPoint3D{ public: int x; int y; int z; /* Constructor */ DvPoint3D() { x = 0; y = 0; z = 0; } DvPoint3D( int px, int py, int pz ) { x = px; y = py; z = pz; } /* Operator */ inline DvPoint3D &operator =(const DvPoint3D &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; return *this; } }; //< typedef struct typedef struct { ///< Vertex float P[3]; ///< Position float N[3]; ///< Normal }DvVertex; typedef struct { ///< Face int vIdx[3]; }DvFace; typedef struct { ///< Object vector<DvVertex> VertList; vector<DvFace> FaceList; }DvObject; /*! \brief a class for Marching Cube */ template<class DataType> class DvMarchingCube { public: /* Constructor & Destructor */ DvMarchingCube(); DvMarchingCube(DvVolume<DataType> *pData); virtual ~DvMarchingCube(); /* Member functions */ inline void March(DataType isoVal); inline int GetCubeIndex(DataType isoVal, DvPoint3D pos); inline void FindVertices(DataType isoVal, DvPoint3D pos, int idx); inline DvVertex Lerp(DataType isoVal, DvPoint3D cell1, DvPoint3D cell2, int idx); inline int GetDisplayList(); inline DvVertex GetCenterPosition(); inline void SetData(DataType *pData); inline void SetEdgeTable(); private: /* Member variables */ DvVolume<DataType> *m_Data; DvObject m_VolumeObject; }; #include "dvMarchingCube.inl" #endif // DVMARCHINGCUBE_H
Java
UTF-8
601
3.515625
4
[]
no_license
package Classes; /** * This is for INFSCI 2140 in 2018 */ public class WordNormalizer { public char[] lowercase(char[] chars) { // Transform the word uppercase characters into lowercase. for (int i = 0; i < chars.length; i++) { if (chars[i] <= 'Z' && chars[i] >= 'A') chars[i] += 32; } return chars; } public String stem(char[] chars) { // Return the stemmed word with Stemmer in Classes package. String str = ""; Stemmer stemmer = new Stemmer(); stemmer.add(chars, chars.length); stemmer.stem(); str = stemmer.toString(); return str; } }
PHP
UTF-8
1,558
2.78125
3
[ "MIT" ]
permissive
<?php /** * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ declare(strict_types=1); namespace loophp\collection\Operation; use Closure; use Generator; use Iterator; use loophp\collection\Iterator\IterableIterator; /** * @immutable * * @template TKey * @template T */ final class Flatten extends AbstractOperation { /** * @pure * * @return Closure(int): Closure(Iterator<TKey, T>): Generator<mixed, mixed> */ public function __invoke(): Closure { return /** * @return Closure(Iterator<TKey, T>): Generator<mixed, mixed> */ static fn (int $depth): Closure => /** * @param Iterator<TKey, T> $iterator */ static function (Iterator $iterator) use ($depth): Generator { foreach ($iterator as $key => $value) { if (false === is_iterable($value)) { yield $key => $value; continue; } if (1 !== $depth) { /** @var callable(Iterator<TKey, T>): Generator<mixed, mixed> $flatten */ $flatten = Flatten::of()($depth - 1); $value = $flatten(new IterableIterator($value)); } yield from $value; } }; } }
Java
UTF-8
502
1.953125
2
[]
no_license
// isComment package com.sismics.reader.ui.form.validator; import android.content.Context; import com.sismics.reader.R; /** * isComment */ public class isClassOrIsInterface implements ValidatorType { @Override public boolean isMethod(String isParameter) { return isNameExpr.isMethod().isMethod() != isIntegerConstant; } @Override public String isMethod(Context isParameter) { return isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr); } }
JavaScript
UTF-8
2,486
3.609375
4
[]
no_license
/*350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: ● Each element in the result should appear as many times as it shows in both arrays. ● The result can be in any order. Follow up: ● What if the given array is already sorted? How would you optimize your algorithm? ● What if nums1's size is small compared to num2's size? Which algorithm is better? ● What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? */ /**求两个数组的交集 1. indexOf 或者 lastIndexOf 2. 数组有序,考虑数组大小 * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersect2 = function(nums1, nums2) { var i, index, nums=[], len1=nums1.length; for(i=0;i<len1;i++){ //indexOf:从数组开头往后找元素,如果找到返回index,否则返回-1 index=nums2.indexOf(nums1[i]) if(index!==-1){ nums.push(nums1[i]); nums2.splice(index,1); } } return nums; }; var intersection = function(nums1, nums2) { var i, nums=[], shorter=[]; larger=[]; len1=nums1.length, len2=nums2.length; if(len1>len2){ nums2.sort(compare); shorter=nums2; larger=nums1; }else{ nums1.sort(compare); shorter=nums1; larger=nums2; } len1=larger.length; for(i=0;i<len1;i++){ if(binarySearch(shorter,larger[i])){ nums.push(larger[i]); shorter.splice(shorter.indexOf(larger[i]),1); } } return nums; //二分查找 function binarySearch(nums,target){ if(nums.length===0){ return false; } var left=0, right=nums.length-1, mid=0; while(left<=right){ mid=left+Math.ceil((right-left)/2); if(nums[mid]===target){ return true; } if(nums[mid]>target){ right=mid-1; }else{ left=mid+1; } } return false; } //比较函数,数值升序排序 function compare(a,b){ return a-b; } }; //test var nums1=[61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,47,98,3,41,53,26,66,40,54,44,57,46,70,60,4,63,82,42,65,59,17,98,29,72,1,96,82,66,98,6,92,31,43,81,88,60,10,55,66,82,0,79,11,81], nums2=[5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48]; var a=[1,4,2,3]; var nums=intersection(nums1,nums2); console.log(nums);
PHP
UTF-8
1,092
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\models; use Yii; /** * This is the model class for table "contract_service". * * @property integer $cs_id * @property string $contract_no * @property integer $service_id * @property string $start_time * @property string $end_time * @property integer $status */ class ContractService extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'contract_service'; } /** * @inheritdoc */ public function rules() { return [ [['contract_no', 'service_id'], 'required'], [['service_id', 'status'], 'integer'], [['start_time', 'end_time'], 'safe'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'cs_id' => 'Cs ID', 'contract_no' => 'Contract No', 'service_id' => 'Service ID', 'start_time' => 'Start Time', 'end_time' => 'End Time', 'status' => 'Status', ]; } }
Java
GB18030
375
2.671875
3
[]
no_license
package Singleton; /** * ʽ * ԼʱѾԼʵ ҪǶ̷߳ʵİȫ * */ public class Singleton1 { private static final Singleton1 instance=new Singleton1(); private Singleton1() { // TODO Auto-generated constructor stub } public static Singleton1 GetIntance() { return instance; } }
C#
UTF-8
1,203
2.640625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace FocusFrame { public class Singleton<T> : MonoBehaviour where T : Singleton<T> { protected static T instance; protected static bool isExit = false; public static T GetInstance { get { if (instance == null&&!isExit) { instance = FindObjectOfType<T>(); if (FindObjectsOfType<T>().Length > 1) return instance; if (instance == null) { string name = typeof(T).Name; GameObject go = GameObject.Find(name); if (go == null) { go = new GameObject(name); } instance = go.AddComponent<T>(); } } return instance; } } public virtual void OnDestroy() { instance = null; isExit = true; } } }
Java
UTF-8
697
2.421875
2
[]
no_license
package com.example.am_projekt.variables; public class CurrentLoggedUserData { private static String currentLoggedUsername = "NOT_LOGGED"; private static String currentServerIP = "192.168.0.101"; public static String getCurrentLoggedUsername() { return currentLoggedUsername; } public static void setCurrentLoggedUsername(String currentLoggedUsername) { CurrentLoggedUserData.currentLoggedUsername = currentLoggedUsername; } public static String getCurrentServerIP() { return currentServerIP; } public static void setCurrentServerIP(String currentServerIP) { CurrentLoggedUserData.currentServerIP = currentServerIP; } }
Python
UTF-8
1,491
2.6875
3
[]
no_license
import posixpath from abc import abstractmethod from .cli_context import CliContext from .themes import NoColorTheme class CliCommandBase(object): """base class for a single CCDB CLI command""" #context = ConsoleContext() uses_db = False changes_db = False help_util = False is_alias = False command = "" _context = None def __init__(self, context): assert isinstance(context, CliContext) self.context = context @property def theme(self): return self.context.theme @theme.setter def theme(self, value): self.context.theme = value @abstractmethod def execute(self, args): """Processes the command :parameter args: [] - a List of arguments """ pass def print_help(self): """Prints help of the command""" print(("Help is not defined for command " + self.command)) def print_usage(self): """Prints usage of the command""" print(("@brief Usage is not defined for command " + self.command)) def print_examples(self): """Prints examples of the command usage""" print(("Examples are not defined for command " + self.command)) def read_multiline(self): user_input = [] entry = eval(input("Enter comment text, put 'EOF' on its own line to quit: \n")) while entry != "EOF": user_input.append(entry) entry = eval(input("")) return user_input
C++
UTF-8
6,446
2.59375
3
[ "BSD-2-Clause" ]
permissive
#include "gvio/msckf/blackbox.hpp" namespace gvio { BlackBox::BlackBox() {} BlackBox::~BlackBox() { // Estimation file if (this->est_file.good()) { this->est_file.close(); } // Measurement file if (this->mea_file.good()) { this->est_file.close(); } // Ground truth file if (this->gnd_file.good()) { this->est_file.close(); } // Sliding window file if (this->win_file.good()) { this->win_file.close(); } } int BlackBox::configure(const std::string &output_path, const std::string &base_name) { // Make directory if it does not exist already if (dir_exists(output_path) == false && dir_create(output_path) != 0) { LOG_ERROR("Failed to create directory [%s] for blackbox!", output_path.c_str()); return -1; } // Estimation file this->est_file.open(output_path + "/" + base_name + "_est.dat"); if (this->est_file.good() == false) { LOG_ERROR("Failed to open estimate file for recording [%s]", output_path.c_str()); return -1; } // Measurement file this->mea_file.open(output_path + "/" + base_name + "_mea.dat"); if (this->mea_file.good() == false) { LOG_ERROR("Failed to open measurement file for recording [%s]", output_path.c_str()); return -1; } // Ground truth file this->gnd_file.open(output_path + "/" + base_name + "_gnd.dat"); if (this->gnd_file.good() == false) { LOG_ERROR("Failed to open ground truth file for recording [%s]", output_path.c_str()); return -1; } // Sliding window file this->win_file.open(output_path + "/" + base_name + "_win.dat"); if (this->win_file.good() == false) { LOG_ERROR("Failed to open ground truth file for recording [%s]", output_path.c_str()); return -1; } // Write header // clang-format off const std::string est_header = "t,x,y,z,vx,vy,vz,roll,pitch,yaw"; this->est_file << est_header << std::endl; const std::string mea_header = "t,ax_B,ay_B,az_B,wx_B,wy_B,wz_B"; this->mea_file << mea_header << std::endl; const std::string gnd_header = "t,x,y,z,vx,vy,vz,roll,pitch,yaw"; this->gnd_file << gnd_header << std::endl; const std::string win_header = "x,y,z,roll,pitch,yaw"; this->win_file << win_header << std::endl; // clang-format on return 0; } int BlackBox::recordMSCKF(const double time, const MSCKF &msckf) { // Pre-check if (this->est_file.good() == false) { LOG_ERROR("BlackBox not configured!"); return -1; } // -- Time this->est_file << time << ","; // -- Position this->est_file << msckf.imu_state.p_G(0) << ","; this->est_file << msckf.imu_state.p_G(1) << ","; this->est_file << msckf.imu_state.p_G(2) << ","; // -- Velocity this->est_file << msckf.imu_state.v_G(0) << ","; this->est_file << msckf.imu_state.v_G(1) << ","; this->est_file << msckf.imu_state.v_G(2) << ","; // -- Roll, pitch and yaw const Vec3 rpy_G = quat2euler(msckf.imu_state.q_IG); this->est_file << rpy_G(0) << ","; this->est_file << rpy_G(1) << ","; this->est_file << rpy_G(2) << std::endl; return 0; } int BlackBox::recordEstimate(const double time, const Vec3 &p_G, const Vec3 &v_G, const Vec3 &rpy_G) { // Pre-check if (this->est_file.good() == false) { LOG_ERROR("BlackBox not configured!"); return -1; } // -- Time this->est_file << time << ","; // -- Position this->est_file << p_G(0) << ","; this->est_file << p_G(1) << ","; this->est_file << p_G(2) << ","; // -- Velocity this->est_file << v_G(0) << ","; this->est_file << v_G(1) << ","; this->est_file << v_G(2) << ","; // -- Roll, pitch and yaw this->est_file << rpy_G(0) << ","; this->est_file << rpy_G(1) << ","; this->est_file << rpy_G(2) << std::endl; return 0; } int BlackBox::recordMeasurement(const double time, const Vec3 &a_B, const Vec3 &w_B) { // Pre-check if (this->mea_file.good() == false) { LOG_ERROR("BlackBox not configured!"); return -1; } // -- Time this->mea_file << time << ","; // -- Acceleration this->mea_file << a_B(0) << ","; this->mea_file << a_B(1) << ","; this->mea_file << a_B(2) << ","; // -- Angular velocity this->mea_file << w_B(0) << ","; this->mea_file << w_B(1) << ","; this->mea_file << w_B(2) << std::endl; return 0; } int BlackBox::recordGroundTruth(const double time, const Vec3 &p_G, const Vec3 &v_G, const Vec3 &rpy_G) { // Pre-check if (this->gnd_file.good() == false) { LOG_ERROR("BlackBox not configured!"); return -1; } // -- Time this->gnd_file << time << ","; // -- Position this->gnd_file << p_G(0) << ","; this->gnd_file << p_G(1) << ","; this->gnd_file << p_G(2) << ","; // -- Velocity this->gnd_file << v_G(0) << ","; this->gnd_file << v_G(1) << ","; this->gnd_file << v_G(2) << ","; // -- Roll, pitch and yaw this->gnd_file << rpy_G(0) << ","; this->gnd_file << rpy_G(1) << ","; this->gnd_file << rpy_G(2) << std::endl; return 0; } int BlackBox::recordCameraStates(const MSCKF &msckf) { // Pre-check if (this->win_file.good() == false) { LOG_ERROR("BlackBox not configured!"); return -1; } for (auto cam_state : msckf.cam_states) { // -- Position this->win_file << cam_state.p_G(0) << ","; this->win_file << cam_state.p_G(1) << ","; this->win_file << cam_state.p_G(2) << ","; // -- Roll, pitch and yaw const Vec3 rpy_G = quat2euler(msckf.imu_state.q_IG); this->win_file << rpy_G(0) << ","; this->win_file << rpy_G(1) << ","; this->win_file << rpy_G(2) << std::endl; } return 0; } int BlackBox::recordTimeStep(const double time, const MSCKF &msckf, const Vec3 &mea_a_B, const Vec3 &mea_w_B, const Vec3 &gnd_p_G, const Vec3 &gnd_v_G, const Vec3 &gnd_rpy_G) { // Estimated this->recordMSCKF(time, msckf); // Measurements this->recordMeasurement(time, mea_a_B, mea_w_B); // Ground truth this->recordGroundTruth(time, gnd_p_G, gnd_v_G, gnd_rpy_G); return 0; } } // namespace gvio
Markdown
UTF-8
1,253
3.359375
3
[]
no_license
# oc-genblog overcodes tool to generate a static blog. # Example Write your blog post: politics-are-overrated.md ``` <!-- @template "blog-post.html" --> # Politics are overrated Politics are overrated, but discussion is a necesary evil to ensure we fight the creep of authoritative government. ``` Generate the post: ``` oc-genblog politics-are-overrated.md > politics-are-overrated.html ``` # Templates The key to making this more than just a Markdown to HTML convert is the use of templates that have plugins; for example, we can write an HTML template that uses one of the default templates to populate the last-modified date. blog-post.html.template ``` <html> <body> <h1>{{ attributes(key="title") }} <small>last-updated {{ last_modified() }}</small></h1> {{ content() }} </body> </html> ``` The templates are powered by Tera, and you can use of the features provided by that template language. We define some context objects which can be used: - attribute(key="some key") -- used to fetch an attribute specified in the markdown file; for example, 'template' above - content() -- fetches the HTML representation of the Markdown file - last_modified() -- gets the last-modified timestamp from the file in question
Markdown
UTF-8
1,102
3.578125
4
[]
no_license
### 解题思路 直接看代码就能理解 ```java /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { //默认第一节点不为空 //计算2个线性表第一个节点值的和 int a = l1.val + l2.val; //判断是否有进位 int b = a/10; ListNode head = new ListNode(a % 10); ListNode current = head; ListNode n1 = l1.next; ListNode n2 = l2.next; while (null != n1 || null != n2) { a = null == n1 ? b : n1.val + b; a = null == n2 ? a : n2.val + a; current.next = new ListNode(a % 10); current = current.next; b = a / 10; n1 = null == n1 ? null : n1.next; n2 = null == n2 ? null : n2.next; } //有进位的话则增加一个节点 if (b > 0) { current.next = new ListNode(1); } return head; } } ```
Java
UTF-8
987
2.78125
3
[]
no_license
package org.softlang.megal.util; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newLinkedList; import java.util.Deque; import java.util.List; import java.util.ListIterator; import com.google.common.collect.AbstractIterator; public abstract class PostOrderDeepeningIterator<E> extends AbstractIterator<E> { private final List<E> tier; private final Deque<E> sequence; public PostOrderDeepeningIterator(Iterable<? extends E> initial) { tier = newArrayList(initial); sequence = newLinkedList(initial); } protected abstract Iterable<? extends E> getNext(E e); @Override protected E computeNext() { if (!sequence.isEmpty()) return sequence.poll(); for (ListIterator<E> it = tier.listIterator(); it.hasNext();) { E v = it.next(); it.remove(); for (E s : getNext(v)) { it.add(s); sequence.offer(s); } } if (sequence.isEmpty()) return endOfData(); return sequence.poll(); } }
Python
UTF-8
1,419
2.703125
3
[]
no_license
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() def __str__(self): return self.name, self.age class Publisher(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) pubdate = models.DateField() def __str__(self): return self.name def display_authors(self): """ Creates a string for the Genre. This is required to display genre in Admin. """ return ', '.join([genre.name for genre in self.authors.all()[:3]]) display_authors.short_description = 'Authors' class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) def __str__(self): return self.name, self.books def display_books(self): """ Creates a string for the Books. This is required to display Books in Admin. """ return ', '.join([genre.name for genre in self.books.all()[:3]]) display_books.short_description = 'Books'
Python
UTF-8
1,196
2.921875
3
[]
no_license
# -*- coding:utf-8 -*- class Container(object): __shield_list = [] # 顺序遍历 __separate_list = [] # 顺序遍历 __output_list = [] # 顺序遍历 __process_list = [] # 非并发,顺序遍历, 多择其一 def set_shield(self, shield_cls): self.__shield_list.append(shield_cls) def set_separate(self, separate_cls): self.__separate_list.append(separate_cls) def set_output(self, output_cls): self.__output_list.append(output_cls) def set_process(self, process_cls): self.__process_list.append(process_cls) def shield_perform(self, warning_dict): for c in self.__shield_list: if not c.shield(warning_dict): return False return True def separate_perform(self, warning_dict): for c in self.__separate_list: c.separate(warning_dict) return warning_dict def output_perform(self, warning_dict): for c in self.__output_list: c.output(warning_dict) def process_perform(self, warning_dict): for c in self.__process_list: res = c.process(warning_dict) if res: break
Java
UTF-8
1,928
2.75
3
[ "MIT" ]
permissive
package seedu.address.testutil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.address.model.reminders.ReadOnlyReminder; import seedu.address.model.reminders.UniqueReminderList; import seedu.address.storage.XmlSerializableReminders; //@@author justinpoh /** * A utility class containing a list of {@code Reminder} objects to be used in tests. */ public class TypicalReminders { public static final ReadOnlyReminder COFFEE_REMINDER = new ReminderBuilder().build(); public static final ReadOnlyReminder HOMEWORK_REMINDER = new ReminderBuilder().withReminder("Do homework") .withDate("01/01/2018").withTime("07:30").build(); public static final ReadOnlyReminder DINNER_REMINDER = new ReminderBuilder().withReminder("Dinner with family") .withDate("25/12/2017").withTime("18:00").build(); // Manually added public static final ReadOnlyReminder MEETING_REMINDER = new ReminderBuilder().withReminder("Meet with CS2103 group") .withDate("09/09/2017").withTime("12:00").build(); public static final ReadOnlyReminder DENTIST_REMINDER = new ReminderBuilder().withReminder("Go for dental checkup") .withDate("10/10/2017").withTime("14:00").build(); private TypicalReminders() {} //prevents instantiation public static List<ReadOnlyReminder> getTypicalReminders() { return new ArrayList<>(Arrays.asList(COFFEE_REMINDER, HOMEWORK_REMINDER, DINNER_REMINDER)); } /** * Utility method to return a UniqueReminderList containing a list of {@code Reminder} objects * to be used in tests. */ public static UniqueReminderList getUniqueTypicalReminders() { return new UniqueReminderList(new XmlSerializableReminders(getTypicalReminders())); } }
JavaScript
UTF-8
2,037
2.796875
3
[ "MIT" ]
permissive
import auditors from './auditors'; import * as Err from './err'; import prop from './prop'; /** * @public * @param {*} value Checked value * @param {function|string} naming Name on error (string or function that returns a string) * @param {function(*):boolean} auditor Checking function. The name of this function must be meaningful and understandable * because it is used in the error message. Additional information provided in the * "info" property is also used */ export const audit = (value, naming, auditor) => { if (!auditor(value)) { throw Err.setup(new TypeError(Err.makeMessage(naming, {name:auditor.name, ...auditor.info}, value)), 1); } }; /** * Set of auditing methods * @public * @type {object} */ const TypeAudit = { /** * @public * @type {TypeAudit.is} */ is: auditors, /** * @public * @type {TypeAudit.prop} */ prop: prop }; Object.getOwnPropertyNames(auditors).forEach((method) => { const getAuditor = auditors[method]; TypeAudit[method] = 1 < getAuditor.length /** * @public * @param {*} value Checked value * @param {string|function} typeInfo Info about type or class of checked value * @param {function|string} naming Name on error (string or function that returns a string) * @param {boolean} [isRequired] Values null and undefined are not allowed (optional) */ ? (value, typeInfo, naming, isRequired) => audit(value, naming, getAuditor(typeInfo, isRequired)) /** * @public * @param {*} value Checked value * @param {function|string} naming Name on error (string or function that returns a string) * @param {boolean} [isRequired] Values null and undefined are not allowed (optional) */ : (value, naming, isRequired) => audit(value, naming, getAuditor(isRequired)); }); Object.freeze(TypeAudit); export default TypeAudit;
PHP
UTF-8
2,607
2.625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\modules\api\controllers; use app\models\Tweet; use Yii; use yii\rest\Controller; use app\models\User; /** * Default controller for the `api` module */ class DefaultController extends Controller { /** * Renders the index view for the module * @return string */ public function actionAdd() { $params = Yii::$app->request->get(); if (!isset($params['id'], $params['secret'], $params['user'])) { Yii::$app->response->setStatusCode(400); return [ 'errors' => 'missing parameter' ]; } else if(sha1($params['id'] . $params['user']) !== $params['secret']) { Yii::$app->response->setStatusCode(400); return [ 'errors' => 'access denied' ]; } $user = new User(); $user->username = $params['user']; $user->hash = $params['id']; if(!$user->save()) { Yii::$app->response->setStatusCode(500); return [ 'errors' => 'internal error' ]; } return; } public function actionFeed() { $params = Yii::$app->request->get(); if (!isset($params['id'], $params['secret'])) { Yii::$app->response->setStatusCode(400); return [ 'errors' => 'missing parameter' ]; } else if(sha1($params['id']) !== $params['secret']) { Yii::$app->response->setStatusCode(400); return [ 'errors' => 'access denied' ]; } $tweets = Tweet::findLast(); if(empty($tweets)) { return; } return [ 'feed' => $tweets ]; } public function actionRemove() { $params = Yii::$app->request->get(); if (!isset($params['id'], $params['secret'], $params['user'])) { Yii::$app->response->setStatusCode(400); return [ 'errors' => 'missing parameter' ]; } else if(sha1($params['id'] . $params['user']) !== $params['secret']) { Yii::$app->response->setStatusCode(400); return [ 'errors' => 'access denied' ]; } $user = User::findByUsername($params['user']); if($user === null || !$user->delete()) { Yii::$app->response->setStatusCode(500); return [ 'errors' => 'internal error' ]; } return; } }
C++
UTF-8
3,075
2.6875
3
[ "BSD-3-Clause", "LGPL-2.0-or-later", "Apache-2.0", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Definitions for the Interchange File Format (IFF) // Alexander Gessler, 2006 // Adapted to Assimp August 2008 #ifndef AI_IFF_H_INCLUDED #define AI_IFF_H_INCLUDED #include <assimp/ByteSwapper.h> namespace Assimp { namespace IFF { ///////////////////////////////////////////////////////////////////////////////// //! Describes an IFF chunk header ///////////////////////////////////////////////////////////////////////////////// struct ChunkHeader { //! Type of the chunk header - FourCC uint32_t type; //! Length of the chunk data, in bytes uint32_t length; }; ///////////////////////////////////////////////////////////////////////////////// //! Describes an IFF sub chunk header ///////////////////////////////////////////////////////////////////////////////// struct SubChunkHeader { //! Type of the chunk header - FourCC uint32_t type; //! Length of the chunk data, in bytes uint16_t length; }; #define AI_IFF_FOURCC(a,b,c,d) ((uint32_t) (((uint8_t)a << 24u) | \ ((uint8_t)b << 16u) | ((uint8_t)c << 8u) | ((uint8_t)d))) #define AI_IFF_FOURCC_FORM AI_IFF_FOURCC('F','O','R','M') ///////////////////////////////////////////////////////////////////////////////// //! Load a chunk header //! @param outFile Pointer to the file data - points to the chunk data afterwards //! @return Copy of the chunk header ///////////////////////////////////////////////////////////////////////////////// inline ChunkHeader LoadChunk(uint8_t*& outFile) { ChunkHeader head; ::memcpy(&head.type, outFile, 4); outFile += 4; ::memcpy(&head.length, outFile, 4); outFile += 4; AI_LSWAP4(head.length); AI_LSWAP4(head.type); return head; } ///////////////////////////////////////////////////////////////////////////////// //! Load a sub chunk header //! @param outFile Pointer to the file data - points to the chunk data afterwards //! @return Copy of the sub chunk header ///////////////////////////////////////////////////////////////////////////////// inline SubChunkHeader LoadSubChunk(uint8_t*& outFile) { SubChunkHeader head; ::memcpy(&head.type, outFile, 4); outFile += 4; ::memcpy(&head.length, outFile, 2); outFile += 2; AI_LSWAP2(head.length); AI_LSWAP4(head.type); return head; } ///////////////////////////////////////////////////////////////////////////////// //! Read the file header and return the type of the file and its size //! @param outFile Pointer to the file data. The buffer must at //! least be 12 bytes large. //! @param fileType Receives the type of the file //! @return 0 if everything was OK, otherwise an error message ///////////////////////////////////////////////////////////////////////////////// inline const char* ReadHeader(uint8_t* outFile, uint32_t& fileType) { ChunkHeader head = LoadChunk(outFile); if(AI_IFF_FOURCC_FORM != head.type) { return "The file is not an IFF file: FORM chunk is missing"; } ::memcpy(&fileType, outFile, 4); AI_LSWAP4(fileType); return 0; } }} #endif // !! AI_IFF_H_INCLUDED
Markdown
UTF-8
5,080
2.828125
3
[]
no_license
# express-winston Appsynth's Winston logger Express middleware. ## Features - Redacts sensitive information automatically (token, password, credit card...) - Optionally allows you to log request and response body for specific routes - A unique request ID is assigned to each request that has multiple logs - The generated unique request Id can also act as a correlation id for outgoing requests (`res.locals.requestId`) - Logs user information if data is attached to the context (`res.locals.user`) ## Usage ### Installation ``` npm i @appsynth-org/express-winston --save ``` ### Quick Start ```javascript const logger = require('@appsynth-org/express-winston'); app.use(logger()); ``` Request log will look like: ```json { "requestId": "ckagm39qh0000ek1gc108gz7d", "req": { "headers": { "host": "localhost:3000", "connection": "keep-alive", "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "accept": "*/*", "accept-encoding": "gzip, deflate, br", "cache-control": "no-cache" }, "path": "/login", "method": "POST", "ip": "::1" }, "res": { "type": "application/json", "statusCode": 200, "headers": { "content-length": "16", "content-type": "application/json; charset=utf-8" } }, "responseTime": 8, "level": "info", "message": "request success for POST /login" } ``` ## Configuration ```javascript app.use( logger({ transports: [new winston.transports.Console()], level: 'info', logReqBody: false, logReqBodyOnly: [], logReqBodyExcept: [], logResBody: false, logResBodyOnly: [], logResBodyExcept: [], }) ); ``` ## Examples ### NOTE: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while ussing CommonJS imports with `require()`, use the following approach: ```javascript const logger = require('@appsynth-org/express-winston').default; ``` ### Correlation ID This logging library assigns a unique id to each request and its value is accessible through `res.locals.requestId`. The unique id is generated in either of these two ways: 1. The `res.locals.requestId` will use the value of the `x-correlation-id` header of the incoming request. 2. If `x-correlation-id` doesn't exist in incoming request header, it will generate on its own using `cuid`. You can use the value of `res.locals.requestId` as the `x-correlation-id` request header for your outgoing request as such: ```javascript app.use(async (req, res) => { const response = await axios.get('http://localhost:3000', { headers: { 'x-correlation-id': res.locals.requestId, }, }); }); ``` This way, the service who sent the request and the service who is receiving the request will have the same `requestId` in the log. ### Specifying logging transports ```javascript const { LoggingWinston } = require('@google-cloud/logging-winston'); app.use( logger({ transports: [ new LoggingWinston({ projectId: 'gcp-project-id', keyFilename: 'account-service.json', logName: 'appsynth-express-winston', serviceContext: { service: 'appsynth-express-winston', version: 'v1.0.0', }, }), ], }) ); ``` ### Logging all request and response bodies ```javascript app.use( logger({ logResBody: true, }) ); ``` ### Logging all request and response bodies ONLY for specific routes ```javascript app.use({ logger({ logReqBody: true, logReqBodyOnly: [ '/register', '/login' ], logResBody: true, logResBodyOnly: [ '/register', '/login' ] }) }) ``` ### Logging all request and response bodies EXCEPT for specific routes ```javascript app.use({ logger({ logReqBody: true, logReqBodyExcept: [ '/register', '/login' ], logResBody: true, logResBodyExcept: [ '/register', '/login' ] }) }) ``` > **Note**: If `logResBodyOnly` and/or `logReqBodyOnly` has been specified, `logReqBodyExcept` and/or `logResBodyExcept` will be ignored ### Adding extra logs to your router ```javascript async (req, res) => { res.locals.logger.info('Request received'); res.send('Cool!) }; ``` ### Skipping logs ```javascript app.use( logger({ skip: (req, res) => { return req.headers['user-agent'] && req.headers['user-agent'].includes('kube-probe'); }, }) ); ``` ## Contributing - If you're unsure if a feature would make a good addition, you can always [create an issue](https://bitbucket.org/appsynth/express-winston/issues/new) first. Raising an issue before creating a pull request is recommended. - We aim for 100% test coverage. Please write tests for any new functionality or changes. - Any API changes should be fully documented. - Make sure your code meets our linting standards. Run `npm run lint` to check your code. - Maintain the existing coding style. - Be mindful of others when making suggestions and/or code reviewing.
Python
UTF-8
2,804
2.953125
3
[]
no_license
import re def get_descriptor(filepath,regex,name): """ Helper function to build requests :param filepath: path to logfile :param regex: Regular expression (as a raw string) used to locate the descriptor :param name: String containing name of parameters in case not found :return: float zero point descriptor if found. False if nothing found """ with open(filepath, "r") as file: file_data = file.readlines() pattern = re.compile(regex) for line in file_data: m = pattern.search(line) if m: # match found # print(line) # print(m) # print(m[1]) # print(float(m[1])) return float(m[1]) print(name+" not found!") return False def get_phosphine_phosphorus_number(filename): """ returns gaussian atom id for the phosphorus atom. Assumes that the central phoshine phosphorus is the only P in the molecule, or that it at least appears before any others. """ return str(int(get_descriptor(filename, r' (\d+) P .*?', # r' (.*) P.*?', "phosphorus id number"))) def get_phosphine_atom_numbers(filename, phosid): """ returns array of gaussian atom ID's for the 3 atoms attached to phosphorus. """ return [str(int(get_descriptor(filename, # atom 1 r' ! R1 R\({},(\d+)\).*?'.format(phosid), "atom 1 id number"))), str(int(get_descriptor(filename, # atom 2 r' ! R2 R\({},(\d+)\).*?'.format(phosid), "atom 2 id number"))), str(int(get_descriptor(filename, # atom 3 r' ! R3 R\({},(\d+)\).*?'.format(phosid), "atom 3 id number")))] def truncate_to(filename,regex,outfilename): with open(filename) as file: filedata = file.readlines() pattern = re.compile(regex) idx = 0 begin = 0 for line in filedata: m = pattern.search(line) if m: begin = idx break else: idx = idx + 1 with open(filename.replace(".log","") + "_{}.log".format(outfilename),'w') as file: file.writelines(filedata[(begin+1):]) return filename.replace(".log","") + "_{}.log".format(outfilename) def truncate_pre_optimized(filename): """ trims part of file which includes pre-optimized values """ return truncate_to(filename,r'Optimization complete.',"opt") def truncate_to_mulliken(filename): """ trims part of file which includes pre-optimized values and location matrix """ return truncate_to(filename,r'Mulliken charges:',"mul") def truncate_to_APT(filename): """ trims part of file which includes pre-optimized values and location matrix """ return truncate_to(filename,r' APT charges:',"APT")
Rust
UTF-8
394
2.671875
3
[ "CC0-1.0" ]
permissive
use crate::types; pub fn parse(input: &str) -> types::Data { let mut result = types::Data::default(); for line in input.lines() { let block: Vec<u8> = line.chars().map(|x| x as u8 - b'0').collect(); if result.height == 0 { result.width = block.len(); } result.data.extend(block); result.height += 1; } result }
Java
UTF-8
512
2.609375
3
[ "Apache-2.0" ]
permissive
package se.thinkcode.ctd; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TodoList { Map<String, List<String>> tasks = new HashMap<>(); public void addTask(String owner, String task) { List<String> currentTasks = tasks.getOrDefault(owner, new ArrayList<>()); currentTasks.add(task); tasks.put(owner, currentTasks); } public List<String> getTasks(String owner) { return tasks.get(owner); } }
Ruby
UTF-8
424
3.609375
4
[]
no_license
class Person # class << self # def count # @count ||= 0 # end # end # atalho para criacao de metodo na classe Singleton do objeto Person def self.count @count ||= 0 end def self.count=(increment) @count = increment end def initialize(name) @name = name self.class.count += 1 end def name @name end end john = Person.new("John Doe") puts john.name puts Person.count
C++
UTF-8
425
2.859375
3
[]
no_license
const int N = 1e5 + 5; int dsu[N]; // negative and equals to -size if root, parent if non-root int trace(int u) { return dsu[u] < 0 ? u : dsu[u] = trace(dsu[u]); } bool connect(int u, int v) { if ((u = trace(u)) == (v = trace(v))) { return false; } if (dsu[u] > dsu[v]) { swap(u, v); } dsu[u] += dsu[v]; dsu[v] = u; return true; } int main() { fill(dsu, dsu + N, -1); }
Python
UTF-8
1,130
2.921875
3
[ "MIT" ]
permissive
import pytz import unittest from datetime import datetime, timezone from identidoc.services import get_current_time_as_POSIX_timestamp, datetime_to_POSIX_timestamp class TestMiscFunctions(unittest.TestCase): # This test is going to be very hard to "test" def test_get_current_time_as_POSIX_timestamp(self): current_time = datetime.now(tz=timezone.utc) current_time_test = get_current_time_as_POSIX_timestamp() current_time_timestamp = int(current_time.timestamp()) assert isinstance(current_time_test, int) # Just assert that the difference is less than 3 seconds assert abs(current_time_test - current_time_timestamp) < 3 def test_datetime_to_POSIX_timestamp(self): current_time = datetime.now(tz=timezone.utc) utc_timestamp = datetime_to_POSIX_timestamp(current_time) for tz in pytz.all_timezones: different_timezone = current_time.astimezone(pytz.timezone(tz)) different_timezone_timestamp = datetime_to_POSIX_timestamp(different_timezone) assert utc_timestamp == different_timezone_timestamp
Python
UTF-8
1,965
4.1875
4
[]
no_license
#Simple implementation of a binary tree and the 3 different traversals import unittest class Node: def __init__(self, value): self.value = value self.left = None self.right = None #Prints the left child, parent and then right child. #In a binary tree, this prints in ascending order def inOrderTraversal(node, list): if node: inOrderTraversal(node.left, list) list.append(node.value) inOrderTraversal(node.right, list) return list #Prints the parent, left and then right child. def preOrderTraversal(node, list): if node: list.append(node.value) preOrderTraversal(node.left, list) preOrderTraversal(node.right, list) return list #Prints the left and right children and then parent node. def postOrderTraversal(node, list): if node: postOrderTraversal(node.left, list) postOrderTraversal(node.right, list) list.append(node.value) return list root = Node(1) fullTree = Node(2) fullTree.left = Node(1) fullTree.right = Node(3) leftChild = Node(2) leftChild.left = Node(1) rightChild = Node(2) rightChild.right = Node(3) class Test(unittest.TestCase): def test_inOrder_traversal(self): self.assertEqual(inOrderTraversal(root, []), [1]) self.assertEqual(inOrderTraversal(leftChild, []), [1, 2]) self.assertEqual(inOrderTraversal(rightChild, []), [2, 3]) self.assertEqual(inOrderTraversal(fullTree, []), [1, 2, 3]) def test_preOrder_traversal(self): self.assertEqual(preOrderTraversal(root, []), [1]) self.assertEqual(preOrderTraversal(leftChild, []), [2, 1]) self.assertEqual(preOrderTraversal(rightChild, []), [2, 3]) self.assertEqual(preOrderTraversal(fullTree, []), [2, 1 , 3]) def test_postOrder_traversal(self): self.assertEqual(postOrderTraversal(root, []), [1]) self.assertEqual(postOrderTraversal(leftChild, []), [1, 2]) self.assertEqual(postOrderTraversal(rightChild, []), [3, 2]) self.assertEqual(postOrderTraversal(fullTree, []), [1, 3 , 2]) if __name__ == "__main__": unittest.main()
Java
UTF-8
1,580
2.078125
2
[]
no_license
package com.abhishekmaurya.abhivyakti2k15; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * Created by ABHISHEK MAURYA on 24-01-2015. */ public class ComperingCell extends Activity { Button compab, compmem, compcont; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.comperingcell); compab = (Button) findViewById(R.id.comperabout); compmem = (Button) findViewById(R.id.compermem); compcont = (Button) findViewById(R.id.compercont); compab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent openComperAbout = new Intent("com.Abhivyakti2k15.abhishekmaurya.ComperingAbout"); startActivity(openComperAbout); } }); compmem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent openComperMem = new Intent("com.Abhivyakti2k15.abhishekmaurya.ComperingMem"); startActivity(openComperMem); } }); compcont.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent openComperCon = new Intent("com.Abhivyakti2k15.abhishekmaurya.ContactsCompering"); startActivity(openComperCon); } }); } }
JavaScript
UTF-8
5,549
2.5625
3
[ "Apache-2.0" ]
permissive
// FIXME Line numbers are not aligned to correspondent text line // https://trello.com/c/hdZGr9EA/684 describe.skip("ep_script_page_view - height of line numbers", function() { // Letter // var PAPER_SZE = 'Letter'; // var GENERALS_PER_PAGE = 54; // A4 var PAPER_SZE = 'A4'; var GENERALS_PER_PAGE = 58; var utils; before(function(){ utils = ep_script_page_view_test_helper.utils; }); beforeEach(function(done){ var simplePageViewUtils = ep_script_simple_page_view_test_helper.utils; simplePageViewUtils.newPadWithPaperSize(function() { utils.cleanPad(done); }, PAPER_SZE); this.timeout(60000); }); context("when pad has a non-split page break without MORE-CONTD", function() { beforeEach(function(done) { this.timeout(4000); // build script with one line on second page var script = utils.buildScriptWithGenerals("general", GENERALS_PER_PAGE+1); utils.createScriptWith(script, "general", function() { // wait for pagination to finish before start testing helper.waitFor(function() { var $linesWithPageBreaks = utils.linesAfterNonSplitPageBreaks(); return $linesWithPageBreaks.length > 0; }, 2000).done(done); }); }); it("displays number of first line of next page on the top of its text", function(done) { var firstLineOfSecondPage = GENERALS_PER_PAGE+1; utils.testLineNumberIsOnTheSamePositionOfItsLineText(firstLineOfSecondPage, this, done); }); }); context("when pad has a non-split page break with MORE-CONTD", function() { beforeEach(function(done) { this.timeout(4000); // build script with character => dialogue on first page, and parenthetical => dialogue // on second page (to have MORE/CONT'D) var lastLineText = "last dialogue"; var fullLine = utils.buildStringWithLength(23, "1") + ". "; // 2-line parenthetical var parentheticalText = fullLine + fullLine; var pageFullOfGenerals = utils.buildScriptWithGenerals("general", GENERALS_PER_PAGE - 4); var character = utils.character("character"); var dialogueOfPreviousPage = utils.dialogue("a very very very very very long dialogue"); var parentheticalOfNextPage = utils.parenthetical(parentheticalText); var dialogueOfNextPage = utils.dialogue(lastLineText); var script = pageFullOfGenerals + character + dialogueOfPreviousPage + parentheticalOfNextPage + dialogueOfNextPage; utils.createScriptWith(script, lastLineText, function() { // wait for pagination to finish before start testing helper.waitFor(function() { var $linesWithPageBreaks = utils.linesAfterNonSplitPageBreaks(); return $linesWithPageBreaks.length > 0; }, 2000).done(done); }); }); it("displays number of first line of next page on the top of its text", function(done) { var firstLineOfSecondPage = GENERALS_PER_PAGE-1; utils.testLineNumberIsOnTheSamePositionOfItsLineText(firstLineOfSecondPage, this, done); }); }); context("when pad has a split page break without MORE-CONTD", function() { beforeEach(function(done) { this.timeout(4000); // build script with last line split between pages var lastLineText = "last line"; var fullLine = utils.buildStringWithLength(59, "1") + ". "; var pageFullOfGenerals = utils.buildScriptWithGenerals("general", GENERALS_PER_PAGE-1); var splitGeneral = utils.general(fullLine + fullLine); var lastLine = utils.general(lastLineText); var script = pageFullOfGenerals + splitGeneral + lastLine; utils.createScriptWith(script, lastLineText, function() { // wait for pagination to finish before start testing helper.waitFor(function() { var $linesWithPageBreaks = utils.linesAfterSplitPageBreaks(); return $linesWithPageBreaks.length > 0; }, 2000).done(done); }); }); it("displays number of first line of next page on the top of its text", function(done) { var firstLineOfSecondPage = GENERALS_PER_PAGE+1; utils.testLineNumberIsOnTheSamePositionOfItsLineText(firstLineOfSecondPage, this, done); }); }); context("when pad has a split page break with MORE-CONTD", function() { beforeEach(function(done) { this.timeout(4000); // build script with very long parenthetical at the end of first page var lastLineText = "last line"; var fullLine = utils.buildStringWithLength(23, "1") + ". "; // 4-line parenthetical (to be split) var parentheticalText = fullLine + fullLine + fullLine + fullLine; var pageFullOfGenerals = utils.buildScriptWithGenerals("general", GENERALS_PER_PAGE - 3); var longParenthetical = utils.parenthetical(parentheticalText); var lastLine = utils.general(lastLineText); var script = pageFullOfGenerals + longParenthetical + lastLine; utils.createScriptWith(script, lastLineText, function() { // wait for pagination to finish before start testing helper.waitFor(function() { var $linesWithPageBreaks = utils.linesAfterSplitPageBreaks(); return $linesWithPageBreaks.length > 0; }, 2000).done(done); }); }); it("displays number of first line of next page on the top of its text", function(done) { var firstLineOfSecondPage = GENERALS_PER_PAGE-2; utils.testLineNumberIsOnTheSamePositionOfItsLineText(firstLineOfSecondPage, this, done); }); }); });