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
Markdown
UTF-8
2,726
3.375
3
[]
no_license
# AFlexView **Extends** [`AComponent`](AComponent.html#acomponent) 뷰(View1)를 유동적으로 생성하는 컴포넌트 <br/> ## Properties ### views \<[AView](AView.html#aview) Array> 화면을 구성하기 위해 구분된 뷰(AView)들을 저장한 배열 <br/> ### viewDirection \<String> 화면의 뷰들을 위치 시키는 방향을 저장한 변수. 값은 row, colum <br/> <br/> ## Class Methods <br/> <br/> ## Instance Methods ### getView( index ) index 순번에 해당하는 뷰를 반환한다. - `index` \<Number> 순번 - **Returns** \<[AView](AView.html#aview)> 뷰 객체 ```js // FlexView ID : flexView 일경우 // 뷰가 2개 추가 됨. view01.lay, view02.lay this.flexView.setViewDirection('row'); this.flexView.insertView('Source/view01.lay'); this.flexView.insertView('Source/view02.lay'); console.log(this.flexView.getView(0)); ------------------------------------------------------- view01 {element: ... } ``` <br/> ### insertView( view, index ) index 번째 뷰 앞에 view를 추가한다. - `view` \<[AView](AView.html#aview) or String> 뷰 객체 또는 뷰 Url - `index` \<Number> 추가할 뷰의 기준 순번 ```js // FlexView ID : flexView 일경우 // 뷰가 2개 추가 됨. view01.lay, view02.lay this.flexView.setViewDirection('row'); this.flexView.insertView('Source/view01.lay'); this.flexView.insertView('Source/view02.lay'); console.log(this.flexView.getView(1)); // 순번이 1인 뷰 this.flexView.insertView('Source/view03.lay', 1); // 순번이 1인 뷰 앞에 추가 console.log(this.flexView.getView(1)); // 순번이 1인 뷰 ------------------------------------------------------- view02 {element: ... } view03 {element: ... } ``` <br/> ### removeAllViews() FlexView 컴포넌트 내 모든 뷰를 삭제한다. ```js // FlexView ID : flexView 일경우 // 뷰가 2개 추가 됨. view01.lay, view02.lay, view03.lay this.flexView.setViewDirection('row'); this.flexView.insertView('Source/view01.lay'); this.flexView.insertView('Source/view02.lay'); this.flexView.insertView('Source/view03.lay'); console.log(this.flexView.views.length); this.flexView.removeAllViews(); // 모두 삭제 console.log(this.flexView.views.length); ------------------------------------------------------- 3 0 ``` <br/> ### setViewDirection( direction ) 뷰의 정렬 방향을 설정한다. - `direction` \<String> row : 행, column : 열 ```js // FlexView ID : flexView 일경우 // 뷰가 2개 추가 됨. view01.lay, view02.lay, view03.lay this.flexView.setViewDirection('row'); console.log(this.flexView.viewDirection); ------------------------------------------------------- row ``` <br/> <br/>
C++
UTF-8
1,382
2.65625
3
[]
no_license
#include "Player/Skill/SkillManager.h" using namespace Logic; SkillManager::SkillManager() { m_currentSkill = nullptr; } SkillManager::~SkillManager() { m_currentSkill = nullptr; clear(); } void SkillManager::clear() { for (int i = 0; i < m_allSkills.size(); i++) delete m_allSkills[i]; m_allSkills.clear(); } void SkillManager::init(ProjectileManager* projectileManager, GameTime* gameTime) { m_allSkills = { { /*new SkillBulletTime(BULLET_TIME_CD, gameTime)*/ new SkillBulletTime(projectileManager, ProjectileData(0, 1, 1, 100, 0, BULLET_TIME_DURATION, Graphics::ModelID::SPHERE, 1, ProjectileType::ProjectileTypeBulletTime)) }, { new SkillGrapplingHook(projectileManager, ProjectileData(0, 1, 1, 500, 0, 2000, Graphics::ModelID::SPHERE, 1, ProjectileType::ProjectileTypeGrappling)) }, { new SkillShieldCharge(projectileManager, ProjectileData(0, 1, 0, 0, 0, 3000, Graphics::ModelID::CUBE, 1, ProjectileType::ProjectileTypeShield)) } }; switchToSkill(1); } void SkillManager::switchToSkill(int index) { m_currentSkill = m_allSkills[index]; } void SkillManager::useSkill(btVector3 forward, Entity& shooter) { if (m_currentSkill) m_currentSkill->use(forward, shooter); } void SkillManager::update(float deltaTime) { m_currentSkill->update(deltaTime); } void SkillManager::render(Graphics::Renderer& renderer) { m_currentSkill->render(renderer); }
C++
UTF-8
2,108
2.65625
3
[]
no_license
/* AS5045_scorpion.h - Library for 2 encoders as odometry Created by Aaron Chong, Feb 2018 minebot, Team B, MRSD 2018 */ #ifndef AS5045_SCORPION_h #define AS5045_SCORPION_h #include "Arduino.h" class scorpion_wheels { public: //if reverse is true, it probably means its the right wheel scorpion_wheels(int CSn_pin, int clock_pin, int left_input, int right_input, float wheel_diam, float base_width); void setup_rotary_encoders(); void calibrate_rotary_encoders(); void rotary_data(); void dist_data(); void get_vx_vth(); //non shared int left_input_stream = 0; // one bit read from pin int right_input_stream = 0; long left_packed_data = 0; // two bytes concatenated from inputstream long right_packed_data = 0; long left_angle = 0; // holds processed angle value long right_angle = 0; float left_angle_float = 0.0; float right_angle_float = 0.0; float left_true_angle = 0.0; float right_true_angle = 0.0; float left_calib_angle = 0.0; float right_calib_anglt = 0.0; float left_offset_angle = 0.0; //18 22 float right_offset_angle = 0.0; float left_rotary_angle = 0.0; float right_rotary_angle = 0.0; float left_starting_angle = 0.0; float right_starting_angle = 0.0; long left_angle_temp = 0; long right_angle_temp = 0; float left_true_rad; float right_true_rad; int left_cnt = 0; int right_cnt = 0; float left_prev_rad; float right_prev_rad; float left_dist; float right_dist; long dt_micros = 0; long past_micros = 0; float left_past_dist = 0; float right_past_dist = 0; float vx; float vth; //shared long angle_mask = 262080; // 0x111111111111000000: mask to obtain first 12 digits with position info float pi = 3.1415; float resolution = 0.08789; int debug; private: int _clock_pin; int _CSn_pin; int _left_input; int _right_input; float _left_resting_angle; float _right_resting_angle; float _wheel_diam; //in meters float _base_width; //in meters }; #endif
C++
ISO-8859-1
8,106
2.578125
3
[]
no_license
#include "pch.h" #include "../MaBibliotheque/Route.hpp" #include "../MaBibliotheque/Draw.hpp" #include "../MaBibliotheque/Data.cpp" /* Test verifiant que la generation de vehicule se fait correctement*/ TEST(TestGenerationVoiture, TestStatique) { Route route = Route(); route.generation_vehicules( basse); route.get_vehicule(route.get_voie_basse(), 0)->set_vitesse_x(80); route.get_vehicule(route.get_voie_basse(), 0)->set_x(550); EXPECT_EQ(route.get_vehicule(route.get_voie_basse(), 0)->get_vitesse_x(), 80); EXPECT_EQ(route.get_vehicule(route.get_voie_basse(), 0)->get_x(), 550); } /* Tests verifiant que la fonction de colision et de consequence associe fonctionne correctement*/ TEST(TestConsColli, TestStatique1) { Route route = Route(); route.generation_vehicules( basse); route.generation_vehicules(basse); Voitures* v1 = (Voitures*)route.get_vehicule(route.get_voie_basse(), 0); Voitures* v2 = (Voitures*)route.get_vehicule(route.get_voie_basse(), 1); v1->set_vitesse_x(80); v1->set_x(450); v1->set_etat_pc_avant((etat_pare_choc)0); v2->set_etat_pc_arriere((etat_pare_choc)0); v1->consequence_collision(route.get_voie_basse(), 0,*v2); EXPECT_EQ(v1->get_etat_pc_avant(), -1); EXPECT_EQ(route.get_voie_basse().size(), 1); route.generation_vehicules(basse); v2 = (Voitures*)route.get_vehicule(route.get_voie_basse(), 1); v1->set_etat_pc_avant((etat_pare_choc)3); v2->set_etat_pc_arriere((etat_pare_choc)1); v1->consequence_collision(route.get_voie_basse(), 0, *v2); EXPECT_EQ(v1->get_etat_pc_avant(), 2); EXPECT_EQ(route.get_voie_basse().size(), 1); } TEST(TestConsColli, TestStatique2) { Route route = Route(); route.generation_vehicules(basse); route.generation_vehicules(basse); Voitures* v1 = (Voitures*)route.get_vehicule(route.get_voie_basse(), 0); Voitures* v2 = (Voitures*)route.get_vehicule(route.get_voie_basse(), 1); v1->set_vitesse_x(80); v1->set_x(450); v1->set_etat_pc_avant((etat_pare_choc)3); v2->set_etat_pc_arriere((etat_pare_choc)1); v1->consequence_collision(route.get_voie_basse(), 0, *v2); EXPECT_EQ(v1->get_etat_pc_avant(), 2); EXPECT_EQ(route.get_voie_basse().size(), 1); } TEST(TestConsColli, TestStatique3) { Route route = Route(); route.generation_vehicules(basse); route.generation_vehicules(basse); Voitures* v1 = (Voitures*)route.get_vehicule(route.get_voie_basse(), 0); Voitures* v2 = (Voitures*)route.get_vehicule(route.get_voie_basse(), 1); v1->set_vitesse_x(80); v1->set_x(450); v1->set_etat_pc_avant((etat_pare_choc)1); v2->set_etat_pc_arriere((etat_pare_choc)3); v1->consequence_collision(route.get_voie_basse(), 0, *v2); EXPECT_EQ(v1->get_etat_pc_avant(), -2); EXPECT_EQ(v2->get_etat_pc_arriere(), 2); } /* Test verifiant que box2d est correctement implente*/ TEST(TestCorp, TestStatique1) { Route route = Route(); route.generation_vehicules( basse); Vehicules* temp = route.get_vehicule(route.get_voie_basse(), 0); EXPECT_EQ(temp->get_x(), WINDOW_WIDTH + 100); EXPECT_EQ(temp->corps.body->GetPosition().x, WINDOW_WIDTH + 100); } /* Test verifiant que box2d est correctement implente et que le moteur tourne*/ TEST(TestCorp, TestDynamique1) { Route route = Route(); SFML_output out; route.generation_vehicules( basse); Vehicules* temp = route.get_vehicule(route.get_voie_basse(), 0); b2Vec2 vel = temp->corps.body->GetLinearVelocity(); for (int32 i = 0; i < 60; ++i) { route.Update(); } EXPECT_NE(vel.x, 0); EXPECT_NE(temp->corps.body->GetPosition().x, 500); } /* Test verifiant que les vhicules adaptent bien leur vitesse en fonction du vehicule en face */ TEST(TestAI, TestDynamique1) { Route route = Route(); SFML_output out; route.generation_vehicules( basse); Vehicules* vehi1 = route.get_vehicule(route.get_voie_basse(), 0); vehi1->set_vitesse_x(10); vehi1->corps.body->SetLinearVelocity(b2Vec2(vehi1->get_vitesse_x(), 0)); vehi1->set_x(400); route.generation_vehicules( basse); Vehicules* vehi2 = route.get_vehicule(route.get_voie_basse(), 1); vehi2->set_vitesse_x(-10); vehi2->corps.body->SetLinearVelocity(b2Vec2(vehi2->get_vitesse_x(), 0)); vehi2->set_x(400 + LONGUEUR_VOITURE); EXPECT_NE(vehi1->corps.body->GetLinearVelocity().x, vehi2->corps.body->GetLinearVelocity().x); for (int32 i = 0; i < 60; ++i) { route.Update(); } EXPECT_EQ(vehi1->corps.body->GetLinearVelocity().x, vehi2->corps.body->GetLinearVelocity().x); } /* Test permettant de verifier que les vehicules se dtruisent bien en sortant de l'cran du joueur */ TEST(TestAI, TestDestruction1) { Route route = Route(); SFML_output out; route.generation_vehicules( basse); route.get_vehicule(route.get_voie_basse(), 0)->set_x(0); EXPECT_EQ(route.get_voie_basse().size(), 1); double x = route.get_vehicule(route.get_voie_basse(), 0)->get_x(); while (x > - 100 ) { x = route.get_vehicule(route.get_voie_basse(), 0)->get_x(); route.Update(); } EXPECT_EQ(route.get_voie_basse().size() , 0); } /* Ce test permet de vrifier qu'une voiture qui est appel par la mthode changer_de_voie dcrmente bien le vercteur dans lequel elle se trouve et se positionne correctement dans le vecteur de la direction ou aller*/ TEST(TestAI, TestDeplacementVoie1) { Route route = Route(); route.generation_vehicules( basse); route.generation_vehicules( basse); route.generation_vehicules( milieu); route.get_vehicule(route.get_voie_basse(), 0)->set_x(400); route.get_vehicule(route.get_voie_basse(), 1)->set_x(800); route.get_vehicule(route.get_voie_milieu(), 1)->set_x(600); bool success = route.changer_de_voie(basse, milieu, *route.get_vehicule(route.get_voie_milieu(), 1), false) ; EXPECT_EQ(success, true); EXPECT_EQ(route.get_voie_milieu().size(), 1); // le joueur EXPECT_EQ(route.get_voie_basse().size(), 3); EXPECT_EQ(route.get_vehicule(route.get_voie_basse(), 0)->get_x(), 400); EXPECT_EQ(route.get_vehicule(route.get_voie_basse(), 1)->get_x(), 600); EXPECT_EQ(route.get_vehicule(route.get_voie_basse(), 2)->get_x(), 800); } /* Ce test permet de vrifier que la position de la voiture du joueur est bien dcrmenter/incrementer quand une voiture se dplace d'une voie une autre */ TEST(TestAI, TestDeplacementVoie2) { Route route = Route(); route.generation_vehicules(basse); route.get_vehicule(route.get_voie_basse(), 0)->set_x(300); route.changer_de_voie(milieu, basse, *route.get_vehicule(route.get_voie_basse(), 0), false); EXPECT_EQ(route.get_voie_milieu().size(), 2); EXPECT_EQ(route.get_voie_basse().size(), 0); EXPECT_EQ(route.get_index_voiture_joueur(), 1); route.changer_de_voie(basse, milieu, *route.get_vehicule(route.get_voie_milieu(), 0), false); EXPECT_EQ(route.get_voie_milieu().size(), 1); EXPECT_EQ(route.get_voie_basse().size(), 1); EXPECT_EQ(route.get_index_voiture_joueur(), 0); } /* Ce test permet de vrifier qu'une voiture ne peux pas aller sur un voie si une autre voiture est dj prsente au mme niveau qu'elle */ TEST(TestAI, TestDeplacementVoie3) { Route route = Route(); route.generation_vehicules( basse); route.generation_vehicules( basse); route.generation_vehicules( milieu); route.get_vehicule(route.get_voie_basse(), 0)->set_x(500); route.get_vehicule(route.get_voie_basse(), 1)->set_x(500 + LONGUEUR_VOITURE); route.get_vehicule(route.get_voie_milieu(), 0)->set_x(500 + LONGUEUR_VOITURE/2); EXPECT_EQ(route.changer_de_voie(basse, milieu, *route.get_vehicule(route.get_voie_milieu(), 0), false), false); } /*Test permettant de vrifier le bon fonctionnement du select et de l'update de la DB*/ TEST(TestDB, TestFetchAndChange1) { SQLite sqlite = SQLite(); if (sqlite.get_rc()) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(sqlite.get_db())); sqlite3_close(sqlite.get_db()); } else { fprintf(stderr, "Opened database successfully\n"); } Route route = Route(); sqlite.update_op(1); EXPECT_EQ(NIVEAU_DATA, 1); sqlite.select_op(route); EXPECT_EQ(route.get_niveau(), 1); sqlite.update_op(3); sqlite.select_op(route); EXPECT_EQ(route.get_niveau(), 3); sqlite.update_op(1); // pour remettre la valeur 1 dans le fichier sqlite3_close(sqlite.get_db()); }
Python
UTF-8
665
3.625
4
[]
no_license
#Test.assert_equals(kebabize('myCamelCasedString'), 'my-camel-cased-string') #Test.assert_equals(kebabize('myCamelHas3Humps'), 'my-camel-has-humps') #Test.assert_equals(kebabize('SOS'), 's-o-s') #Test.assert_equals(kebabize('42'), '') #Test.assert_equals(kebabize('CodeWars'), 'code-wars') def kebabize(string): result = '' for t in string: if t.islower(): result += t elif t.isupper(): result += '-'+ t.lower() elif t.isnumeric(): result += '' if string.isnumeric(): return '' if result[0] == '-': return result[1:] return result print(kebabize('myCamelHas3Humps'))
C#
UTF-8
1,280
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AnimalHouseEntities; using AnimalHousePersistence; namespace AnimalHouse { public class SaleController { //SingleTon Mønster private static SaleController instance; private SaleController() { } public static SaleController Instance() { if (instance == null) { instance = new SaleController(); } return instance; } ISaleManager saleManager = new SaleManager(); Iinvoice invoice = new Invoice(); public Sale CreateSale(Sale sale) { Sale saleWithID = saleManager.CreateSale(sale); return saleWithID; } public string DeleteSale(Sale sale) { string returncode = saleManager.DeleteSale(sale); return returncode; } public List<Sale> GetManySalesByCustomerID(Customer customer) { List<Sale> sales = saleManager.GetManySalesByCustomerID(customer); return sales; } public void CreateInvoice(Sale sale) { invoice.CreatePDF(sale); } } }
Java
UTF-8
4,957
2.3125
2
[]
no_license
package com.me.controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.me.adaptor.Validation; import com.me.connector.NewUserDBConnector; import com.me.entity.BankDataBean; /** * Servlet implementation class NewUserServlet */ @WebServlet("/NewUserServlet") public class NewUserServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public NewUserServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean rst=false; response.setContentType("text/html"); PrintWriter out = response.getWriter(); BankDataBean bdb=new BankDataBean(); String firstName =request.getParameter("fName"); bdb.setFirstName(firstName); String lastName =request.getParameter("lName"); bdb.setLastName(lastName); String userId =request.getParameter("userID"); bdb.setUser_ID(userId); String password =request.getParameter("password"); bdb.setPassword(password); String email =request.getParameter("emailID"); bdb.setEmail_ID(email); String dob =request.getParameter("DOB"); bdb.setDateOfBirth(dob); bdb.setAccountType("N"); if(request.getParameter("Checking")!=null) { bdb.setAccountType("C"); float checkingbal=Float.parseFloat(request.getParameter("checkingBal")); bdb.setCheckingBal(checkingbal); } if(request.getParameter("Saving")!=null) { if (bdb.getAccountType().equals("C")){ bdb.setAccountType("B"); } else{ bdb.setAccountType("S"); } float savingbal=Float.parseFloat(request.getParameter("savBal")); bdb.setSavingBal(savingbal); } Validation vd=new Validation(); try { rst=vd.newUserTest(bdb); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) { e.printStackTrace(); } if(rst) { NewUserDBConnector nd=new NewUserDBConnector(); try{ nd.setConnection(); nd.getUserInformation(bdb); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } String fName=bdb.getFirstName(); String lName=bdb.getLastName(); String emailId=bdb.getEmail_ID(); int savingAcctNum=bdb.getSavingAcctNum(); int checkingAcctNum=bdb.getCheckingAcctNum(); out.write("<html><head> <title>Account Details</title>"); out.write("<center> <b>"+fName+" "+lName+" Account Details </b></center>"); out.print("<form action='FormServlet'>"); out.print("First Name:"+fName+"<br/>"); out.print("Last Name :"+lName+"<br/>"); out.print("email ID :"+emailId+"<br/>"); if(savingAcctNum>0) { float savingBal=bdb.getSavingBal(); int SavAcct=savingAcctNum; // out.print("Saving Account no:"+SavAcct+"<br/>"); out.print("Saving Account no: <input type ='text' name ='savnum' value = "+SavAcct+" readonly><br/>"); // out.print("Saving Account no: <input type ='text' name ='savnum' value = "+SavAcct+" readonly><br/>"); // out.print("Sav Account no: <input type =\"text\" name =\"savnum\" value = "+SavAcct+" readonly><br/>"); out.print("Saving Account Balance: $"+savingBal+"<br/>"); } if(checkingAcctNum>0) { float checkingBal=bdb.getCheckingBal(); int checkAcct=checkingAcctNum; // out.print("Checking Account no:"+checkAcct+"<br/>"); out.print("Checking Account no: <input type ='text' name ='chknum' value = "+checkAcct+" readonly><br/>"); out.print("Checking Account Balance: $"+checkingBal+"<br/>"); } out.print("<br/><input type='submit' value='Transaction' name='arith'/><br/><br/>"); out.print("<input type='submit' value='LogOff' name='arith'/><br/>"); out.print("</form>"); } else { RequestDispatcher disp1 = request.getRequestDispatcher("/NewUserFrame.html"); disp1.forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
Java
UTF-8
3,574
2.234375
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
package io.delta.flink.source.internal.state; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.apache.flink.connector.file.src.util.CheckpointedPosition; import org.apache.flink.core.fs.Path; import org.apache.flink.core.io.SimpleVersionedSerialization; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class DeltaSourceSplitSerializerTest { public static final String RANDOM_ID = UUID.randomUUID().toString(); static void assertSplitsEqual(DeltaSourceSplit expected, DeltaSourceSplit actual) { assertEquals(expected.getPartitionValues(), actual.getPartitionValues()); assertEquals(expected.getReaderPosition(), actual.getReaderPosition()); assertEquals(expected.splitId(), actual.splitId()); assertEquals(expected.path(), actual.path()); assertEquals(expected.offset(), actual.offset()); assertEquals(expected.length(), actual.length()); assertArrayEquals(expected.hostnames(), actual.hostnames()); assertEquals(expected.getReaderPosition(), actual.getReaderPosition()); } private static DeltaSourceSplit serializeAndDeserialize(DeltaSourceSplit split) throws IOException { DeltaSourceSplitSerializer serializer = DeltaSourceSplitSerializer.INSTANCE; byte[] bytes = SimpleVersionedSerialization.writeVersionAndSerialize(serializer, split); return SimpleVersionedSerialization.readVersionAndDeSerialize(serializer, bytes); } @Test public void serializeSplitWithNoPartitions() throws Exception { DeltaSourceSplit split = new DeltaSourceSplit( Collections.emptyMap(), RANDOM_ID, new Path("hdfs://namenode:14565/some/path/to/a/file"), 100_000_000, 64_000_000, new String[]{"host1", "host2", "host3"}, new CheckpointedPosition(7665391L, 100L)); DeltaSourceSplit deSerialized = serializeAndDeserialize(split); assertSplitsEqual(split, deSerialized); } @Test public void serializeSplitWithSinglePartition() throws Exception { DeltaSourceSplit split = new DeltaSourceSplit( Collections.singletonMap("col1", "val1"), "random-id", new Path("hdfs://namenode:14565/some/path/to/a/file"), 100_000_000, 64_000_000, new String[]{"host1", "host2", "host3"}, new CheckpointedPosition(7665391L, 100L)); DeltaSourceSplit deSerialized = serializeAndDeserialize(split); assertSplitsEqual(split, deSerialized); } @Test public void serializeSplitWithPartitions() throws Exception { Map<String, String> partitions = new HashMap<>(); partitions.put("col1", "val1"); partitions.put("col2", "val2"); partitions.put("col3", "val3"); DeltaSourceSplit split = new DeltaSourceSplit( partitions, "random-id", new Path("hdfs://namenode:14565/some/path/to/a/file"), 100_000_000, 64_000_000, new String[]{"host1", "host2", "host3"}, new CheckpointedPosition(7665391L, 100L)); DeltaSourceSplit deSerialized = serializeAndDeserialize(split); assertSplitsEqual(split, deSerialized); } }
Java
UTF-8
546
2.890625
3
[]
no_license
package com.flipkart.exception; public class IncompleteRegistrationRequirementException extends Exception{ private String studentId; private String courseId; public IncompleteRegistrationRequirementException(String studentId, String courseId) { this.studentId = studentId; this.courseId = courseId; } @Override public String getMessage() { return "The student " + this.studentId + " cannot be registered to the course " + this.courseId + " due to incomplete registration requirements!"; } }
Java
UTF-8
17,885
2.1875
2
[]
no_license
package biz.africanbib.Tabs; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.ArrayList; import biz.africanbib.Activity.MainActivity; import biz.africanbib.Adapters.ComplexRecyclerViewAdapter; import biz.africanbib.Models.Add; import biz.africanbib.Models.Divider; import biz.africanbib.Models.Heading; import biz.africanbib.Models.SimpleEditTextBuilder; import biz.africanbib.Models.SimpleText; import biz.africanbib.R; import biz.africanbib.Tools.DatabaseHelper; import biz.africanbib.Tools.Helper; //Our class extending fragment public class Tab1 extends Fragment { RecyclerView recyclerView; ComplexRecyclerViewAdapter adapter; Helper helper; boolean isTab; DatabaseHelper databaseHelper; ArrayList<Object> items = new ArrayList<>(); public String businessName = "Business Name *"; public String registerationNumber = "Registeration No "; public String keyVisual = "Keyvisual (Photo) "; public String corporateLogo = "Corporate Logo "; public String telephone = "Telephone "; public String city_town = "City / Town "; public String state = "District / State "; public String country = "Country "; private final String TAG = "Tab1"; private Fragment fragment; ProgressDialog progressDialog; int a = 0; public ArrayList<Object> getList() { return items; } //Overriden method onCreateView @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab_1, container, false); Log.d("Company", "Trying to initialize"); helper = new Helper(this.getContext()); isTab = helper.isTab(); databaseHelper = new DatabaseHelper(view.getContext(), DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION); init(view); fragment = this; progressDialog = new ProgressDialog(this.getContext()); progressDialog.setMessage("Loading.."); progressDialog.show(); a = 10; return view; } private void init(View view) { recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_1); getSampleArrayList(); /*manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if (adapter.getItem(position) instanceof Heading) return 2; else return 1; } }); */ //SnapHelper snapHelper = new GravitySnapHelper(Gravity.TOP); //snapHelper.attachToRecyclerView(recyclerView); Log.d("Company", "Adapter set"); } @Override public void onConfigurationChanged(Configuration config) { super.onConfigurationChanged(config); /* // Check for the rotation if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this.getContext(), "LANDSCAPE", Toast.LENGTH_SHORT).show(); setupGridLayout(true); } else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(this.getContext(), "PORTRAIT", Toast.LENGTH_SHORT).show(); if (isTab) { setupGridLayout(true); } else { setupGridLayout(false); } } */ } private void setupGridLayout(boolean multiColumn) { if (multiColumn) { GridLayoutManager manager = new GridLayoutManager(this.getContext(), 2); manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { Object ob = adapter.getItem(position); if (ob instanceof Heading || ob instanceof Add || ob instanceof SimpleText || ob instanceof Divider) return 2; else return 1; } }); recyclerView.setLayoutManager(manager); } else { GridLayoutManager manager = new GridLayoutManager(this.getContext(), 1); recyclerView.setLayoutManager(manager); } } public ComplexRecyclerViewAdapter getAdapter() { return adapter; } private void getSampleArrayList() { LoadTab loadTab = new LoadTab(); loadTab.execute(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { try { super.onActivityResult(requestCode, resultCode, data); Log.d("Tab1", "Request Code " + requestCode); adapter.onActivityResult(requestCode, resultCode, data); } catch (Exception e) { e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { adapter.onRequestPermissionsResult(requestCode, permissions, grantResults); } else { Toast.makeText(getActivity(), "Please give your permission.", Toast.LENGTH_LONG).show(); } break; } } } private class LoadTab extends AsyncTask<Void, Void, ArrayList<Object>> { @Override protected ArrayList<Object> doInBackground(Void... voids) { items = new ArrayList<>(); items.add(new Heading("COMPANY / INSTITUTION PROFILE", null)); String columnName = DatabaseHelper.COLUMN_COMPANY_NAME; String tableName = DatabaseHelper.TABLE_COMPANY_PROFILE; String value = databaseHelper.getStringValue(columnName, tableName); Log.v("Tab1", "Value = " + value); items.add(new SimpleEditTextBuilder() .setTableName(tableName) .setColumnName(columnName) .setTitle(businessName) .setValue(value) .setXmlTag("name") .setRowno(-1) .createSimpleEditText()); columnName = DatabaseHelper.COLUMN_REGISTERATION_NO; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText(registerationNumber, value, tableName, columnName, -1, "registrationNumber")); columnName = DatabaseHelper.COLUMN_NGO_DIASPORA; int selectedPosition = databaseHelper.getIntValue(columnName, tableName); items.add(helper.buildDropDown("Company/NGO/DIASPORA", new String[]{"Company", "NGO", "Diaspora"}, new int[]{0, 1, 2}, selectedPosition, tableName, columnName, -1, "companyNgoDiaspora")); columnName = DatabaseHelper.COLUMN_LOGO; Bitmap corporatelogo = null; try { corporatelogo = helper.createBitmapFromByteArray(databaseHelper.getBlobValue(columnName, tableName)); } catch (Exception e) { e.printStackTrace(); } //Log.v(TAG,"Image Value = " + image.toString()); items.add(helper.buildImage(corporateLogo, -1, corporatelogo, tableName, columnName, "logo")); columnName = DatabaseHelper.COLUMN_KEYVISUAL_PHOTO; Bitmap keyvisual = null; try { keyvisual = helper.createBitmapFromByteArray(databaseHelper.getBlobValue(columnName, tableName)); } catch (Exception e) { e.printStackTrace(); } items.add(helper.buildImage(keyVisual, -1, keyvisual, tableName, columnName, "keyvisual")); //items.add(helper.buildDropDown("Keyvisual (Photo)", new String[]{"Collected", "Not Collected"}, selectedPosition, tableName, columnName, -1)); /* columnName = DatabaseHelper.COLUMN_LOGO_NOTE; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Logo Note", value, tableName, columnName, -1, "logonote")); columnName = DatabaseHelper.COLUMN_KEYVISUAL_NOTE; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Key Visual Note", value, tableName, columnName, -1, "keyvisualnote")); */ columnName = DatabaseHelper.COLUMN_BRIEF_DESCRIPTION; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Brief Description of the Company / Instituion", value, tableName, columnName, -1, "description")); columnName = DatabaseHelper.COLUMN_FOUNDING_YEAR_OF_COMPANY; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Founding year of Company / Institution", value, tableName, columnName, -1, "foundingYear")); columnName = DatabaseHelper.COLUMN_AGE_OF_ACTIVE_BUSINESS; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Age of Active Business", value, tableName, columnName, -1, "ageOfActBusiness")); items.add(new Heading("COMPANY CONTACT", "contact")); columnName = DatabaseHelper.COLUMN_TELEPHONE; tableName = DatabaseHelper.TABLE_COMPANY_CONTACT; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText(telephone, value, tableName, columnName, -1, "telephone")); columnName = DatabaseHelper.COLUMN_CELLPHONE; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Cellphone", value, tableName, columnName, -1, "cellphone")); columnName = DatabaseHelper.COLUMN_FAX; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Fax", value, tableName, columnName, -1, "fax")); columnName = DatabaseHelper.COLUMN_EMAIL; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Email", value, tableName, columnName, -1, "email")); columnName = DatabaseHelper.COLUMN_WEBSITE; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Website", value, tableName, columnName, -1, "website")); items.add(new Heading("COMPANY POSTAL ADDRESS", "contact")); tableName = DatabaseHelper.TABLE_COMPANY_POSTAL_ADDRESS; columnName = DatabaseHelper.COLUMN_STREET; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Street & Number", value, tableName, columnName, -1, "street")); columnName = DatabaseHelper.COLUMN_PO_BOX; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Post Office Box", value, tableName, columnName, -1, "postbox")); columnName = DatabaseHelper.COLUMN_POSTAL_CODE; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Postal Code", value, tableName, columnName, -1, "postalCode")); columnName = DatabaseHelper.COLUMN_CITY; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("City / Town", value, tableName, columnName, -1, "city")); columnName = DatabaseHelper.COLUMN_DISTRICT; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("District/State", value, tableName, columnName, -1, "district")); columnName = DatabaseHelper.COLUMN_COUNTRY; selectedPosition = databaseHelper.getIntValue(columnName, tableName); items.add(helper.buildDropDown("Country", helper.getCountryNames(), helper.getCountryCodes(), selectedPosition, tableName, columnName, -1, "country")); /*items.add(new Heading("COMPANY PHYSICAL ADRESS", "contact")); columnName = DatabaseHelper.COLUMN_STREET; tableName = DatabaseHelper.TABLE_COMPANY_PHYSICAL_ADDRESS; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Street & Number", value, tableName, columnName, -1, "street")); columnName = DatabaseHelper.COLUMN_CITY; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText(city_town, value, tableName, columnName, -1, "city")); columnName = DatabaseHelper.COLUMN_POSTAL_CODE; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Postal Code", value, tableName, columnName, -1, "postalCode")); columnName = DatabaseHelper.COLUMN_DISTRICT; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText(state, value, tableName, columnName, -1, "district")); columnName = DatabaseHelper.COLUMN_STREET; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Street & Number", value, tableName, columnName, -1, "street")); columnName = DatabaseHelper.COLUMN_COUNTRY; selectedPosition = databaseHelper.getIntValue(columnName, tableName); items.add(helper.buildDropDown(country, helper.getCountryNames(), helper.getCountryCodes(), selectedPosition, tableName, columnName, -1, "country")); */ items.add(new Heading("COMPANY SPECIFIC INFORMATION", "about")); columnName = DatabaseHelper.COLUMN_LEGAL_FORM; tableName = DatabaseHelper.TABLE_COMPANY_SPECIFIC_INFORMATION; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Legal Form", value, tableName, columnName, -1, "legalForm")); columnName = DatabaseHelper.COLUMN_TYPE_OF_ORGANISATION; selectedPosition = databaseHelper.getIntValue(columnName, tableName); items.add(helper.buildDropDown("Type of Orgainsation", new String[]{"Business Partnership", "International NGO", "Freelance", "Public Institution", "Individual Enterprise", "Local NGO", "Privately Held Company", "Publicly Held Institution"}, new int[]{0, 3, 1, 6, 2, 4, 5, 7}, selectedPosition, tableName, columnName, -1, "typeOrganization")); columnName = DatabaseHelper.COLUMN_TYPE_OF_ACTIVITIES; selectedPosition = databaseHelper.getIntValue(columnName, tableName); items.add(helper.buildDropDown("Type of Activities", new String[]{"Manufacturing", "Service Provider", "Manufacturing + Service Provider"}, new int[]{1, 2, 3}, selectedPosition, tableName, columnName, -1, "typeActivities")); columnName = DatabaseHelper.COLUMN_ABOUT_US; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("About Us", value, tableName, columnName, -1, "aboutStatement")); columnName = DatabaseHelper.COLUMN_VISION; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Vision", value, tableName, columnName, -1, "vision")); columnName = DatabaseHelper.COLUMN_MISSION_STATEMENT; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Mission Statement", value, tableName, columnName, -1, "missionStatement")); columnName = DatabaseHelper.COLUMN_GUIDING_PRINCIPALS; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Guiding Principals", value, tableName, columnName, -1, "guidingPrinciples")); /* columnName = DatabaseHelper.COLUMN_INVESTMENT_OPPORTUNITIES; value = databaseHelper.getStringValue(columnName, tableName); items.add(helper.buildEditText("Investment Opportunities", value, tableName, columnName, -1, "investmentOpportunities")); */ Log.v(TAG, "Tab1 Initialize Complete"); return items; } @Override protected void onPostExecute(ArrayList<Object> objects) { super.onPostExecute(objects); adapter = new ComplexRecyclerViewAdapter(objects, getFragmentManager(), fragment); if (MainActivity.first) { if (isTab) { setupGridLayout(true); } else { setupGridLayout(false); } MainActivity.first = false; } recyclerView.setAdapter(adapter); progressDialog.dismiss(); } } }
C++
UTF-8
8,323
2.8125
3
[]
no_license
#include <utility> #include <Console/Graphics.hpp> Graphics::Graphics(const std::vector<std::string>& columnsNames, const std::vector<std::vector<std::string>>& rowsValues, DiningScheduler& diningScheduler) : _window(nullptr) , _menu(nullptr) , _menuItems(nullptr) , _columnsNames(columnsNames) , _rows() , _rowsValues(rowsValues) , _nullRow("\0") , _topPadding(4) , _bottomPadding(4) , _horizontalPadding(4) , _columnsCount(columnsNames.size()) , _columnWidth() , _rowsCount() , _baseMenuItemId(2) , _rowsForkStateIndex(4) , _rowsForkOwnerIndex(3) , _diningScheduler(diningScheduler) { // set COLS and LINES variables initscr(); // calculate each columns maximum string length _columnWidth = calculateColumnWidth(); createRows(); init(); } Graphics::~Graphics() { wrefresh(_window); // deallocate menu unpost_menu(_menu); free_menu(_menu); // deallocate menu items for(uint32_t rowId = 0; rowId < _rowsCount; ++rowId) { free_item(_menuItems[rowId]); } // deallocate window wborder(_window, ' ', ' ', ' ',' ',' ',' ',' ',' '); refresh(); delwin(_window); // stop ncurses endwin(); } std::string Graphics::createRow(const std::vector<std::string>& columnsValues) { // this method draws table row out of given values std::string result; uint32_t bordersCount = 0; for(const auto& columnValue : columnsValues) { // calculate padding between columns row content and column separator uint32_t padding = _columnWidth - columnValue.size(); // build row result = result + columnValue + std::string(padding, ' '); if(++bordersCount != columnsValues.size()) { // add column separator if not all columns were filled result = result + "|"; } else { // append more padding to the last column to fill whole menu window size padding = calculateWindowWidth() - 2 - result.size(); result = result + std::string(padding, ' '); } } return result; } void Graphics::createRows() { // this method creates rows for table // first two rows are column titles and line separator // succesive rows are table records // create row containing column titles // create row containing line separator std::string menuTitle = createRow(_columnsNames); std::string lineSeparator = createRow(std::vector<std::string>(_columnsCount, std::string(_columnWidth, '-'))); // push rows to the rows vector as table column names and line separator _rows.push_back(menuTitle); _rows.push_back(lineSeparator); // create following table records for(const auto& row : _rowsValues) { std::string menuItem = createRow(row); _rows.push_back(menuItem); } // ncurses menu requires that menu item list is closed with null item _rows.push_back(_nullRow); _rowsCount = _rows.size(); // add columns names, line separator and null row to rows values vector _rowsValues.insert(_rowsValues.begin(), std::vector<std::string>(_columnsCount, std::string(_columnWidth, '-'))); _rowsValues.insert(_rowsValues.begin(), _columnsNames); _rowsValues.push_back(std::vector<std::string>(1, _nullRow)); } uint32_t Graphics::calculateWindowWidth() { return COLS - 2*_horizontalPadding; } uint32_t Graphics::calculateWindowHeight() { return LINES - _topPadding - _bottomPadding; } uint32_t Graphics::calculateColumnWidth() { return ((calculateWindowWidth() - 1) - (_columnsCount - 1)) / _columnsCount; } void Graphics::initMenuItems() { // this method creates actual menu items from created rows _menuItems = new ITEM*[_rows.size()]; for(uint32_t rowId = 0; rowId < _rows.size() - 1; ++rowId) { _menuItems[rowId] = new_item(_rows[rowId].c_str(), _rows[rowId].c_str()); } // add null item at the end _menuItems[_rows.size() - 1] = new_item(_rows.rbegin()->c_str(), _rows.rbegin()->c_str()); } void Graphics::init() { // block OS signal receiver for special characters combinations like Ctrl + C raw(); // do not print user selections on the screen noecho(); // give keypad control to the main screen keypad(stdscr, true); _columnWidth = calculateColumnWidth(); uint32_t windowHeight = calculateWindowHeight(); uint32_t windowWidth = calculateWindowWidth(); uint32_t menuHeight = calculateWindowHeight() - 2; uint32_t menuWidth = calculateWindowWidth() - 2; initMenuItems(); // allocate memory for parent window and its sibling menu _menu = new_menu(_menuItems); _window = newwin(windowHeight, windowWidth, _topPadding, _horizontalPadding); keypad(_window, true); // associate menu with window set_menu_win(_menu, _window); // create sub window for menu set_menu_sub(_menu, derwin(_window, menuHeight, menuWidth, 1, 1)); // create sub window for menu set_menu_format(_menu, menuHeight, 1); // hide marking char for current menu selection set_menu_mark(_menu, ""); // draw simple box sround window box(_window, 0, 0); // print heading and user tips mvprintw(0, _horizontalPadding, "%s", "Author: Wolanski Grzegorz"); mvprintw(_topPadding - 1, _horizontalPadding + 1, "%s", "DINING TABLE STATE"); mvprintw(_topPadding + windowHeight, _horizontalPadding, "%s", "Q - exit program"); refresh(); // generate menu with items in the memory of the window post_menu(_menu); wrefresh(_window); refresh(); } void Graphics::refreshMenu() { // save current selection so screen will not revert // to the top after update ITEM* currentItem = _menu->curitem; unpost_menu(_menu); set_menu_items(_menu, _menuItems); set_current_item(_menu, currentItem); post_menu(_menu); wrefresh(_window); } void Graphics::display() { int32_t option; bool quit = false; while(!quit && (option = getch())) { std::lock_guard<std::mutex> lock(mutex); switch(option) { case KEY_DOWN: // choose lower item menu_driver(_menu, REQ_DOWN_ITEM); break; case KEY_UP: // choose higher item menu_driver(_menu, REQ_UP_ITEM); break; case KEY_NPAGE: // scroll to next page menu_driver(_menu, REQ_SCR_DPAGE); break; case KEY_PPAGE: // scroll to previous page menu_driver(_menu, REQ_SCR_UPAGE); break; case 'q': _diningScheduler.stopDinner(); quit = true; break; default: break; } wrefresh(_window); } } void Graphics::updateRow(uint32_t philosopherIndex, uint32_t rightForkIndex, const std::vector<std::string>& philosopherRowValues, const std::pair<std::string, std::string>& rightForkOwnerAndState) { std::lock_guard<std::mutex> lock(mutex); // align indexes to menu items indexing philosopherIndex += _baseMenuItemId; rightForkIndex += _baseMenuItemId; // update table row with right fork of corresponding philosopher that is being updated _rowsValues[rightForkIndex][_rowsForkOwnerIndex] = rightForkOwnerAndState.first; _rowsValues[rightForkIndex][_rowsForkStateIndex] = rightForkOwnerAndState.second; // create new rows from given values std::string updatedPhilosopherRow = createRow(philosopherRowValues); std::string updatedRightForkRow = createRow(_rowsValues[rightForkIndex]); // overwrite rows at given indexes _rowsValues[philosopherIndex] = philosopherRowValues; _rows[philosopherIndex] = updatedPhilosopherRow; _rows[rightForkIndex] = updatedRightForkRow; _menuItems[philosopherIndex] = new_item(_rows[philosopherIndex].c_str(), _rows[philosopherIndex].c_str()); _menuItems[rightForkIndex] = new_item(_rows[rightForkIndex].c_str(), _rows[rightForkIndex].c_str()); // update menu items refreshMenu(); }
Java
UTF-8
823
3.203125
3
[]
no_license
import java.util.Scanner; public class Uri1182 { public static void main (String[] args) { Scanner scan = new Scanner(System.in); int c, i = 0, j = 0; double m [][] = new double [12][12]; char ch; c = scan.nextInt(); ch = scan.next().charAt(0); while(i < 12) { while (j < 12) { m[i][j] = scan.nextDouble(); j++; } i++; j = 0; } System.out.printf("%.1f\n", coluna(c, ch, m)); } public static double coluna(int c, char ch, double m[][]) { int i = 0; double soma = 0; while(i < 12) { soma = soma + m[i][c]; i++; } if(ch == 'M') { soma = soma / 12; } return soma; } }
Rust
UTF-8
16,055
4.4375
4
[]
no_license
// Rust’s standard library includes a number of very useful data structures called collections. Most other // data types represent one specific value, but collections can contain multiple values. Unlike the built-in // array and tuple types, the data these collections point to is stored on the heap, which means the amount // of data does not need to be known at compile time and can grow or shrink as the program runs. Each kind // of collection has different capabilities and costs, and choosing an appropriate one for your current // situation is a skill you’ll develop over time. In this chapter, we’ll discuss three collections that are // used very often in Rust programs: // - A vector allows you to store a variable number of values next to each other. // - A string is a collection of characters. We’ve mentioned the String type previously, but in this chapter // we’ll talk about it in depth. // - A hash map allows you to associate a value with a particular key. It’s a particular implementation of // the more general data structure called a map. // The first collection type we’ll look at is Vec<T>, also known as a vector. Vectors allow you to store // more than one value in a single data structure that puts all the values next to each other in memory. // Vectors can only store values of the same type. They are useful when you have a list of items, such // as the lines of text in a file or the prices of items in a shopping cart. // Creation of a new empty vector: let v: Vec<i32> = Vec::new(); // In more realistic code, Rust can often infer the type of value you want to store once you insert values, // so you rarely need to do this type annotation. It’s more common to create a Vec<T> that has initial values, // and Rust provides the vec! macro for convenience. The macro will create a new vector that holds the values // you give it. Because we’ve given initial i32 values, Rust can infer that the type of v is Vec<i32>, and // the type annotation isn’t necessary. let v = vec![1, 2, 3]; // Push some values onto a vector: let mut v = Vec::new(); v.push(5); v.push(6); // Like any other struct, a vector is freed when it goes out of scope { let v = vec![1, 2, 3, 4]; // do stuff with v } // <- v goes out of scope and is freed here // You can access elements in a vector with either bracket notation or using "get". Bracket notation will // panic if it attempts to reference a non-existent element. Get will return None without panicing let v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {}", third); match v.get(2) { Some(third) => println!("The third element is {}", third), None => println!("There is no third element."), } // Iterate over a vector: let v = vec![100, 32, 57]; for i in &v { println!("{}", i); } // Iterate over mutable references let mut v = vec![100, 32, 57]; for i in &mut v { *i += 50; } // At the beginning of this chapter, we said that vectors can only store values that are the same type. This // can be inconvenient; there are definitely use cases for needing to store a list of items of different // types. Fortunately, the variants of an enum are defined under the same enum type, so when we need to // store elements of a different type in a vector, we can define and use an enum! // For example, say we want to get values from a row in a spreadsheet in which some of the columns in the row // contain integers, some floating-point numbers, and some strings. We can define an enum whose variants will // hold the different value types, and then all the enum variants will be considered the same type: that of // the enum. Then we can create a vector that holds that enum and so, ultimately, holds different types. enum SpreadsheetCell { Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; // What Is a String? // We’ll first define what we mean by the term string. Rust has only one string type in the core language, which // is the string slice str that is usually seen in its borrowed form &str. In Chapter 4, we talked about string // slices, which are references to some UTF-8 encoded string data stored elsewhere. String literals, for example, // are stored in the program’s binary and are therefore string slices. // The String type, which is provided by Rust’s standard library rather than coded into the core language, is a // growable, mutable, owned, UTF-8 encoded string type. When Rustaceans refer to “strings” in Rust, they usually // mean the String and the string slice &str types, not just one of those types. Although this section is largely // about String, both types are used heavily in Rust’s standard library, and both String and string slices are // UTF-8 encoded. // Rust’s standard library also includes a number of other string types, such as OsString, OsStr, CString, and // CStr. Library crates can provide even more options for storing string data. See how those names all end in // String or Str? They refer to owned and borrowed variants, just like the String and str types you’ve seen // previously. These string types can store text in different encodings or be represented in memory in a different // way, for example. // Creating a new string let mut s = String::new(); // Start with some data in a string let data = "initial contents"; let s = data.to_string(); // the method also works on a literal directly: let s = "initial contents".to_string(); // Or let s = String::from("initial contents"); // Remember that strings are UTF-8 encoded, so we can include any properly encoded data in them let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); // Modifying a string let mut s = String::from("foo"); s.push_str("bar"); // push a string slice let mut s = String::from("lo"); s.push('l'); // push a single character // String concatenation let s1 = String::from("Hello, "); let s2 = String::from("world!"); let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used // First, s2 has an &, meaning that we’re adding a reference of the second string to the first string because // of the s parameter in the add function: we can only add a &str to a String; we can’t add two String values // together. But wait—the type of &s2 is &String, not &str, as specified in the second parameter to add. // The reason we’re able to use &s2 in the call to add is that the compiler can coerce the &String argument into // a &str. When we call the add method, Rust uses a deref coercion, which here turns &s2 into &s2[..]. We’ll // discuss deref coercion in more depth in Chapter 15. Because add does not take ownership of the s parameter, // s2 will still be a valid String after this operation. // Second, we can see in the signature that add takes ownership of self, because self does not have an &. This // means s1 in Listing 8-18 will be moved into the add call and no longer be valid after that. So although // let s3 = s1 + &s2; looks like it will copy both strings and create a new one, this statement actually takes // ownership of s1, appends a copy of the contents of s2, and then returns ownership of the result. In other // words, it looks like it’s making a lot of copies but isn’t; the implementation is more efficient than copying. // If we need to concatenate multiple strings, the behavior of the + operator gets unwieldy: let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); let s = s1 + "-" + &s2 + "-" + &s3; // So we can use the format! macro: let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); let s = format!("{}-{}-{}", s1, s2, s3); // A String is a wrapper over a Vec<u8>. Let’s look at some an example string: let len = String::from("Hola").len(); // In this case, len will be 4, which means the vector storing the string “Hola” is 4 bytes long. Each of these // letters takes 1 byte when encoded in UTF-8. But what about the following line? (Note that this string begins // with the capital Cyrillic letter Ze, not the Arabic number 3.) let len = String::from("Здравствуйте").len(); // Asked how long the string is, you might say 12. However, Rust’s answer is 24: that’s the number of bytes it // takes to encode “Здравствуйте” in UTF-8, because each Unicode scalar value in that string takes 2 bytes of // storage. Therefore, an index into the string’s bytes will not always correlate to a valid Unicode scalar // value. To demonstrate, consider this invalid Rust code: let hello = "Здравствуйте"; let answer = &hello[0]; // What should the value of answer be? Should it be З, the first letter? When encoded in UTF-8, the first byte // of З is 208 and the second is 151, so answer should in fact be 208, but 208 is not a valid character on its own. // Returning 208 is likely not what a user would want if they asked for the first letter of this string; however, // that’s the only data that Rust has at byte index 0. Users generally don’t want the byte value returned, even // if the string contains only Latin letters: if &"hello"[0] were valid code that returned the byte value, it would // return 104, not h. To avoid returning an unexpected value and causing bugs that might not be discovered immediately, // Rust doesn’t compile this code at all and prevents misunderstandings early in the development process. // Slicing Strings // Indexing into a string is oftfen a bad idea because it’s not clear what the return type of the string-indexing // operation should be: a byte value, a character, a grapheme cluster, or a string slice. Therefore, Rust asks you to // be more specific if you really need to use indices to create string slices. To be more specific in your indexing // and indicate that you want a string slice, rather than indexing using [] with a single number, you can use [] // with a range to create a string slice containing particular bytes: let hello = "Здравствуйте"; let s = &hello[0..4]; // Here, s will be a &str that contains the first 4 bytes of the string. Earlier, we mentioned that each of these // characters was 2 bytes, which means s will be Зд. // What would happen if we used &hello[0..1]? The answer: Rust would panic at runtime in the same way as if an // invalid index were accessed in a vector // You can also iterate over a string with different methods: for c in "नमस्ते".chars() { println!("{}", c); } // And for b in "नमस्ते".bytes() { println!("{}", b); } // Hash Maps // Just like vectors, hash maps store their data on the heap. // You can create an empty hash map with new and add elements with insert. use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); // Another way of constructing a hash map is by using the collect method on a vector of tuples, where each tuple // consists of a key and its value. The collect method gathers data into a number of collection types, including // HashMap. For example, if we had the team names and initial scores in two separate vectors, we could use the // zip method to create a vector of tuples where “Blue” is paired with 10, and so forth. Then we could use the collect // method to turn that vector of tuples into a hash map use std::collections::HashMap; let teams = vec![String::from("Blue"), String::from("Yellow")]; let initial_scores = vec![10, 50]; let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); // The type annotation HashMap<_, _> is needed here because it’s possible to collect into many different data structures // and Rust doesn’t know which you want unless you specify. For the parameters for the key and value types, however, we // use underscores, and Rust can infer the types that the hash map contains based on the types of the data in the vectors // For types that implement the Copy trait, like i32, the values are copied into the hash map. For owned values like String, // the values will be moved and the hash map will be the owner of those values use std::collections::HashMap; let field_name = String::from("Favorite color"); let field_value = String::from("Blue"); let mut map = HashMap::new(); map.insert(field_name, field_value); // field_name and field_value are invalid at this point, try using them and compiler will be angry! // We can get a value out of the hash map by providing its key to the get method use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); let team_name = String::from("Blue"); let score = scores.get(&team_name) // We can iterate over each key/value pair in a hash map in a similar manner as we do with vectors, using a for loop: use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); for (key, value) in &scores { println!("{}: {}", key, value) } // If we insert a key and a value into a hash map and then insert that same key with a different value, the value associated with // that key will be replaced. Even though the code in Listing 8-24 calls insert twice, the hash map will only contain one // key/value pair because we’re inserting the value for the Blue team’s key both times. use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Blue"), 25); println!("{:?}", scores); // {"Blue": 25} -> second insert overwrote the first // Only Inserting a Value If the Key Has No Value use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.entry(String::from("Yellow")).or_insert(50); scores.entry(String::from("Blue")).or_insert(50); println!("{:?}", scores); // {"Yellow": 50, "Blue": 10} // Updating a value based on the old value use std::collections::HashMap; let text = "hello world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); *count += 1; } println!("{:?}", map); // This code will print {"world": 2, "hello": 1, "wonderful": 1}. The or_insert method actually returns a mutable // reference (&mut V) to the value for this key. Here we store that mutable reference in the count variable, so in // order to assign to that value, we must first dereference count using the asterisk (*). The mutable reference goes // out of scope at the end of the for loop, so all of these changes are safe and allowed by the borrowing rules. // By default, HashMap uses a “cryptographically strong”1 hashing function that can provide resistance to Denial of Service // (DoS) attacks. This is not the fastest hashing algorithm available, but the trade-off for better security that comes with // the drop in performance is worth it. If you profile your code and find that the default hash function is too slow for your // purposes, you can switch to another function by specifying a different hasher. A hasher is a type that implements the // BuildHasher trait. We’ll talk about traits and how to implement them in Chapter 10. You don’t necessarily have to // implement your own hasher from scratch; crates.io has libraries shared by other Rust users that provide hashers implementing // many common hashing algorithms.
C++
UTF-8
3,796
3.25
3
[]
no_license
#include "shape.h" Shape::Shape(int shape, int psize) { std::cout << "shape constructor" << std::endl; switch(shape) { case CIRCLE: setCircleShape(psize); size = psize; break; default : break; } } Shape::Shape(const Shape &pshape) { size = pshape.size; lefthalfsize = pshape.lefthalfsize; righthalfsize = pshape.righthalfsize; onescounted = pshape.onescounted; matrix = (bool*)malloc(sizeof(bool)*size*size); for(int offset = 0; offset<size*size; offset++) { *(matrix+offset) = *(pshape.matrix+offset); } } Shape::~Shape() { std::cout << "destructor of shape" << std::endl; free(matrix); } void Shape::setCircleShape(int psize) { matrix = (bool*)malloc(sizeof(bool)*psize*psize); for(int i = 0; i<psize*psize; i++) *(matrix+i) = 0; lefthalfsize = (psize/2)-1; int tmpVal = 0; onescounted = 0; float x, y; if(psize%2 == 0) { righthalfsize = lefthalfsize+1; //iteration over the width for(int w = 0; w<=lefthalfsize; w++) { x = 0.5+w; //iteration over the height for(int h = 0; h<=lefthalfsize; h++) { y = 0.5+h; tmpVal = ((x*x)+(y*y)) <= psize*psize/4 ? 1 : 0; *(matrix + (lefthalfsize-h)*psize + (lefthalfsize-w)) = tmpVal; *(matrix + (lefthalfsize-h)*psize + (righthalfsize+w)) = tmpVal; *(matrix + (righthalfsize+h)*psize + (lefthalfsize-w)) = tmpVal; *(matrix + (righthalfsize+h)*psize + (righthalfsize+w)) = tmpVal; if(tmpVal) onescounted += 4; } } } else { righthalfsize = lefthalfsize+2; //iteration over the width for(int w = 0; w<psize/2; w++) { x = 1+w; //iteration over the height for(int h = 0; h<psize/2; h++) { y = 1+h; tmpVal = (((x*x)+(y*y)) <= psize*psize/4) ? 1 : 0; *(matrix + (lefthalfsize-h)*psize + (lefthalfsize - w)) = tmpVal; *(matrix + (lefthalfsize-h)*psize + (righthalfsize + w)) = tmpVal; *(matrix + (righthalfsize+h)*psize + (lefthalfsize - w)) = tmpVal; *(matrix + (righthalfsize+h)*psize + (righthalfsize + w)) = tmpVal; if(tmpVal) onescounted += 4; } } int middle = (psize/2); for(int i = 0; i < middle; i++) { *(matrix + (middle*psize) + i) = 1; *(matrix + (i*psize) + middle) = 1; *(matrix + (middle*psize) + middle + i + 1) = 1; *(matrix + ((middle+i+1)*psize) + middle) = 1; } *(matrix + (middle*psize) + middle) = 1; } } //for ease : shapes with an even siz bool* Shape::getmatrix() { return matrix; } int Shape::getSize() { return size; } int Shape::getonescounted() { return onescounted; }
TypeScript
UTF-8
879
3.109375
3
[ "MIT" ]
permissive
export const generateMarkdownTemplate = ( serial: string, title: string, functionName: string, functionBody: string, ) => `--- id: ${serial}-${functionName} title: ${title} sidebar_label: ${serial}. ${title} keywords: - HashMap --- :::success Tips 题目类型: HashMap 相关题目: - [1. 两数之和](/leetcode/easy/1-two-sum) ::: ## 题目 这里是题目这里是题目这里是题目这里是题目这里是题目 :::note 提示: - xxxxxxxxx ::: :::info 示例 输入: 输出: ::: ## 题解 这里是题解这里是题解这里是题解这里是题解这里是题解 import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem' <Tabs> <TabItem value="JavaScript" label="JavaScript" default> \`\`\`ts ${functionBody} \`\`\` </TabItem> <TabItem value="Rust" label="Rust"> \`\`\`rust pub fn foo() -> () { } \`\`\` </TabItem> </Tabs> `
Python
UTF-8
1,602
2.65625
3
[]
no_license
from django.db import models from django.contrib.auth.models import User from di import resolve class TodoTitleGenerator: def __init__(self, title_prefix, now): ''' Another example of DI. We use this class to generate titles for todos. __init__ will be called once on application startup ''' self.title_prefix = title_prefix self.now = now def __call__(self): ''' This method is required, because models.CharField default arg expects a callable ''' return '{}-{}'.format(self.title_prefix, self.now()) class TodoManager(models.Manager): def get_all_todos(self): return super().get_queryset() def get_user_todos(self, owner_id): return super().get_queryset().filter(owner_id=owner_id) def get_user_todos_count(self, owner_id): return super().get_queryset().filter(owner_id=owner_id).count() class Todo(models.Model): title = models.CharField(max_length=200, default=resolve(TodoTitleGenerator)) due_date = models.DateTimeField(null=True, blank=True) owner = models.OneToOneField(User, on_delete=models.CASCADE) objects = TodoManager() def is_overdue(self): # this method is not testable unless you use # FreezeGun or simiar to mock datetime from datetime import datetime return self.due_date > datetime.now() class TodoService: def __init__(self, now_fn): self.now_fn = now_fn def is_overdue(self, todo): return todo.due_date > self.now_fn()
Markdown
UTF-8
3,423
3.703125
4
[ "MIT" ]
permissive
# JavaScript 101<br />Variables --- ## Variables - JavaScript variables hold values or expressions. - A variable can be a short name like `x` or a descriptive name like `myFirstName`. - Variables are case sensitive so `y` is different than `Y`. - A variable must start with a letter, $, _ and cannot contain any mathematical operators. --- ## Variables #### Creating var x; var y; var a = "SomeValue", b = 1234; - You can declare variables with or without a value. The `x` and `y` variables declared here will have a null value. - You can use the `var` keyword multiple times or set several variables with a single `var` declaration. - __Note:__ A single `var` declaration for setting multiple variables has faster performance, multiple `vars` are easier to read. - Redeclaring a variable will cause it to loose its existing value*. --- ## Variables #### Scope - Unlike other programming languages any variable created without var keyword will exist in the global namespace. - This can cause problems when creating client-side scripts. - When calling a variable JavaScript will check the local namespace and move up to the global namespace if it's not found. --- ## Variables #### Scope .runnable var sy = "Hello "; function say(name) { var str = sy + name; console.log(str); ex = "Hello"; } say("Splinter"); console.log("The variable str is: " + typeof str + " and the variable sy is: " + typeof sy + " and the variable ex is: " + typeof ex); --- ## Variables #### Scope - ### Global - All variables created without the var keyword will exist in the global namespace. - In a browser context global variables will be deleted when the window is closed. - ### Local - Variables created in functions will be deleted once the function is executed. - A variable can only be accessed within the given function. - Local variables in different functions can have the same name. --- ## Variables #### Mathematical Operators .runnable var v = 3 x = 6, y = 9, a = "(x + y) * v = "; console.log(a+((y+x)*v)); - You can perform mathematical operations on variables. - Since JavaScript is loosely typed you can concatenate strings using same operators. - Visit: http://www.w3schools.com/js/js_operators.asp for full list of operators. --- ## Variables #### Comparison Operators .runnable var v = "Teenage Mutant Ninja Turtles"; if( v == "Teenage Mutant Ninja Turtles" ) { console.log("That is the best cartoon ever!"); } else { console.log("I'm sorry, did you mean to say " + v + "?"); } - Comparison operators are used in logical statements to determine equality or difference between variables. - They can be used in conditional statements that will take action if criteria is met or not. - == Allows you to check equality and === checks for exactness (value and type). - Visit: http://www.w3schools.com/js/js_comparisons.asp for full list of comparison operators. --- ## Variables #### Assignment Operators Used to assign values to variables. .runnable var v = 5; console.log(typeof v); console.log(v); console.log(v+=4); console.log(v-=7); console.log(v+=" String"); console.log(typeof v); --- ## Variables #### Logical Operators Used to determine the logic between variables or values. .runnable var v = 5; if( v == 5 || !isNaN(v) ) { console.log("This matches."); } else { console.log("This doesn't match."); }
Java
UTF-8
812
1.898438
2
[]
no_license
package com.tchyon.reviewapp.controller; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) public class UserTests { @Autowired private MockMvc mockMvc; @Test public void testAppRunning3() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/hello") .accept(MediaType.ALL)) .andExpect(status().is2xxSuccessful()); } }
PHP
UTF-8
8,547
2.75
3
[]
no_license
<?php $display = 'hide'; // Função para somar as parcelas das despesas function SomarData($data, $dias, $meses, $ano){ // A data deve estar no formato dd/mm/yyyy $data = explode("/", $data); $nova_data = date("d/m/Y", mktime(0, 0, 0, $data[1] + $meses, $data[0] + $dias, $data[2] + $ano) ); return $nova_data; } // Evento cadastrar despesa if(isset($_POST['btncadastrar']) && $_POST['btncadastrar'] == 1){ //echo "<pre>"; //print_r($_POST); //break; $tipo_despesa_id = $_POST['tipo_despesa_id']; // Tipo de despesa $array = explode("/", $_POST['data_despesa']); $data_despesa = "$array[2]-$array[1]-$array[0]"; // Data de despesa $array = explode("/", $_POST['data_vencimento']); $data_vencimento = "$array[2]-$array[1]-$array[0]"; // Data de vencimento $mes = $array[1]; $ano = $array[2]; // Mes - Ano $array = explode("/", $_POST['data_pagamento']); $data_pagamento = "$array[2]-$array[1]-$array[0]"; // Data de pagamento $descricao = addslashes($_POST['descricao']); // Descricao $valor = $_POST['valor']; // Valor $parcelado = $_POST['parcelado']; // Parcelado $total_parcela = (int)$_POST['total_parcela']; // Numero total de parcela $conta_fixa = $_POST['conta_fixa']; // Parcela fixa $conta_paga = $_POST['conta_paga']; // Conta paga $forma_pagamento_id = $_POST['forma_pagamento_id']; // Forma de pagamento $cartoes_id = (int)$_POST['cartoes_id']; // Cartao de credito/debito $obs = addslashes($_POST['obs']); // Observações // Caso escolha pago não e data pgto sim, zera o conteudo da data pgto if($conta_paga == 'N') $data_pagamento = ''; // Caso usuario escolha parcelado e conta fixa vai prevalecer a conta fixa if($conta_fixa == 'S') $parcelado = 'N'; if(($descricao == "") || ($valor == "")){ $alert = "danger"; $icon = "times"; $msg = "<strong>Erro!</strong> Existem campos obrigatórios a serem preenchidos."; } else{ // Pega o valor remove os pontos e substitui a virgula pelo ponto $source = array('.', ','); $replace = array('', '.'); $valor = str_replace($source, $replace, $valor); // Conta fixa if($conta_fixa == 'S'){ // Seta as variaveis igual a zero... $total_parcela = 0; $numero_parcela = 0; // Insere na tabela copag $insert = $conectar->prepare("INSERT INTO copag VALUES ('',?,?,?,?,?,?,?,?,now())") or die (mysqli_error($conectar)); $insert->bind_param('iiisssss', $usuarioID, $tipo_despesa_id, $forma_pagamento_id, $data_despesa, $descricao, $parcelado, $total_parcela, $conta_fixa); $insert->execute(); // Pega o ultimo ID inserido $ultimo_id = $insert->insert_id; // Cadastra 12 vezes a despesa for($x = 1; $x <= 12; $x++){ if($x == 1){ // Data de vencimento original $nova_data = explode("/", $_POST['data_vencimento']); } else{ // Calcula a nova data do vencimento $nova_data = explode("/", SomarData($_POST['data_vencimento'], 0, $x - 1, 0)); } $nova_data_vencimento = "$nova_data[2]-$nova_data[1]-$nova_data[0]"; $ano = "$nova_data[2]"; $mes = "$nova_data[1]"; // Insere na tabela parcelas $insert = $conectar->prepare("INSERT INTO parcelas VALUES ('',?,?,?,?,?,?,?,?,?)") or die (mysqli_error($conectar)); $insert->bind_param('issssssss', $ultimo_id, $nova_data_vencimento, $ano, $mes, $valor, $numero_parcela, $obs, $conta_paga, $data_pagamento); $insert->execute(); if($cartoes_id != ''){ $insertCartao = $conectar->prepare("INSERT INTO cartoes_has_copag VALUES (?,?)") or die (mysqli_error($conectar)); $insertCartao->bind_param('ii', $cartoes_id, $ultimo_id); $insertCartao->execute(); } } // fim do for if($insert == true){ $alert = "success"; $icon = "check"; $msg = "<strong>Feito!</strong> Cadastro realizado com sucesso."; } else{ $alert = "danger"; $icon = "times"; $msg = "<strong>Ops!</strong> Houve um erro para realizar o cadastro."; } } // fim do if // Conta parcelada elseif($parcelado == 'S'){ // Insere na tabela copag $insert = $conectar->prepare("INSERT INTO copag VALUES ('',?,?,?,?,?,?,?,?,now())") or die (mysqli_error($conectar)); $insert->bind_param('iiisssss', $usuarioID, $tipo_despesa_id, $forma_pagamento_id, $data_despesa, $descricao, $parcelado, $total_parcela, $conta_fixa); $insert->execute(); // Pega o ultimo ID inserido $ultimo_id = $insert->insert_id; // Cadastra conforme o numero de parcelas de entrada for($x = 1; $x <= $total_parcela; $x++){ $numero_parcela = $x; if($x == 1){ // Data de vencimento original $nova_data = explode("/", $_POST['data_vencimento']); } else{ // Calcula a nova data do vencimento $nova_data = explode("/", SomarData($_POST['data_vencimento'], 0, $x - 1, 0)); } $nova_data_vencimento = "$nova_data[2]-$nova_data[1]-$nova_data[0]"; $ano = "$nova_data[2]"; $mes = "$nova_data[1]"; // Insere na tabela parcelas $insert = $conectar->prepare("INSERT INTO parcelas VALUES ('',?,?,?,?,?,?,?,?,?)") or die (mysqli_error($conectar)); $insert->bind_param('issssssss', $ultimo_id, $nova_data_vencimento, $ano, $mes, $valor, $numero_parcela, $obs, $conta_paga, $data_pagamento); $insert->execute(); if($cartoes_id != ''){ $insertCartao = $conectar->prepare("INSERT INTO cartoes_has_copag VALUES (?,?)") or die (mysqli_error($conectar)); $insertCartao->bind_param('ii', $cartoes_id, $ultimo_id); $insertCartao->execute(); } } // fim do for if($insert == true){ $alert = "success"; $icon = "check"; $msg = "<strong>Feito!</strong> Cadastro realizado com sucesso."; } else{ $alert = "danger"; $icon = "times"; $msg = "<strong>Ops!</strong> Houve um erro para realizar o cadastro."; } } // fim do elseif // Caso seja uma despesa normal (sem parcelas e não fixa) else{ // Seta as variaveis igual a zero... $total_parcela = 0; $numero_parcela = 0; // Insere na tabela copag $insert = $conectar->prepare("INSERT INTO copag VALUES ('',?,?,?,?,?,?,?,?,now())") or die (mysqli_error($conectar)); $insert->bind_param('iiisssss', $usuarioID, $tipo_despesa_id, $forma_pagamento_id, $data_despesa, $descricao, $parcelado, $total_parcela, $conta_fixa); $insert->execute(); // Pega o ultimo ID inserido $ultimo_id = $insert->insert_id; // Insere na tabela parcelas $insert = $conectar->prepare("INSERT INTO parcelas VALUES ('',?,?,?,?,?,?,?,?,?)") or die (mysqli_error($conectar)); $insert->bind_param('issssssss', $ultimo_id, $data_vencimento, $ano, $mes, $valor, $numero_parcela, $obs, $conta_paga, $data_pagamento); $insert->execute(); if($cartoes_id != ''){ $insertCartao = $conectar->prepare("INSERT INTO cartoes_has_copag VALUES (?,?)") or die (mysqli_error($conectar)); $insertCartao->bind_param('ii', $cartoes_id, $ultimo_id); $insertCartao->execute(); } if($insert == true){ $alert = "success"; $icon = "check"; $msg = "<strong>Feito!</strong> Cadastro realizado com sucesso!!."; } else{ $alert = "danger"; $icon = "times"; $msg = "<strong>Ops!</strong> Houve um erro para realizar o cadastro."; } } // fim do else } // fim do else $display = 'show'; } // fim do if // Query busca tipo de despesas $sqlTipoDespesa = $conectar->prepare("SELECT tipo_despesa_id, descricao FROM view_tipo_despesa WHERE usuarios_id = ? ORDER BY descricao") or die (mysqli_error($conectar)); $sqlTipoDespesa->bind_param('i', $usuarioID); $sqlTipoDespesa->execute(); $sqlTipoDespesa->store_result(); $sqlTipoDespesa->bind_result($id, $descricao); // Query busca forma de pagamentos $sqlPagamentos = $conectar->prepare("SELECT forma_pagamento_id, descricao FROM view_forma_pagamento WHERE usuarios_id = ? ORDER BY descricao") or die (mysqli_error($conectar)); $sqlPagamentos->bind_param('i', $usuarioID); $sqlPagamentos->execute(); $sqlPagamentos->store_result(); $sqlPagamentos->bind_result($id, $descricao); // Query busca ultimas despesas cadastradas $sqlUltimas = $conectar->prepare(" SELECT descricao, data_vencimento, valor, desc_forma_pagamento, desc_cartao FROM view_copag WHERE usuarios_id = ? GROUP BY copag_id ORDER BY data_cadastro DESC LIMIT 5 ") or die (mysqli_error($conectar)); $sqlUltimas->bind_param('i', $usuarioID); $sqlUltimas->execute(); $sqlUltimas->store_result(); $sqlUltimas->bind_result($descricao, $data_vencimento, $valor, $desc_forma_pagamento, $desc_cartao); ?>
Markdown
UTF-8
1,288
2.59375
3
[ "MIT" ]
permissive
--- layout: post title: "Softmax GAN" date: 2017-04-20 15:35:14 categories: arXiv_CV tags: arXiv_CV Adversarial GAN Classification author: Min Lin mathjax: true --- * content {:toc} ##### Abstract Softmax GAN is a novel variant of Generative Adversarial Network (GAN). The key idea of Softmax GAN is to replace the classification loss in the original GAN with a softmax cross-entropy loss in the sample space of one single batch. In the adversarial learning of $N$ real training samples and $M$ generated samples, the target of discriminator training is to distribute all the probability mass to the real samples, each with probability $\frac{1}{M}$, and distribute zero probability to generated data. In the generator training phase, the target is to assign equal probability to all data points in the batch, each with probability $\frac{1}{M+N}$. While the original GAN is closely related to Noise Contrastive Estimation (NCE), we show that Softmax GAN is the Importance Sampling version of GAN. We futher demonstrate with experiments that this simple change stabilizes GAN training. ##### Abstract (translated by Google) ##### URL [https://arxiv.org/abs/1704.06191](https://arxiv.org/abs/1704.06191) ##### PDF [https://arxiv.org/pdf/1704.06191](https://arxiv.org/pdf/1704.06191)
Java
UTF-8
526
2.15625
2
[]
no_license
package cn.hal.code.algorithm; import org.springframework.stereotype.Component; /** * @Author: Steven HUANG * @Date: 2020/3/31 * * topic: * url: * * desc: * * 样例: * 例1: * * * * 例2: * * * * 知识点 * */ @Component public class Title { /** * 空间 :O(n) ; 时间: O(n) */ public void solution1() { } /** * 空间 :O(n) ; 时间: O(n) */ public void solution2() { } /** * 空间 :O(n) ; 时间: O(n) */ public void solution3() { } }
Markdown
UTF-8
2,645
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
--- title: "Freeway Traffic Incident Detection from Cameras: A Semi-Supervised Learning Approach" excerpt: "We used semi-supervised techniques to detect traffic incident trajectories from the cameras. Our proposed approach for trajectory classification is based on semi-supervised parameter estimation using maximum-likelihood (ML) estimation. Results show that approximately 14% improvement in trajectory classification can be achieved using the proposed approach compared to baseline algorithms. <br/><img src='/images/cple-image.jpg'>" collection: portfolio --- **Pranamesh Chakraborty**, Anuj Sharma, Chinmay Hegde To appear in [IEEE Intelligent Transportation Systems Conference, 2018](https://www.ieee-itsc2018.org/) ![GitHub Logo](/images/cple-image.jpg) **Abstract:** Early detection of incidents is a key step to reduce incident related congestion. State Department of Transportation (DoTs) usually install a large number of Close Circuit Television (CCTV) cameras in freeways for traffic surveillance. In this study, we used semi-supervised techniques to detect traffic incident trajectories from the cameras. Vehicle trajectories are identified from the cameras using state-of-the-art deep learning based You Look Only Once (YOLOv3) classifier and Simple Online Realtime Tracking (SORT) is used for vehicle tracking. Our proposed approach for trajectory classification is based on semi-supervised parameter estimation using maximum-likelihood (ML) estimation. The ML based Contrastive Pessimistic Likelihood Estimation (CPLE) attempts to identify incident trajectories from the normal trajectories. We compared the performance of CPLE algorithm to traditional semi-supervised techniques Self Learning and Label Spreading, and also to the classification based on the corresponding supervised algorithm. Results show that approximately 14% improvement in trajectory classification can be achieved using the proposed approach. # Methodology ## Vehicle Detection and Tracking We used YOLOv3 for vehicle detection and SORT for tracking purpose. <img src="/images/cple-track.png" alt="drawing" align="middle" width="400"/> ## Incident Trajectory Classification Trajectory classification is based on semi-supervised CPLE and its accuracy is compared with baseline algorithms. <img src="/images/cple-acc-comp.png" alt="drawing" width="400"/> **Citation**: P. Chakraborty, A. Sharma, and C. Hegde. Freeway Traffic Incident Detection from Cameras: A Semi-Supervised Learning Approach, IEEE Conference on Intelligent Transportation Systems (ITSC), November 2018. [Pdf](https://pranamesh.github.io/files/2018-IEEE-ITSC-draft.pdf), [Video](https://youtu.be/KhcdOXa29bo)
Python
UTF-8
4,932
3.203125
3
[ "MIT" ]
permissive
"""The entry point and controller for display code. Elements in the game world or in the user interface construct windows (see window.py), matrixes of information about what they want to show in a region they own. This module composites them into a single image and then uses the blessed library to print that image to the terminal screen each frame. This module also contains functions controlling window interaction and organization, e.g., passing input to interactive menus and popping up and dismissing submenus. """ import typing as t import rich import env import space import util import window win_stack: t.List[window.Window] = [] input_sink_stack: t.List[t.Any] = [] # TODO? more correct to have List[OverarchingWidgetClass] here def render() -> None: """Composite live windows to a screen.""" screen_to_render: env.Screen = [[" "] * env.term_width for _ in range(env.term_height)] num_of_cells_to_render: int = env.term_height * env.term_width rendered: t.List[t.List[bool]] = [[False] * env.term_width for _ in range(env.term_height)] for p in reversed(win_stack): num_of_cells_to_render -= p.render(rendered, screen_to_render) if num_of_cells_to_render <= 0: break print_screen(screen_to_render) def print_screen(screen_to_render: env.Screen) -> None: """Print a screen on terminal.""" with env.term.location(0, 0): rich.print("\n".join(["".join(i) for i in screen_to_render])) def show_main_menu() -> None: """Pause game when the player hits Esc at game world.""" env.paused = True def unpause() -> None: """Toggle unpausing of game.""" env.paused = False def end_game() -> None: """Stop main game loop.""" env.game_over = True def controls() -> None: """Shows Controls.""" do_display = True controls: window.TextWidget = window.TextWidget( [ window.TextWidgetEntry("Controls", "blue"), window.TextWidgetEntry("Left Arrow: Left", "blue"), window.TextWidgetEntry("Right Arrow: Right", "blue"), window.TextWidgetEntry("Save Game: Delete Key", "blue"), window.TextWidgetEntry("Load Save: Backspace", "blue"), window.TextWidgetEntry("Select On Menu: Enter", "blue"), window.TextWidgetEntry("Go To Menu: Escape", "blue") ], center_entries=True, maximize=False ) while do_display: controlwindow = controls.make_window() global win_stack win_stack = [controlwindow] render() inp = env.term.inkey(timeout=0) inp_s = inp.name if inp_s == "KEY_ESCAPE": return main_menu: window.Menu = window.Menu([window.MenuEntry("Play", "blue", True, unpause), window.MenuEntry("Options", "blue"), window.MenuEntry("See Controls", "blue", True, controls), window.MenuEntry("Quit", "blue", True, end_game)], maximize=False, center_entries=True) input_sink_stack.append(main_menu) # start with this open def process_input(keypress: str) -> None: """Receive input to pass to a menu or interface object. TODO: this needs to do the part that's not just passing input on, too! """ util.assert_(len(input_sink_stack) > 0) if keypress == "KEY_ESCAPE": input_sink_stack.pop() if len(input_sink_stack) == 0: unpause() else: input_sink_stack[-1].process_input(keypress) def display(world: list) -> None or list: """Entry point into displaying on the terminal screen.""" global win_stack if env.paused: # Menu displayer main_menu_window = main_menu.make_window() logo = [list(line) for line in env.logo.split("\n")[1:-1]] logo[-1].append("\n") logo_origin = space.Point(main_menu_window.origin.y-8, int(main_menu_window.origin.x-3*len(logo[0])/10)) # Centers the logo. logo_window = window.Window.from_origin(logo_origin, logo) win_stack = [logo_window, main_menu_window] else: # Game displayer root_window = window.Window.from_origin(space.Point(0, 0), util.convert_data(world)) display_hits = env.hits - 4 if env.hits > 4 else 0 info_widget = window.TextWidget([window.TextWidgetEntry(f"Level #{env.level_num}"), window.TextWidgetEntry(f"Lives: {display_hits}")], maximize=False) info_window = info_widget.make_window(space.Point(0, root_window.bottom.x + 10)) win_stack = [root_window, info_window] render() return world if 'world' in locals() else None
Python
UTF-8
4,963
2.765625
3
[]
no_license
import numpy as np import sys, random, pdb def load_mnist(path, kind='train'): import os import gzip import numpy as np """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels-idx1-ubyte' % kind) images_path = os.path.join(path, '%s-images-idx3-ubyte' % kind) with open(labels_path, 'rb') as lbpath: labels = np.frombuffer(lbpath.read(), dtype=np.uint8, offset=8) with open(images_path, 'rb') as imgpath: images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels), 784) return images, labels def loss(w,x,y): op = y*np.dot(w,x) return op def pegasos(data,labels,T,lamda=1.0): S = len(data) w = np.zeros((data[0].shape[0])) for k in range(1,T): i = random.randrange(S) step = 1/(k*lamda) if loss(w,data[i],labels[i])<1: w1 = ((1-step*lamda)*w)+step*data[i]*labels[i] elif loss(w,data[i],labels[i])>=1: w1 = ((1-step*lamda)*w) tt = (1/np.sqrt(lamda)/np.linalg.norm(w1)) w1 = min(1,tt)*w1 w = w1 return w def create_train_data(X_train, y_train, labels): X_train_binary=[] y_train_binary=[] for k in range(0,y_train.shape[0]): if y_train[k]==labels[0]: X_train_binary.append(X_train[k]) y_train_binary.append(1) elif y_train[k]==labels[1]: X_train_binary.append(X_train[k]) y_train_binary.append(-1) print("Number of train set samples for binary case :",len(X_train_binary)) return X_train_binary, y_train_binary def create_test_data(X_test, y_test, labels): X_test_binary =[] y_test_binary =[] for j in range(0,y_test.shape[0]): if y_test[j]==labels[0]: X_test_binary.append(X_test[j]) y_test_binary.append(labels[0]) elif y_test[j]==labels[1]: X_test_binary.append(X_test[j]) y_test_binary.append(labels[1]) print("Number of test set samples for binary case :",len(X_test_binary)) return X_test_binary, y_test_binary def fit(X_train_binary, y_train_binary): w=pegasos(X_train_binary,y_train_binary,10000) return w def test(X_test_binary, y_test_binary, w): correct=0 for k in range(0,len(y_test_binary)): if np.dot(w,X_test_binary[k])<0 and y_test_binary[k]<0: correct+=1 elif np.dot(w,X_test_binary[k])>0 and y_test_binary[k]>0: correct+=1 acc = (correct*1.0/len(y_test_binary)) return acc def predict_label(X_test_binary, w): predicted = [] for k in range(0,len(X_test_binary)): pred = np.dot(w,X_test_binary[k]) if pred < 0: predicted.append(-1) else: predicted.append(1) return predicted def predict_class(predicted_labels, labels): for i in range(len(predicted_labels)): if predicted_labels[i] == 1: predicted_labels[i] = labels[0] else: predicted_labels[i] = labels[1] return predicted_labels def voting(lab1, lab2, lab3, labels): final_pred = [] for i in range(len(lab1)): temp = [lab1[i], lab2[i], lab3[i]] c1 = temp.count(labels[0]) c2 = temp.count(labels[1]) c3 = temp.count(labels[2]) if c1 == 1 and c2 == 1 and c3==1: final_pred.append(-1) elif c1 == max(c1,c2,c3): final_pred.append(labels[0]) elif c2 == max(c1,c2,c3): final_pred.append(labels[1]) elif c3 == max(c1,c2,c3): final_pred.append(labels[2]) return final_pred def calc_acc(pred, gt): correct = 0 for i in range(len(gt)): if pred[i] == gt[i]: correct = correct+1 acc = (correct*1.0)/len(gt) return acc X_train, y_train = load_mnist('fashionmnist/', kind='train') X_test, y_test = load_mnist('fashionmnist/', kind='t10k') # THIS IS FOR CLASS 1 vs 2 X_train_binary, y_train_binary = create_train_data(X_train, y_train, [1,2]) X_test_binary, y_test_binary = create_test_data(X_test, y_test, [1,2]) test = X_test_binary test_labels = y_test_binary test=np.array(test) test_labels = np.array(test_labels) w12 = fit(X_train_binary, y_train_binary) X_train_binary, y_train_binary = create_train_data(X_train, y_train, [2,3]) X_test_binary, y_test_binary = create_test_data(X_test, y_test, [2,3]) test = np.append(test, X_test_binary, axis=0) test_labels = np.append(test_labels, y_test_binary, axis=0) w23 = fit(X_train_binary, y_train_binary) # THIS IS FOR CLASS 1 vs 3 X_train_binary, y_train_binary = create_train_data(X_train, y_train, [1,3]) X_test_binary, y_test_binary = create_test_data(X_test, y_test, [1,3]) test = np.append(test, X_test_binary, axis=0) test_labels = np.append(test_labels, y_test_binary, axis=0) w13 = fit(X_train_binary, y_train_binary) pred12 = predict_label(test, w12) pred12 = predict_class(pred12, [1,2]) pred23 = predict_label(test,w23) pred23 = predict_class(pred23, [2,3]) pred13 = predict_label(test, w13) pred13 = predict_class(pred13, [1,3]) final_pred = voting(pred12, pred23, pred13, [1,2,3]) acc = calc_acc(final_pred, test_labels) print ("Accuracy: " + str(acc))
Markdown
UTF-8
3,725
2.515625
3
[]
no_license
Data Is Plural — 2020.05.20 edition =================================== *Excess deaths, trade agreements, US forests, historical crop yields, and Victorian fiction.* __Excess deaths.__ The Economist has published [the data](https://github.com/TheEconomist/covid-19-excess-deaths-tracker) behind its [estimates of excess deaths due to COVID-19](https://www.economist.com/graphic-detail/2020/04/16/tracking-covid-19-excess-deaths-across-countries). The data repository currently covers 20 countries; it provides recent weekly/monthly death totals, officially-counted COVID-19 death, and average historical death totals for the same time periods. __Related__: [Data journalist James Tozer’s introductory Twitter thread](https://twitter.com/J_CD_T/status/1261625814854045696). [h/t [Sharon Machlis](https://twitter.com/sharon000/status/1262029159976574976)] __Trade agreements.__ The [Design of Trade Agreements](https://www.designoftradeagreements.org) database collects information about customs unions, free trade agreements, and other similar treaties signed between 1948 and 2018. It currently includes more than 800 agreements, plus additional negotiations, accessions, withdrawals, consolidations, and amendments. For each agreement, the database indicates the its name, member countries, year of signature, and [a number of policy-specific variables](https://www.designoftradeagreements.org/downloads/). [h/t [Erik Gahner Larsen](https://github.com/erikgahner/PolData/)] __US forests.__ The US Department of Agriculture’s [National Forest Type Dataset](https://data.fs.usda.gov/geodata/rastergateway/forest_type/) shows the geographic distribution of the country’s “forest types” — defined as ”logical ecological groupings of species mixes.” (Examples include “deciduous oak woodland” and “subalpine fir.”) To estimate the extent of each forest type, the dataset’s developers combined satellite imagery with “nearly 100 other geospatial data layers, including elevation, slope, aspect, and ecoregions.” __Related__: The Washington Post has used the dataset to [map fall foliage](https://wapo.st/peep-these-leaves) and [forests where Christmas-y trees grow](https://www.washingtonpost.com/nation/2019/12/12/where-christmas-trees-come/). [h/t [Joe Fox](https://twitter.com/joemfox)] __Historical crop yields.__ The [Global Dataset of Historical Yields](https://doi.pangaea.de/10.1594/PANGAEA.909132) combines data from agricultural censuses and satellite sensors to estimate the annual yields for four major crops — maize, rice, wheat, and soybean — annually from 1981 to 2016, for each 0.5-degree square on the planet. __Related__: [The dataset’s authors describe their methodology and the latest update](https://www.nature.com/articles/s41597-020-0433-7). __Victorian fiction.__ [At the Circulating Library](https://www.victorianresearch.org/atcl/index.php) “offers a biographical and bibliography database of nineteenth-century British fiction.” Launched by literature professor [Troy J. Bassett](https://twitter.com/3VolumeNovel) in 2007, the [searchable](https://www.victorianresearch.org/atcl/search.php), [browseable](https://www.victorianresearch.org/atcl/view_authors.php), [downloadable](http://www.victorianresearch.org/atcl/snapshots.php) database now contains information on more than 19,000 titles by more than 4,000 authors. *Dataset suggestions? Criticism? Praise? Send Dickensian feedback to jsvine@gmail.com, or just reply to this email. Looking for past datasets? [This spreadsheet contains them all](https://docs.google.com/spreadsheets/d/1wZhPLMCHKJvwOkP4juclhjFgqIY8fQFMemwKL2c64vk). Did a friend forward you this email? [Click here to subscribe](https://tinyletter.com/data-is-plural).*
C++
UTF-8
1,122
2.796875
3
[ "MIT" ]
permissive
#ifndef TX_DSCATTACHEDPASSPORTCOUNTER_H #define TX_DSCATTACHEDPASSPORTCOUNTER_H #include <cstdint> #include <vector> #include "Serialization/serialize.h" class DSCAttachedPassportCounter { public: static bool increment(std::vector<unsigned char> dscId); static bool decrement(std::vector<unsigned char> dscId); static uint64_t getCount(std::vector<unsigned char> dscId); }; struct DSCAttachedPassportCount{ uint32_t count; inline DSCAttachedPassportCount& operator=(const DSCAttachedPassportCount& other){ count = other.count; return *this; } inline DSCAttachedPassportCount& operator=(const uint32_t other){ count = other; return *this; } DSCAttachedPassportCount operator++(int) { count++; return *this; } DSCAttachedPassportCount operator--(int) { count--; return *this; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(count); } }; #endif //TX_DSCATTACHEDPASSPORTCOUNTER_H
JavaScript
UTF-8
189
3.25
3
[]
no_license
const valor = 'Global' function exibe(){ return valor } function exec(){ const valor = 'Local' return exibe() } // Global console.log(exibe()); // Global console.log(exec());
Markdown
UTF-8
5,811
3.125
3
[]
no_license
--- id: domain_gameserver_srv_link title: Domains: Set up game server forwarding description: Information on how to set up a forwarding from your domain to a game server - ZAP-Hosting.com documentation sidebar_label: Domain Gameserver Redirect --- > Please note that it can always take up to 24 hours before changes to DNS entries become active! ## Forward domain to game server You can either redirect your domain completely, or only a subdomain to your game server. So nobody has to remember the complicated IP address which consists of numbers, but can simply connect to your game server using the domain. In the following examples, create two subdomains and forward them to a Minecraft and a FiveM game server. ## How does it work? ### Before we start creating entries in the DNS settings of the domain, here is some information in advance: For the forwarding of the IP address either a subdomain is created which redirects to the IP address of the game server, or you forward the complete domain without subdomain. This would be sufficient if the game server uses the default port of the game. If the game server uses a different port than the standard port of the game, an additional **SRV entry** is created. is required to forward the subdomain to the correct port. > Not all games support the forwarding of a domain to the game port via SRV entry, so check in advance if your game supports SRV entries. ### SRV Service The service name depends on the game and always starts with a **underscore**. For example, the service name for a Minecraft game server is always **_minecraft** and for a FiveM game server **_cfx**. ### SRV Protocol As protocol we specify the Internet protocol used for the connection. Here **UDP** and **TCP** are available. Which protocol is used here also depends on the game, the specification of the protocol also always starts with an **underscore** and is either **_udp** or **_tcp**. ## Forwarding the domain without subdomain To forward your domain to a game server without creating a subdomain, first open your domain by on the dashboard, then open DNS Management from the menu on the left. ![](https://puu.sh/Fuzfa/0927cbb177.png) ![](https://puu.sh/FuzhO/6f4694ab62.png) There you will see all existing DNS entries for your domain. If you have not yet created your own entries there, you can view all existing entries by clicking on the red trash can on the right side. ![](https://puu.sh/Fuzm8/39f3c72fa6.png) Then click **New record** and you will be taken to the creation of a new DNS record. As **Name** we choose here the name of the domain, as an example **fivem-server.de**, the **type is A** and the **value** is the pay IP of your game server, in this case **88.214.57.116**. You can leave the field **TTL** untouched. ![](https://puu.sh/Fuzsi/3bbe761892.png) If you have all your entries, click on **Save**, the entry will be saved in the DNS settings and will be saved within of 24 hours. > It can always take up to 24 hours until new DNS entries become active. Unfortunately nobody has influence on this. ## Forwarding the domain with subdomain If you want to create a subdomain, for example minecraft.fivem-server.de, you do it like in the previous example, However, for **Name** you do not enter the name of the domain, but the subdomain. This looks like this: ![](https://puu.sh/Fuzxd/de90d297e8.png) ## Forwarding of the domain with game port (SRV) If the game port is not used, an additional **SRV entry** must be created to not only protect the domain to the IP of the game server but also to the correct port. First you either create a **subdomain** as described above, or you redirect the domain as described above directly to the game server, both is possible. ### Forwarding without subdomain After you have forwarded your domain to the IP address of your game server as described above, click on **New entry**. and create an entry that looks like this: ![](https://puu.sh/FuXZs/a4d7149643.png) The field **Name** contains the name of the service, which in this case is our Minecraft gameserver, so **_minecraft**. The protocol type is also specified there, in this case **_tcp** as well as the **domain name**. The field **Type** indicates what kind of entry it is, in this case it is a **SRV** entry. The field **value** contains the game port and the domain, in this case **0 2132 fivem-server.de**, where **2132** is the **port of the game** and **fivem-server.de** is the domain to which the redirection is done. The value **0** is no longer relevant and always remains the same. You also leave the field **TTL** untouched. Then you can click on **Save**. > It is important that in the field **value** at the end of the domain a **dot** is set! ### Forwarding with subdomain With a subdomain it behaves almost exactly the same. First you create a subdomain as described above and forward it to the IP address of your game server. Then click on **New entry** and create an entry with the following content: ![](https://puu.sh/FuYbj/423a8cb5eb.png) The field **Name** contains the name of the service, which in this case is our Minecraft gameserver, so **_minecraft**. The protocol type is also specified there, in this case **_tcp** as well as the **domain name** together with the **subdomain**, which is **minecraft.fivem-server.de**. The **Type** field indicates the type of entry, in this case it is a **SRV** entry. The field **Value** contains the game port and the domain with subdomain, in this case **0 2132 minecraft.fivem-server.de**, where **2132** is the **port of the game** and **minecraft.fivem-server.de** is the domain with subdomain to which the redirection is done. The value **0** is no longer relevant and always remains the same. The field **TTL** is also not affected.
Shell
UTF-8
1,260
4.0625
4
[ "MIT" ]
permissive
#!/bin/bash check() { hash $1 2>/dev/null || { echo >&2 "This needs \`$1\` to function properly. Please consule the poe-ui readme for more info."; exit 1; } } check git check npm check make if [[ $(ls -l | wc -l) -gt 1 ]]; then answer=Y read -e -p "project is not empty. abort? ($answer) " answer answer="${input:-$answer}" if [[ $answer == 'Y' ]]; then <&2 echo "aborting poe app creation" exit 1 fi fi PROJECT=`pwd | xargs basename` DESCRIPTION='A poe app' ORGANIZATION=`git config --get user.name` NG_VERSION=1.2.16 read -e -p "project: ($PROJECT) " input PROJECT="${input:-$PROJECT}" read -e -p "description: ($DESCRIPTION) " input DESCRIPTION="${input:-$DESCRIPTION}" read -e -p "organization: ($ORGANIZATION) " input ORGANIZATION="${input:-$ORGANIZATION}" FILENAME=`realpath $0 | xargs dirname` FILES=`realpath $FILENAME/../files` test ! -d $FILES && exit 1 for i in $(echo $FILES/* $FILES/.[!.]*); do cp -rf $i . done for i in $(find . -type f -maxdepth 3); do sed -e "s,PROJECT,$PROJECT," $i | \ sed -e "s,DESCRIPTION,$DESCRIPTION," | \ sed -e "s,REPO,$ORGANIZATION/$PROJECT," | \ sed -e "s,NG_VERSION,$NG_VERSION," > /tmp/poe cat /tmp/poe > $i done echo 'Installing dependencies...' npm install make start
PHP
UTF-8
1,095
2.90625
3
[ "MIT" ]
permissive
<?php namespace App; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; /** * Class Bookable * @package App * @property integer $id * @property integer $price * @property string $title * @property string $description * @property \Illuminate\Support\Carbon $created_at * @property \Illuminate\Support\Carbon $updated_at * */ class Bookable extends Model { public function bookings(): HasMany { return $this->hasMany(Booking::class); } public function availableFor($from, $to): bool { return $this->bookings()->betweenDates($from, $to)->count() === 0; } public function reviews(): HasMany { return $this->hasMany(Review::class); } public function priceFor($from, $to): PriceDto { $days = (new Carbon($from)) ->diffInDays(new Carbon($to)) + 1; // + 1 if somebody wants book for one day $totalPrice = $days * $this->price; return new PriceDto($totalPrice, [ $days => $this->price, ]); } }
Java
UTF-8
475
2.015625
2
[]
no_license
package DataProviders; import org.testng.annotations.DataProvider; public class LoginCredentialsProvider { @DataProvider(name = "Valid credentials") private Object[][] validCredentials(){ return new Object[][] { {"testseavusassignment@gmail.com", "Zlaja2019"}, }; } @DataProvider(name = "Invalid credentials") private Object[][] invalidCredentials(){ return new Object[][] { {"testseavusassignment@gmail.com", "Zlaja20"}, }; } }
C++
UTF-8
2,139
3.109375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <cstring> using namespace std; int arr[110][110]; int Place2(int n, int gap) { int res = 0; while (1) { int x, y; bool flag = true; for (int j = 0; flag && j < n; j++) { for (int i = 0; flag && i < n; i++) { if (arr[i][j] == 0) { res++; x = i; y = j; flag = false; break; } } } if (!flag) { arr[x][y] = 2; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[i][j] == 0 && abs(i - x) + abs(j - y) <= gap) arr[i][j] = 1; } } } else break; } return res; } int Place(int n, int gap) { int ret = 0; for (int i = 0; i < n; i++) { memset(arr, 0, sizeof(arr)); arr[0][i] = 2; for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (abs(j) + abs(k - i) <= gap) arr[j][k] = 1; } } ret = max(ret, Place2(n, gap) + 1); } return ret; } int solution(int n, int m, vector<vector<int>> timetable) { int answer = 0; vector<int> mark(1321, 0); for (auto i : timetable) { mark[i[0]]++; mark[i[1] + 1]--; } int with = 0, now = 0; for (int i = 0; i < mark.size(); i++) { now += mark[i]; with = max(with, now); } if (with <= 1) return 0; vector<int> gap(30); for (int i = 0; i < 30; i++) gap[i] = Place(n, i); while (gap[answer] >= with) answer++; return answer; } int main() { int n = 2; int m = 2; vector<vector<int>> timetable = { {600, 630}, {630, 700} }; cout << solution(n, m, timetable) << "\n"; return 0; }
C#
UTF-8
1,727
2.546875
3
[ "Apache-2.0" ]
permissive
using System; using System.Threading; using Ncqrs.EventBus; using Denormalizer.Properties; using Ncqrs.Eventing.Sourcing; using Ncqrs.Eventing.ServiceModel.Bus; namespace Denormalizer { static class Program { private static int _processedEvents = 0; private static InProcessEventBus _bus = new InProcessEventBus(true); static void Main(string[] args) { // Register all denormalizers in this assembly. _bus.RegisterAllHandlersInAssembly(typeof(Program).Assembly); var connectionString = Settings.Default.EventStoreConnectionString; var browsableEventStore = new MsSqlServerEventStoreElementStore(connectionString); var pipeline = Pipeline.Create(new CallbackEventProcessor(Process), browsableEventStore); pipeline.Start(); Console.ReadLine(); pipeline.Stop(); } static void Process(SourcedEvent evnt) { Thread.Sleep(200); Interlocked.Increment(ref _processedEvents); Console.WriteLine("Processing event {0} (id {1})", evnt.EventSequence, evnt.EventIdentifier); _bus.Publish(evnt); } } public class CallbackEventProcessor : IElementProcessor { private readonly Action<SourcedEvent> _callback; public CallbackEventProcessor(Action<SourcedEvent> callback) { _callback = callback; } public void Process(IProcessingElement evnt) { var typedElement = (SourcedEventProcessingElement) evnt; _callback(typedElement.Event); } } }
Java
UTF-8
893
2.171875
2
[]
no_license
package com.example.vsvll.intent_data; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class SecondPage extends AppCompatActivity { TextView textView; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity2); textView = findViewById(R.id.textView); button = findViewById(R.id.Sumbit); //here the Name convention should be same String Name = getIntent().getStringExtra("Name"); textView.setText("Hello "+Name+"!!"); } public void Click(View view) { Intent intent = new Intent(SecondPage.this,MainActivity.class); startActivity(intent); } }
Java
UTF-8
1,957
3.46875
3
[]
no_license
class Node1{ int data; Node1 left, right, parent; Node1(int d) { data=d; left=right=parent=null; } } class InorderSuccessor{ static Node1 head; Node1 insert(Node1 node, int data) { if (node==null) { return (new Node1(data)); } else { Node1 temp = null; if (data <= node.data) { temp = insert(node.left, data); node.left=temp; temp.parent=node; } else { temp = insert(node.right, data); node.right=temp; temp.parent=node; } return node; } } Node1 inOrderSuccessor(Node1 root, Node1 n) { if (n.right!=null) { return minValue(n.right); } Node1 p = n.parent; while (p != null && n == p.right) { n=p; p=p.parent; } return p; } Node1 minValue(Node1 node) { Node1 current = node; while (current.left != null) { current = current.left; } return current; } public static void main(String[] args) { InorderSuccessor tree = new InorderSuccessor(); Node1 root = null, temp = null, suc = null, min = null; root=tree.insert(root, 20); root=tree.insert(root, 8); root=tree.insert(root, 22); root=tree.insert(root, 4); root=tree.insert(root, 12); root=tree.insert(root, 10); root=tree.insert(root, 14); temp=root.left.right.right; suc=tree.inOrderSuccessor(root, temp); if (suc!=null) { System.out.println("Inorder successor of "+ temp.data + " is " + suc.data); } else{ System.out.println("Inorder successor does not exist"); } } }
JavaScript
UTF-8
2,545
2.640625
3
[]
no_license
import React, { Component } from 'react' import './search.css' import axios from 'axios' //Need to break this up into many components class Search extends Component { constructor() { super(); this.state = { textfield: '', buttonfield: 'Card Name', randomfield : 'Is it Magic Time?', cardId: '', usd: '', usdFoil: '', cardimg: '' } this.handleSearchClick = this.handleSearchClick.bind(this); this.handleSearchChange = this.handleSearchChange.bind(this); this.handleAddCard = this.handleAddCard.bind(this); } handleSearchClick() { axios.get('/card/' + this.state.textfield) .then(response => this.setState({ randomfield: this.state.textfield, cardId: 'Card ID: ' + response.data.id, usd: 'Price: $' + response.data.price.usd, usdFoil: 'Price (foil): $' + response.data.price.usd_foil, cardimg: response.data.image_uris.small }) ) } handleSearchChange(event) { console.log(event.target.value); this.setState({ buttonfield: event.target.value, textfield: event.target.value }); } handleAddCard() { axios.post('/card/' + this.state.textfield + '/add') .then(response => this.setState({ cardimg: 'Added!' }) ) } render () { return ( <div className='app__container'> <div className='App-header'> Magic: The Gathering </div> <div className='search__container'> <input className='search__bar' placeholder="Enter Card Name" onChange={this.handleSearchChange} /> <br></br> <button className='button' onClick={this.handleSearchClick}> Search </button> </div> <div className='cardinfo__container'> <div className='cardimage__container'> <img alt="" src={this.state.cardimg}/> </div> <div className='carddata__container'> <p>{this.state.cardId}</p> <p>{this.state.usd}</p> <p>{this.state.usdFoil}</p> <br></br> <br></br> <br></br> {this.state.cardId && <button className='addcardbutton' onClick={this.handleAddCard}> Add me </button>} </div> </div> <div className='App-footer'> Trap Lord Season Begins </div> </div> ) } } export default Search
C++
UTF-8
5,288
3.125
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <fstream> #include <iostream> #include <map> #include <pthread.h> #include "utils.h" using namespace std; // Server class class Server { public: int id; string ip; int port; bool running; }; // all servers int NUM_OF_SERVERS; map<int, Server> servers; // mutex lock pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER; /* * Parse all servers info */ int parse_all_servers(const char* filename) { ifstream ifs(filename); string line = ""; int id = 1; // read file line by line while (getline(ifs, line)) { // get IP address and port number size_t colon = line.find(":"); if (colon == string::npos) { fprintf(stderr, "Wrong IP address and port number format\n"); exit(1); } string ip_addr = line.substr(0, colon); int port = atoi(line.substr(colon+1).c_str()); Server server; server.id = id; server.ip = ip_addr; server.port = port; server.running = false; servers[id++] = server; } return id - 1; } /* * check server state every 5 second */ void* check_server_state(void* arg) { while (true) { for (int i = 1; i <= NUM_OF_SERVERS; i++) { int sockfd = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in servaddr; inet_aton(servers[i].ip.c_str(), &(servaddr.sin_addr)); servaddr.sin_port = htons(servers[i].port); servaddr.sin_family = AF_INET; if (connect(sockfd, (struct sockaddr*) &servaddr, sizeof(servaddr)) == 0) { pthread_mutex_lock(&mutex_lock); servers[i].running = true; pthread_mutex_unlock(&mutex_lock); cout << "server #" << i << " is active" << endl; } else { pthread_mutex_lock(&mutex_lock); servers[i].running = false; pthread_mutex_unlock(&mutex_lock); cout << "server #" << i << " is down" << endl; } close(sockfd); } // sleep 5 second sleep(5); } return NULL; } /* * Main */ int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "[Usage]: ./lb -p 10000 servers.txt\n"); exit(1); } // local variables int port = 0; // parse command line arguments int c; while ((c = getopt(argc, argv, "p:")) != -1) { switch (c) { case 'p': port = atoi(optarg); break; default: exit(1); } } // parse server config file const char* filename = argv[optind]; NUM_OF_SERVERS = parse_all_servers(filename); // create socket for listening int listen_fd = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htons(INADDR_ANY); servaddr.sin_port = htons(port); bind(listen_fd, (struct sockaddr*) &servaddr, sizeof(servaddr)); // listen on port number and accept connection listen(listen_fd, 100); // check server state pthread_t state_thread; pthread_create(&state_thread, NULL, check_server_state, NULL); int handler_server_id = 1; while (true) { // accept a connection from client struct sockaddr_in client_addr; socklen_t client_addrlen = sizeof(client_addr); int fd = accept(listen_fd, (struct sockaddr*) &client_addr, &client_addrlen); if (fd < 0) continue; // find next available server to handle this request int count = 0; pthread_mutex_lock(&mutex_lock); while (!servers[handler_server_id].running) { handler_server_id = (handler_server_id + 1) % NUM_OF_SERVERS; if (handler_server_id == 0) { handler_server_id = NUM_OF_SERVERS; } count++; if (count >= NUM_OF_SERVERS) break; } pthread_mutex_unlock(&mutex_lock); // http header string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: "; // no server is running now if (count >= NUM_OF_SERVERS) { cout << "No server is running now" << endl; string content = get_file_content_as_string("html/no-server-running.html"); string response = header + to_string(content.length()) + "\r\n\r\n"; response += content; write(fd, response.c_str(), response.length()); } else { cout << "Accept a new connection, redirect to server #" << to_string(handler_server_id) << endl; string content = get_file_content_as_string("html/redirect-this-server.html"); string server = servers[handler_server_id].ip+":"+to_string(servers[handler_server_id].port); replace_all(content, "$server", server); string response = header + to_string(content.length()) + "\r\n\r\n"; response += content; write(fd, response.c_str(), response.length()); handler_server_id = (handler_server_id + 1) % NUM_OF_SERVERS; if (handler_server_id == 0) { handler_server_id = NUM_OF_SERVERS; } } close(fd); } // close load balancer close(listen_fd); return 0; }
Java
UTF-8
2,269
1.867188
2
[]
no_license
package cn.test.book.qqwallet; import com.tencent.mobileqq.openpay.api.IOpenApi; import com.tencent.mobileqq.openpay.api.IOpenApiListener; import com.tencent.mobileqq.openpay.api.OpenApiFactory; import com.tencent.mobileqq.openpay.data.base.BaseResponse; import com.tencent.mobileqq.openpay.data.pay.PayResponse; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import com.facebook.react.bridge.ReadableMap; public class CallbackActivity extends Activity implements IOpenApiListener { IOpenApi openApi; // 处理支付回调 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); openApi = OpenApiFactory.getInstance(this, QqWalletModule.APP_ID); openApi.handleIntent(getIntent(), this); } // 处理支付回调 @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); openApi.handleIntent(intent, this); } // 返回支付结果 @Override public void onOpenResponse(BaseResponse response) { String message; if (response == null) { message = null; return; } else { if (response instanceof PayResponse) { PayResponse payResponse = (PayResponse) response; message = "{\"apiName\":\"" + payResponse.apiName + "\"," + "\"serialnumber\":\"" + payResponse.serialNumber + "\"," + "\"isSucess\":" + payResponse.isSuccess() + "," + "\"retCode\":" + payResponse.retCode + "," + "\"retMsg\":\"" + payResponse.retMsg + "\""; // if (payResponse.isSuccess()) { // if (!payResponse.isPayByWeChat()) { // message += ",\"transactionId:\"" + payResponse.transactionId + "\"," // + "\"payTime:\"" + payResponse.payTime + "\"," // + "\"callbackUrl:\"" + payResponse.callbackUrl + "\"," // + "\"totalFee:\"" + payResponse.totalFee + "\""; // } // } message += "}"; } else { message = "notPayResponse"; } } QqWalletModule.promise.resolve(message); finish(); } }
C++
UTF-8
962
2.578125
3
[]
no_license
// // scChar.cpp // scFont // // Created by Nick Yulman on 3/13/13. // // #include "scChar.h" //scChar::scChar(int _xDim,int _yDim){ //} void scChar::init(char _name, ofVec2f _dims, ofVec2f _nDims, ofVec2f _spacing, vector<ofVec2f> _positions, string _shape){ numNodes = _positions.size(); name = _name; cPos = ofVec2f(100,100); dims = _dims; nDims = _nDims; spacing = _spacing; nShape = _shape; //does the char need to know this? for(int i = 0; i<numNodes; i++){ positions.push_back(_positions[i]); node n; n.init(cPos+positions[i]*nDims*spacing); nodes.push_back(n); } } void scChar::display(){ for(int i = 0; i<numNodes; i++){ nodes[i].display(); } } void scChar::update(){ for(int i = 0; i<numNodes; i++){ nodes[i].pos = cPos+positions[i]*nDims*spacing; } for(int i = 0; i<numNodes; i++){ nodes[i].update(); } }
C#
UTF-8
10,228
2.578125
3
[]
no_license
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class MapGeneratorController : MonoBehaviour { public int width; public int height; public string seed; public bool useRandomSeed; [Range(0,100)] public int randomFillPercent; int[,] map; void Start(){ //Funcion que se llama al inicio del programa GenerateMap (); } void Update(){ //Funcion que se llama en cada frame if (Input.GetMouseButtonDown(0)) { GenerateMap (); } } void GenerateMap() { map = new int[width, height]; RandomFillMap (); for (int i = 0; i < 5; i++) { SmoothMap (); } ProcessMap (); int borderSize = 1; //Con esta variable se controla el numero de cuadros para la orilla int[,] borderedMap = new int[width + borderSize * 2, height + borderSize * 2]; for (int x = 0; x < borderedMap.GetLength (0); x++) { for (int y = 0; y < borderedMap.GetLength (1); y++) { if (x >= borderSize && x < width + borderSize && y >= borderSize && y < height + borderSize) { borderedMap[x,y] = map [x - borderSize, y - borderSize]; } else { borderedMap[x,y] = 1; } } } MeshGenerator meshGen = GetComponent<MeshGenerator> (); meshGen.GenerateMesh (borderedMap, 1); } /* Se encarga de eliminar cuartos que no son suficientemente grandes */ void ProcessMap(){ List<List<Coord>> wallRegions = GetRegions (1); int wallThresholdSize = 50; // Minimum tile size of the regions, if not its removed foreach (List<Coord> wallRegion in wallRegions) { if (wallRegion.Count < wallThresholdSize) { foreach (Coord tile in wallRegion) { map [tile.tileX, tile.tileY] = 0; } } } List<List<Coord>> roomRegions = GetRegions (0); int roomThresholdSize = 50; // Minimum tile size of the regions, if not its removed List<Room> survivingRooms = new List<Room>(); foreach (List<Coord> roomRegion in roomRegions) { if (roomRegion.Count < roomThresholdSize) { foreach (Coord tile in roomRegion) { map [tile.tileX, tile.tileY] = 1; } } else { survivingRooms.Add (new Room(roomRegion, map)); } } survivingRooms.Sort (); survivingRooms [0].isMainRoom = true; survivingRooms [0].isAccessibleFromMainRoom = true; ConnectClosestRooms (survivingRooms); } void ConnectClosestRooms(List<Room> allRooms, bool forceAccessibilityFromMainRoom = false){ List<Room> roomListA = new List<Room> (); // Are not accesible from main room List<Room> roomListB = new List<Room> (); // Are Accessible From Main Room if (forceAccessibilityFromMainRoom) { foreach (Room room in allRooms) { if (room.isAccessibleFromMainRoom) { roomListB.Add (room); } else { roomListA.Add (room); } } } else { roomListA = allRooms; roomListB = allRooms; } int bestDistance = 0; Coord bestTileA = new Coord (); Coord bestTileB = new Coord (); Room bestRoomA = new Room (); Room bestRoomB = new Room (); bool posibleConnectionFound = false; foreach (Room roomA in roomListA) { if (!forceAccessibilityFromMainRoom) { posibleConnectionFound = false; if (roomA.connectedRooms.Count > 0) { continue; } } foreach (Room roomB in roomListB) { if(roomA == roomB || roomA.IsConnected(roomB)){ continue; } for(int tileIndexA =0; tileIndexA < roomA.edgeTiles.Count; tileIndexA++){ for(int tileIndexB =0; tileIndexB < roomB.edgeTiles.Count; tileIndexB++){ Coord tileA = roomA.edgeTiles [tileIndexA]; Coord tileB = roomB.edgeTiles [tileIndexB]; int distanceBetweenRooms = (int) (Math.Pow(tileA.tileX - tileB.tileX, 2) + Math.Pow(tileA.tileY - tileB.tileY, 2)); if(distanceBetweenRooms < bestDistance || !posibleConnectionFound){ bestDistance = distanceBetweenRooms; posibleConnectionFound = true; bestTileA = tileA; bestTileB = tileB; bestRoomA = roomA; bestRoomB = roomB; } } } } if (posibleConnectionFound && !forceAccessibilityFromMainRoom) { CreatePassage (bestRoomA, bestRoomB, bestTileA, bestTileB); } } if (posibleConnectionFound && forceAccessibilityFromMainRoom) { CreatePassage (bestRoomA, bestRoomB, bestTileA, bestTileB); ConnectClosestRooms (allRooms, true); } if(!forceAccessibilityFromMainRoom){ ConnectClosestRooms (allRooms, true); } } void CreatePassage(Room roomA, Room roomB, Coord tileA, Coord tileB){ Room.ConnectRooms (roomA, roomB); Debug.DrawLine (CoordToWorldPoint (tileA), CoordToWorldPoint (tileB), Color.green, 100); List<Coord> line = GetLine (tileA, tileB); foreach(Coord c in line){ DrawCircle (c, 1); } } void DrawCircle(Coord c, int r){ for(int x = -r;x<= r;x++){ for(int y = -r;y<= r;y++){ if (x * x + y * y <= r * r) { int realX = c.tileX + x; int realY = c.tileY + y; if(IsInMapRange(realX, realY)){ map [realX, realY] = 0; } } } } } List<Coord> GetLine(Coord from, Coord to){ List<Coord> line = new List<Coord> (); int x = from.tileX, y = from.tileY; int dx = to.tileX - from.tileX; int dy = to.tileY - from.tileY; bool inverted = false; int step = Math.Sign (dx); int gradientStep = Math.Sign (dy); int longest = Mathf.Abs (dx); int shortest = Mathf.Abs (dy); if (longest < shortest) { inverted = true; longest = Mathf.Abs (dy); shortest = Mathf.Abs(dx); step = Math.Sign (dy); gradientStep = Math.Sign (dx); } int gradientAccumulation = longest / 2; for(int i =0; i< longest;i++){ line.Add (new Coord(x,y)); if (inverted) { y += step; } else { x += step; } gradientAccumulation += shortest; if(gradientAccumulation >= longest){ if (inverted) { x += gradientStep; } else { y += gradientStep; } gradientAccumulation -= longest; } } return line; } Vector3 CoordToWorldPoint(Coord tile){ return new Vector3 (-width/2+.5f+tile.tileX, 2, -height/2 + .5f+tile.tileY); } /* Obtiene regiones del mapa que componen un espacio 1 pared 0 vacio */ List<List<Coord>> GetRegions(int tileType){ List<List<Coord>> regions = new List<List<Coord>> (); int[,] mapFlags = new int[width, height]; for(int x=0;x<width;x++){ for(int y=0;y<height;y++){ if(mapFlags[x,y] == 0 && map[x,y] == tileType){ List<Coord> newRegion = GetRegionTiles(x,y); regions.Add(newRegion); foreach(Coord tile in newRegion){ mapFlags[tile.tileX, tile.tileY] = 1; } } } } return regions; } void RandomFillMap(){ //Funcion para llenar el mapa if (useRandomSeed) { seed = Time.time.ToString (); } System.Random pseudoRandom = new System.Random (seed.GetHashCode ()); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (x == 0 || y == 0 || x == width - 1 || y == height - 1) { //Se considera la orilla map [x, y] = 1; } else { map [x, y] = (pseudoRandom.Next (0, 100) < randomFillPercent)? 1:0 ; } } } } List<Coord> GetRegionTiles(int startX, int startY){ List<Coord> tiles = new List<Coord> (); int[,] mapFlags = new int[width, height]; int tileType = map [startX, startY]; Queue<Coord> queue = new Queue<Coord> (); queue.Enqueue (new Coord(startX, startY)); mapFlags [startX, startY] = 1; while(queue.Count > 0){ Coord tile = queue.Dequeue (); tiles.Add (tile); for (int x = tile.tileX - 1; x <= tile.tileX + 1; x++) { for (int y = tile.tileY - 1 ; y <= tile.tileY + 1; y++) { if(IsInMapRange(x, y) && (y == tile.tileY || x == tile.tileX)){ if(mapFlags[x,y] == 0 && map[x,y] == tileType){ mapFlags [x, y] = 1; queue.Enqueue (new Coord(x,y)); } } } } } return tiles; } bool IsInMapRange(int x, int y){ return x >= 0 && x < width && y >= 0 && y < height; } void SmoothMap(){ //Se encarga de unir paredes y espacios vacios for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int neighbourWallTiles = GetSurrondingWallCount (x,y); if (neighbourWallTiles > 4) map [x, y] = 1; else if (neighbourWallTiles < 4) map [x, y] = 0; } } } int GetSurrondingWallCount(int gridX, int gridY){ int wallCount = 0; for(int neighbourX = gridX -1; neighbourX <= gridX +1; neighbourX ++ ){ for(int neighbourY = gridY -1; neighbourY <= gridY +1; neighbourY ++ ){ if(IsInMapRange(neighbourX, neighbourY)){ if(neighbourX != gridX || neighbourY != gridY) { wallCount += map [neighbourX, neighbourY]; } }else{ wallCount++; } } } return wallCount; } struct Coord{ public int tileX; public int tileY; public Coord(int x, int y){ tileX = x; tileY = y; } } class Room : IComparable<Room>{ public List<Coord> tiles; public List<Coord> edgeTiles; public List<Room> connectedRooms; public int roomSize; public bool isAccessibleFromMainRoom; public bool isMainRoom; public Room(){ } public Room(List<Coord> roomTiles, int[,] map){ tiles = roomTiles; roomSize = tiles.Count; connectedRooms = new List<Room>(); edgeTiles = new List<Coord>(); foreach(Coord tile in tiles){ for(int x = tile.tileX - 1 ; x <= tile.tileX + 1; x++){ for(int y = tile.tileY - 1 ; y <= tile.tileY + 1; y++){ if(x == tile.tileX || y == tile.tileY){ if(map[x,y] == 1){ edgeTiles.Add(tile); } } } } } } public void SetAccessibleFromMainRoom(){ if (!isAccessibleFromMainRoom) { isAccessibleFromMainRoom = true; foreach(Room connectedRoom in connectedRooms){ connectedRoom.SetAccessibleFromMainRoom (); } } } public static void ConnectRooms (Room roomA, Room roomB){ if (roomA.isAccessibleFromMainRoom) { roomB.SetAccessibleFromMainRoom (); } else { if(roomB.isAccessibleFromMainRoom){ roomA.SetAccessibleFromMainRoom (); } } roomA.connectedRooms.Add (roomB); roomB.connectedRooms.Add (roomA); } public bool IsConnected(Room otherRoom){ return connectedRooms.Contains (otherRoom); } public int CompareTo(Room otherRoom){ return otherRoom.roomSize.CompareTo (roomSize); } } }
C++
UTF-8
1,531
2.734375
3
[]
no_license
#include "password.h" Password::Password(QWidget *parent) : QDialog(parent), ui(new Ui::password) { ui->setupUi(this); } void Password::on_pushButton_2_clicked() { this->close(); } void Password::set(const QString& x,const bool b) { id = x; level = b; } void Password::on_pushButton_clicked() { QString old=this->ui->lineEdit->text(); QString new_1=this->ui->lineEdit_2->text(); QString new_2=this->ui->lineEdit_3->text(); if(new_2!=new_1) { QMessageBox::information(this, "失败","两次密码不一样","确认"); return; } if(new_1.isEmpty()) { QMessageBox::information(this, "失败","请输入密码","确认"); return; } QSqlQueryModel *model=new QSqlQueryModel; QString sql; if(level) { sql="select password from staff where staff_id =\'"+id+"\'"; model->setQuery(sql); } else { sql="select password from admin where admin_id =\'"+id+"\'"; model->setQuery(sql); } if(old!=model->index(0,0).data(0).toString()) { QMessageBox::information(this, "失败","密码输入错误","确认"); return; } if(level) { sql="update staff set password ='"+new_1+"' where staff_id='"+id+"'"; model->setQuery(sql); } else { sql="update admin set password ='"+new_1+"' where admin_id='"+id+"'"; model->setQuery(sql); } QMessageBox::information(this, "成功","密码修改成功","确认"); }
JavaScript
UTF-8
1,530
2.59375
3
[]
no_license
import React, {Component} from 'react'; import { ListGroup, ListGroupItem, Container} from 'reactstrap'; import CheckBox from './CheckBox' import Back from './Back' class Lesson7 extends Component { state = { cars: ['BMW', 'Honda', 'Vaz', 'Nissan'], BMW: false, Honda: false, Vaz: false, Nissan: false }; handleCheckBoxChange = event => { const { name } = event.target; this.setState(prevState => ({ [name]: !prevState[name] })) }; render() { const cars = this.state.cars.map((car, index) => { let decoration; if(!this.state[car]) { decoration = { textDecoration: 'line-through' }; } else { decoration = { textDecoration: 'none' } } return <ListGroup key={index}> <ListGroupItem> <CheckBox label={car} isSelected={this.state[car]} decoration={decoration} onCheckBoxChange={this.handleCheckBoxChange} key={car} /> </ListGroupItem> </ListGroup> }); return ( <Container> <Back /> { cars } </Container> ) } } export default Lesson7;
Markdown
UTF-8
4,573
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
--- title: "State" author: ["Petros Papapanagiotou"] lastmod: 2021-06-14T23:26:04+01:00 draft: false weight: 310 --- The console maintains an internal state of the introduced processes and compositions. This includes a list of atomic and stored processes and a separate list of intermediate processes. This allows the user to easily remove all intermediate processes when starting a new composition. ## General {#general} The following commands are general purpose, spanning across the whole state: | Command | Result | |----------------------|---------------------------------------------------------------------------------------------------------------------| | `get "P"` | Returns the process named "P", whether it is atomic, intermediate or stored. | | `reset()` | Resets intermediates and their [step counter](#step) in order to start a new composition. | | `full_reset()` | Resets the entire state in order to start a fresh session from scratch. | | `load "P"` | Assuming a process named "P" is stored, the intermediate processes resulting from its composition steps are loaded. | | `store "_Step4" "P"` | Assuming an intermediate process named "\_Step4" exists, it is stored as a new process named "P". | | `responses()` | Yields the history of all responses given by the reasoner in the current session. | {{< tip warning >}} Commands that delete processes, such as `reset()` and `full_reset()` cannot be undone! {{< /tip >}} #### Notes: {#notes} - The `load` command performs a `reset()` first. ## Processes {#processes} The list of atomic and stored processes can be managed with the following commands: | Command | Result | |----------------------|-----------------------------------------------| | `add_process p` | Adds a new process to the list. | | `get_process "P"` | Retrieves the process named "P" if it exists. | | `exists_process "P"` | Returns `true` if a process named "P" exists. | | `del_process "P"` | Deletes the process named "P" from the list. | | `reset_processes()` | Resets the list by removing all processes. | | `list()` | Returns a list of the names of all processes. | #### Notes: {#notes} - It is easier to use [`create`]({{< relref "commands#create" >}}) rather than `add_process` so that the process specification is built automatically for you. - The commands `del_process` and `reset_processes` should be avoided or, at least, used carefully. There is a risk of reaching an inconsistent state where the components of a composition have been deleted. ## Intermediates {#intermediates} The list of intermediate compositions can be managed with the following commands: | Command | Result | |---------------------------|-------------------------------------------------------------| | `add_intermediate p` | Adds a new intermediate process to the list. | | `get_intermediate "P"` | Retrieves the intermediate process named "P" if it exists. | | `exists_intermediate "P"` | Returns `true` if an intermediate process named "P" exists. | | `del_intermediate "P"` | Deletes the intermediate process named "P" from the list. | | `reset_intermediates()` | Resets the list by removing all intermediate processes. | | `ilist()` | Returns a list of the names of all intermediate processes. | #### Notes: {#notes} - It is easier to use the [composition commands]({{< relref "commands" >}}) rather than `add_intermediate` so that the process specifications are built automatically for you and mistakes are prevented. - The command `del_intermediate` should be avoided or, at least, used carefully. There is a risk of reaching an inconsistent state where the components of a composition have been deleted. - The use of the [`reset`](#general) command is suggested instead of `reset_intermediates`. ## Step counter {#step} Fresh names can be automatically produced for intermediate processes using the prefix `"_Step"` and a _step counter_. The command `resetstep()` can be used to reset the step counter. However, the use of the [`reset`](#general) command is suggested instead.
Java
UTF-8
5,641
2.75
3
[]
no_license
package modelos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class Sobrecalentado { double p; double t; double v; double u; double h; double s; private static Conexion conn; public Sobrecalentado() { conn = new Conexion(); p = 0; t = 0; v = 0; u = 0; h = 0; s = 0; } public ArrayList find(String presion) { ArrayList datos = new ArrayList(); ArrayList datos2 = new ArrayList(); ArrayList full = new ArrayList(); Sobrecalentado propiedades; ArrayList<Double> response = new ArrayList(); try { Connection acc = conn.getConexion(); PreparedStatement ps = acc.prepareStatement("SELECT name FROM sqlite_master WHERE type = 'table'"); ResultSet rs = ps.executeQuery(); while(rs.next()) { response.add(rs.getDouble(1)); } Iterator<Double> it = response.iterator(); while(it.hasNext()) { if(it.next()==0) { it.remove(); } } int size = response.size(); Collections.sort(response); for(int i=0;i<size;i++) { if(response.get(i)==Double.parseDouble(presion)) { String sql = "SELECT * FROM '"+presion+"'"; PreparedStatement pr = acc.prepareStatement(sql); ResultSet rr = pr.executeQuery(); while(rr.next()) { propiedades = new Sobrecalentado(); propiedades.setT(rr.getDouble(1)); propiedades.setV(rr.getDouble(2)); propiedades.setU(rr.getDouble(3)); propiedades.setH(rr.getDouble(4)); propiedades.setS(rr.getDouble(5)); datos.add(propiedades); datos2.add(propiedades); } full.add(datos); full.add(datos2); return full; //break; }else if(Double.parseDouble(presion)>response.get(i) && Double.parseDouble(presion)<response.get(i+1)){ Double in1 = response.get(i); String p1 = String.valueOf(in1); String sql1 = "SELECT * FROM '"+p1+"'"; PreparedStatement pr1 = acc.prepareStatement(sql1); ResultSet rr1 = pr1.executeQuery(); while(rr1.next()) { propiedades = new Sobrecalentado(); propiedades.setP(in1); propiedades.setT(rr1.getDouble(1)); propiedades.setV(rr1.getDouble(2)); propiedades.setU(rr1.getDouble(3)); propiedades.setH(rr1.getDouble(4)); propiedades.setS(rr1.getDouble(5)); datos.add(propiedades); } Double in2 = response.get(i+1); String p2 = String.valueOf(in2); String sql2 = "SELECT * FROM '"+p2+"'"; PreparedStatement pr2 = acc.prepareStatement(sql2); ResultSet rr2 = pr2.executeQuery(); while(rr2.next()) { propiedades = new Sobrecalentado(); propiedades.setP(in2); propiedades.setT(rr2.getDouble(1)); propiedades.setV(rr2.getDouble(2)); propiedades.setU(rr2.getDouble(3)); propiedades.setH(rr2.getDouble(4)); propiedades.setS(rr2.getDouble(5)); datos2.add(propiedades); } full.add(datos); full.add(datos2); return full; } } //return datos; } catch (Exception e) { System.err.println(e.getMessage()); } return datos; } public double getP() { return p; } public void setP(double p) { this.p = p; } public double getT() { return t; } public void setT(double t) { this.t = t; } public double getV() { return v; } public void setV(double v) { this.v = v; } public double getU() { return u; } public void setU(double u) { this.u = u; } public double getH() { return h; } public void setH(double h) { this.h = h; } public double getS() { return s; } public void setS(double s) { this.s = s; } }
Shell
UTF-8
1,363
2.859375
3
[ "Apache-2.0" ]
permissive
#!/bin/bash #setup pathes curr=$PWD echo $curr SPARK_HOME=$HOME/spark-2.1.0-bin-hadoop2.7 analytics_zoo=$HOME/code/analytics-zoo MODELS_HOME=${analytics_zoo}/models PYTHON_API_ZIP_PATH=$MODELS_HOME/target/bigdl-models-0.1-SNAPSHOT-python-api.zip JAR_PATH=${MODELS_HOME}/target/models-0.1-SNAPSHOT-jar-with-dependencies.jar # build model zoo if [ ! -f $PYTHON_API_ZIP_PATH ] then cd $MODELS_HOME echo $MODELS_HOME bash build.sh cd $curr fi # when you build models jar, you should have download BigDL BigDL_HOME=$MODELS_HOME/dist-spark-2.1.1-scala-2.11.8-all-0.4.0-dist MASTER="local[2]" export PYTHONPATH=${PYTHON_API_ZIP_PATH}:$PYTHONPATH export PYSPARK_DRIVER_PYTHON=jupyter export PYSPARK_DRIVER_PYTHON_OPTS="notebook --notebook-dir=./ --ip=* --no-browser" echo ${PYTHON_API_ZIP_PATH} echo ${BigDL_HOME}/conf/spark-bigdl.conf echo ${JAR_PATH} ${SPARK_HOME}/bin/pyspark \ --master ${MASTER} \ --driver-cores 1 \ --driver-memory 10g \ --total-executor-cores 3 \ --executor-cores 1 \ --executor-memory 20g \ --py-files ${PYTHON_API_ZIP_PATH} \ --properties-file ${BigDL_HOME}/conf/spark-bigdl.conf \ --jars ${JAR_PATH} \ --conf spark.driver.extraClassPath=${JAR_PATH} \ --conf spark.driver.maxResultSize=4g \ --conf spark.executor.extraClassPath=models-0.1-SNAPSHOT-jar-with-dependencies.jar
C++
UTF-8
735
2.515625
3
[ "LLVM-exception", "Apache-2.0" ]
permissive
// ------------------------------------------------------------------------- // Part of the CodeChecker project, under the Apache License v2.0 with // LLVM Exceptions. See LICENSE for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // ------------------------------------------------------------------------- // core.DivideZero (C, C++, ObjC) // Check for division by zero. int test1(int z) { if (z == 0){ // codechecker_intentional [core.DivideZero] intentional multiline divide by zero here int x = 1 / z; // warn return x; } } int test2() { int x = 1; // codechecker_intentional [core.DivideZero] intentional divide by zero here int y = x % 0; // warn return y; }
Python
UTF-8
935
3.984375
4
[]
no_license
# coding:utf8 # 如何对字符串进行左,右,居中的对齐 ''' 某个字典存储了一系列属性值 { "lodDist":100.0, "SmallCull":0.04, "DistCull":500, "trilinear":40, "farclip":477 } ''' ''' 在程序中,我们希望以以下格式输出字典的内容,该如何处理 SmallCull :0.04 farclip :477 lodDist :100.0 DistCull :500 trilinear :40 ''' dict = { "lodDist": 100.0, "SmallCull": 0.04, "DistCull": 500, "trilinear": 40, "farclip": 477 } for k, v in dict.items(): print k,':', v print('------------------') for k, v in dict.items(): print k.ljust(9,' '),':',v print('------------------') for k, v in dict.items(): print format(k,'<9'),':',v ''' 解决方案: 方法1:使用字符串的str.ljust(),str.rjust(),str.center进行左,右,居中对齐 方法2:使用format()方法,传递类似'<20','>20','^20'参数完成左对齐,右对齐,居中对齐 '''
Shell
UTF-8
2,077
4.28125
4
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash source "$(dirname "$0")/common_functions.sh" #----------------------------------------------------------------------------------------------------------------------- # # DOCUMENTS ARGUMENTS # #----------------------------------------------------------------------------------------------------------------------- usage() { echo -e "\nUsage: $0 -s <server-name> -b <osa_branch>" 1>&2 echo -e "\nOptions:\n" echo -e " -s Name of the new server, overriden by SRV_NAME environment variable" echo -e " -b Branch of OSA to use. Defaults to MASTER. Overriden by OSA_BRANCH variable" echo -e "\n" exit 1 } #----------------------------------------------------------------------------------------------------------------------- # # GETS SCRIPT OPTIONS # #----------------------------------------------------------------------------------------------------------------------- setScriptOptions() { while getopts "s:b:" o; do case "${o}" in b) opt_b=${OPTARG} ;; s) opt_s=${OPTARG} ;; *) usage ;; esac done shift $((OPTIND-1)) if [ -z ${OSA_BRANCH+x} ]; then if [[ ${opt_b} ]];then OSA_BRANCH=${opt_b} else OSA_BRANCH="master" fi fi if [ -z ${SRV_NAME+x} ]; then if [[ ${opt_s} ]];then SRV_NAME=${opt_s} else usage fi fi } cloneAnsible() { echo "Cloning ansible to ${SRV_NAME}" ssh root@${SRV_NAME} <<EOF # Clone OSA git clone https://git.openstack.org/openstack/openstack-ansible /opt/openstack-ansible cd /opt/openstack-ansible # Checkout a known working version because HEAD is often broken echo "Checking out ${OSA_BRANCH}" git checkout ${OSA_BRANCH} EOF } #----------------------------------------------------------------------------------------------------------------------- # # Start of main script # #----------------------------------------------------------------------------------------------------------------------- header $0 setScriptOptions $@ cloneAnsible footer $0
TypeScript
UTF-8
2,483
3.1875
3
[]
no_license
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk, RootState } from "../../app/store"; import { MovieType } from "./Movie"; interface SearchState { loading: boolean; films: MovieType[]; errorMessage: string | null; } const initialState: SearchState = { loading: false, films: [], errorMessage: null, }; export const searchSlice = createSlice({ name: "search", initialState, reducers: { filmsLoading: (state) => { // Redux Toolkit allows us to write "mutating" logic in reducers. It // doesn't actually mutate the state because it uses the Immer library, // which detects changes to a "draft state" and produces a brand new // immutable state based off those changes state.loading = true; state.errorMessage = null; }, filmsSuccess: (state, action: PayloadAction<MovieType[]>) => { state.loading = false; state.films = action.payload; }, // Use the PayloadAction type to declare the contents of `action.payload` filmsFailure: (state, action: PayloadAction<string>) => { state.loading = false; state.errorMessage = action.payload; }, }, }); export const { filmsLoading, filmsSuccess, filmsFailure } = searchSlice.actions; // The function below is called a thunk and allows us to perform async logic. It // can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This // will call the thunk with the `dispatch` function as the first argument. Async // code can then be executed and other actions can be dispatched export const fetchFilms = (searchValue: string): AppThunk => async ( dispatch ) => { dispatch(filmsLoading()); const response = await fetch( `https://www.omdbapi.com/?s=${searchValue}&apikey=4a3b711b` ); const data = await response.json(); if (data.Response === "True") { dispatch(filmsSuccess(data.Search)); } else { dispatch(filmsFailure(data.Error)); } }; // The function below is called a selector and allows us to select a value from // the state. Selectors can also be defined inline where they're used instead of // in the slice file. For example: `useSelector((state: RootState) => state.counter.value)` export const selectFilms = (state: RootState) => state.search.films; export const selectErrorMessage = (state: RootState) => state.search.errorMessage; export const selectLoadingStatus = (state: RootState) => state.search.loading; export default searchSlice.reducer;
JavaScript
UTF-8
11,774
2.640625
3
[]
no_license
function createUTC(zNum){ //To use this function make sure to choose a number between -12 and 12. This should either be //an integer or a decimal between -9 and 9 with .5 or .75 at the end. // These values cover every capital city timezone. var zNumStr = zNum.toString(); var zNumIndex = zNumStr.indexOf(".5"); var zNumIndexTwo = zNumStr.indexOf(".75"); var zNumIndexThree = zNumStr.indexOf("-"); var uTCString; var uTCSubString; var uTCSubStringEnd; // this removes the minus from the string for easy process below if(zNumIndexThree != -1){ zNumStr = zNumStr.replace("-", ""); } // this adds the utc prefix if(zNum > 0){ uTCSubString = 'UTC +'; } else if(zNum < 0){ uTCSubString = 'UTC -'; } else{ uTCSubString = 'UTC'; } //this adds the suffix and converts decimals to time if((zNumIndex == -1)&&(zNumIndexTwo == -1)){ if(zNumStr.length == 1){ uTCSubStringEnd = "0"+zNumStr+":00"; } else { uTCSubStringEnd = zNumStr+":00"; } } else if(zNumIndex == -1){ uTCSubStringEnd = "0"+(zNumStr.replace(".75", ":45")); } else { uTCSubStringEnd = "0"+(zNumStr.replace(".5", ":30")); } //this creates the finished string if(zNum == 0){ uTCString = uTCSubString; } else{ uTCString = uTCSubString+uTCSubStringEnd; } return uTCString; } var capitalsTz = [[0 , "London", 0], [1, "Paris", 0], [1, "Berlin", 0], [1, "Madrid",0], [0, "Lisbon",0], [0, "Dublin",0], [0, "Belfast",0], [-5, "Washington D.C.",0], [1, "Rome", 0], [9, "Tokyo", 0], [1, "Warsaw", 1], [1, "Vienna", 1], [1, "Stockholm", 1], [1, "Oslo", 1], [2, "Helsinki", 1], [10, "Canberra", 1], [12, "Wellington", 1], [3, "Baghdad", 2], [-5, "Ottawa",2], [8, "Beijing", 2], [5.5, "New Delhi", 2], [2, "Cairo", 2], [1, "Brussels", 1], [-3, "Buenos Aires", 3], [-3, "Brisilia", 2], [2, "Pretoria", 1], [7, "Bangkok", 2], [2, "Kiev", 1], [-5, "Kingston", 3], [5, "Islamabad", 3], [0, "Rabat", 3], [0, "Reykjavik", 1], [2, "Ankara", 2], [7, "Jakarta", 4], [-5, "Bogota", 4], [-5, "Lima", 3], [-4.5, "Caracas", 3], [3, "Mogadishu", 2], [-5, "Port au Prince", 2], [3.5, "Tehran", 2], [-3, "Santiago", 3], [-5, "Le Paz", 3], [-3, "Montevideo", 3], [-4, "Asuncion", 4], [0, "Banjul", 5], [3, "Doha", 4], [3, "Kampala", 5], [1, "Luanda", 4], [4, "Muscat", 5], [1, "Niamey", 5], [-4, "San Juan", 4], [-4, "Road Town", 4], [12, "Tarawa Atoll", 6], [7, "Vientiane", 6], [0, "Ouagadougou", 5], [3, "Asmara", 5], [1, "Copenhagen", 1], [-4, "Santo Domingo", 4], [4.5, "Kabul", 2], [1, "Tirana", 3], [1, "Andorra la Vella", 1], [-4, "Saint John's", 3], [4, "Yerevan", 3], [5, "Baku", 4], [-5, "Nassau", 3], [3, "Manama", 5], [6, "Dhaka", 4], [-4, "Bridgetown", 3], [3, "Minsk", 2], [-6, "Belmopan", 5], [1, "Porto-Novo", 6], [6, "Thimphu", 5], [1, "Sarajevo", 3], [2, "Gaborone", 5], [8, "Bandar Seri Begawan", 5], [2, "Sofia", 3], [2, "Bujumbura", 5], [7, "Phnom Penh", 4], [1, "Yaounde", 4], [1, "Bangui", 5], [1, "N'Djamena", 5], [3, "Moroni", 5], [1, "Brazzaville", 5], [1, "Kinshasa", 4], [0, "Yamoussoukro", 5], [1, "Zagreb", 2], [-5, "Havanna", 3], [3, "Nicosia", 2], [1, "Prague", 2], [3, "Djibouti", 6], [-4, "Roseau", 5], [9, "Dili", 5], [-5, "Quito", 4], [-6, "San Salvador", 5], [1, "Malabo", 5], [2, "Talinn", 2], [3, "Addis Ababa", 3], [12, "Suva", 4], [1, "Libreville", 5], [4, "Tbilisi", 5], [0, "Accra", 4], [-4, "Saint George's", 5], [-6, "Guatemala City", 3], [0, "Conakry", 5], [0, "Bissau", 6], [-4, "Georgetown", 4], [-6, "Tegucigalpa", 5], [1, "Budapest", 2], [2, "Jerusalem", 2], [2, "Amman", 3], [6, "Astana", 5], [3, "Nairobi", 3], [9, "Pyongyang", 4], [9, "Seoul", 3], [1, "Pristina", 5], [3, "Kuwait City", 5], [6, "Bishkek", 5], [2, "Riga", 3], [1, "Vaduz", 3], [2, "Vilinus", 4], [1, "Luxembourg", 1], [1, "Skopje", 4], [3, "Antananarivo", 5], [2, "Lilongwe", 5], [8, "Kuala Lumpur", 4], [5, "Male", 5], [0, "Bamako", 5], [1, "Valetta", 3], [12, "Majuro", 5], [0, "Nouakchott", 5], [-6, "Mexico City", 3], [11, "Palikir", 5], [2, "Chisinau", 4], [1, "Monaco", 1], [8, "Ulaanbaatar", 4], [1, "Podgorica", 6], [2, "Maputo", 4], [6.5, "Nay Pyi Taw", 6], [1, "Windhoek", 4], [5.5, "Kathmandu", 3], [1, "Amsterdam", 2], [-6, "Managua", 5], [1, "Abuja", 3], [9, "Melekeok", 5], [-5, "Panama City", 4], [10, "Port Moresby", 5], [8, "Manila", 3], [2, "Kigali", 5], [-4, "Basseterre", 5], [-4, "Castries", 5], [-4, "Kingstown", 5], [13, "Apia", 5], [1, "San Marino", 1], [0, "Sao Tome", 3], [3, "Riyadh", 3], [0, "Dakar", 4], [1, "Belgrade", 3], [4, "Victoria", 5], [0, "Freetown", 4], [8, "Singapore",2], [1, "Bratislava", 1], [1, "Llubljana", 2], [11, "Honiara", 5], [3, "Juba", 5], [5.5, "Colombo", 6], [3, "Khartoum", 5], [-3, "Paramaribo", 5], [2, "Mbabane", 5], [1, "Bern", 1], [2, "Damascus", 3], [8, "Taipei", 4], [5, "Dunshanbe", 6], [3, "Dodoma", 4], [0, "Lome", 6], [13, "Nuku'alofa", 5], [-4, "Port-of-Spain", 4], [1, "Tunis", 2], [5, "Ashgabat", 5], [12, "Funafuti", 6], [4, "Abu Dhabi", 3], [5, "Tashkent", 6], [11, "Port-Vila", 5], [1, "Vatican City", 1], [7, "Hanoi", 3], [3, "Sanaa", 5], [2, "Lusaka", 6], [2, "Harare", 4] ]; var levelTz = 0; var levelCorrectTz = 0; var usedNumbersTz = []; var levelTz = 0; var currentAnswersTz = []; var buttonArrayTz = []; var questionNumberTz; var correctTz = 0; var attemptsTz = 0; var scoreTotalTz = 0; var scoreTz; var intervalTz; function loadIntervalTz(){ intervalTz = setInterval(function() { scoreReducerTz() }, 100); } function scoreResetTz(){ scoreTz = 1000; } function stopIntervalTz(){ clearInterval(intervalTz); } function scoreReducerTz(){ document.getElementById("potentialTz").innerHTML = scoreTz; scoreTz = scoreTz - 3; if(scoreTz<0){ scoreTz = 0; return scoreTz; } } //allows games to increase level when a certain number of correct answers are reached or there are no more wuestions in that level function levelUpTz() { if((levelTz==0)&&(levelCorrectTz== 3)) { levelTz++; levelCorrectTz = 0; } if((levelTz==1)&&(levelCorrectTz== 4)) { levelTz++; levelCorrectTz = 0; } if ((levelTz==2)&&(levelCorrectTz== 4)){ levelTz++; levelCorrectTz = 0; } if((levelTz==3)&&(levelCorrectTz== 4)) { levelTz++; levelCorrectTz = 0; } if ((levelTz==4)&&(levelCorrectTz== 3)) { levelTz++; levelCorrectTz = 0 } } function questionSelectTz(levelNumber){ var currentAnswersTwoTz=currentAnswersTz; for(var i=0; i<currentAnswersTwoTz.length; i++){ if(capitalsTz[currentAnswersTwoTz[i]][2]== levelNumber){ questionNumberTz = currentAnswersTwoTz[i]; } } } function answersSelectTz(levelNumber){ var uniqueAnswerTz; var newAnswerIntTz; var levelCorrectTz = false; var counterTz = 0; while(levelCorrectTz == false){ currentAnswersTz = []; while (currentAnswersTz.length < 4){ uniqueAnswerTz = true; newAnswerIntTz = Math.floor(Math.random() * capitalsTz.length); //loop through unsednumber array to check if it has already been answered correctly for(var u=0; u<usedNumbersTz.length; u++){ if(newAnswerIntTz== usedNumbersTz[u]){ uniqueAnswerTz = false; } } //Loop through array to check unique and to check four different timezones. for(var j=0; j<currentAnswersTz.length; j++){ if (newAnswerIntTz == currentAnswersTz[j]){ uniqueAnswerTz = false; } if(capitalsTz[newAnswerIntTz][0] == capitalsTz[currentAnswersTz[j]][0]){ uniqueAnswerTz = false; } } if (uniqueAnswerTz == true) { currentAnswersTz.push(newAnswerIntTz); } } for (var k=0; k<currentAnswersTz.length; k++){ if (capitalsTz[currentAnswersTz[k]][2]== levelNumber){ counterTz++; } } if(counterTz>0){ levelCorrectTz = true; } } } function fillButtonsTz(){ var currentAnswersThreeTz = currentAnswersTz; var uniqueButtonTz; buttonArrayTz = []; var butRandTz; while(buttonArrayTz.length<4){ uniqueButtonTz = true; butRandTz = Math.floor(Math.random()*4); for(var p=0; p<buttonArrayTz.length; p++){ if(butRandTz==buttonArrayTz[p]){ uniqueButtonTz=false; } } if(uniqueButtonTz == true){ buttonArrayTz.push(butRandTz); } } document.getElementById("buttonOneTz").value = (capitalsTz[currentAnswersThreeTz[buttonArrayTz[0]]][1]); document.getElementById("buttonTwoTz").value = (capitalsTz[currentAnswersThreeTz[buttonArrayTz[1]]][1]); document.getElementById("buttonThreeTz").value = (capitalsTz[currentAnswersThreeTz[buttonArrayTz[2]]][1]); document.getElementById("buttonFourTz").value = (capitalsTz[currentAnswersThreeTz[buttonArrayTz[3]]][1]); } function fillQuestionTz(levelNumber){ var questiTz = document.getElementById("capitalTz"); questiTz.innerHTML = createUTC(capitalsTz[questionNumberTz][0]); } function scoreCounterTz(){ document.getElementById("correctTz").innerHTML = correctTz; document.getElementById("attemptsTz").innerHTML = attemptsTz; document.getElementById("scoreTz").innerHTML = scoreTotalTz; document.getElementById("levelTz").innerHTML = levelTz + 1; } function loadGameTz(){ scoreResetTz(); answersSelectTz(levelTz); questionSelectTz(levelTz); fillQuestionTz(levelTz); fillButtonsTz(); loadIntervalTz(); scoreCounterTz(); } function checkAnswerTz(){ attemptsTz++; levelUpTz(); var counterCheckTz; for(var q=0; q<buttonArrayTz.length; q++){ if(currentAnswersTz[buttonArrayTz[q]]==questionNumberTz){ counterCheckTz= q; } } return counterCheckTz; } function clickButOneTz(){ stopIntervalTz(); var numberOneTz = checkAnswerTz(); if(numberOneTz==0){ document.getElementById("resultTz").innerHTML =("CORRECT"); correctTz++; levelCorrectTz++; scoreTotalTz = scoreTotalTz + scoreTz; usedNumbersTz.push(questionNumberTz); } if(numberOneTz!=0){ document.getElementById("resultTz").innerHTML = ("INCORRECT!"); } if(attemptsTz<25){ loadGameTz(); } if(attemptsTz==25){ endQuizTz(); } } function clickButTwoTz(){ stopIntervalTz(); var numberTwoTz = checkAnswerTz(); if(numberTwoTz==1){ document.getElementById("resultTz").innerHTML =("CORRECT"); correctTz++; levelCorrectTz++; scoreTotalTz = scoreTotalTz + scoreTz; usedNumbersTz.push(questionNumberTz); } if(numberTwoTz!=1){ document.getElementById("resultTz").innerHTML = ("INCORRECT!"); } if(attemptsTz<25){ loadGameTz(); } if(attemptsTz==25){ endQuizTz(); } } function clickButThreeTz(){ stopIntervalTz(); var numberThreeTz = checkAnswerTz(); if(numberThreeTz==2){ document.getElementById("resultTz").innerHTML =("CORRECT"); correctTz++; levelCorrectTz++; scoreTotalTz = scoreTotalTz + scoreTz; usedNumbersTz.push(questionNumberTz); } if(numberThreeTz!=2){ document.getElementById("resultTz").innerHTML = ("INCORRECT!"); } if(attemptsTz<25){ loadGameTz(); } if(attemptsTz==25){ endQuizTz(); } } function clickButFourTz(){ stopIntervalTz(); var numberFourTz = checkAnswerTz(); if(numberFourTz==3){ document.getElementById("resultTz").innerHTML =("CORRECT"); correctTz++; levelCorrectTz++; scoreTotalTz = scoreTotalTz + scoreTz; usedNumbersTz.push(questionNumberTz); } if(numberFourTz!=3){ document.getElementById("resultTz").innerHTML = ("INCORRECT!"); } if(attemptsTz<25){ loadGameTz(); } if(attemptsTz==25){ endQuizTz(); } } function endQuizTz(){ scoreCounterTz(); document.getElementById("endMesTz").innerHTML = ("Congratulations you have completed the quiz, your score is "+scoreTotalTz+"."); document.getElementById('endFormTz').style.display = "inline"; $('#finalScoreTz').val(scoreTotalTz); document.getElementById("scorePassTwoTz").value = (scoreTotalTz); } function beginQuizTz(){ document.getElementById("introTz").style.display = "none"; document.getElementById("quiz-titleTz").innerHTML = ("The Capital Cities Quiz"); loadGameTz(); document.getElementById("quizTz").style.display = "block"; }
Go
UTF-8
116
2.734375
3
[]
no_license
package piscine func Concat(str1 string, str2 string) string { str3 := []rune(str1 + str2) return string(str3) }
C#
UTF-8
1,455
2.65625
3
[ "MIT" ]
permissive
using CarDealer.Services; using CarDealer.Web.Models.Logs; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; namespace CarDealer.Web.Controllers { public class LogsController : Controller { private readonly ILogService logService; public LogsController(ILogService logService) { this.logService = logService; } [Authorize] [Route("logs/all/{pageNumber}")] public IActionResult All(int pageNumber, string search) { if (pageNumber <= 0 || this.logService.LogsCount() / 20 < pageNumber - 1) { pageNumber = 1; } var logs = this.logService.GetAllLogs(pageNumber); var totalPages = (int)Math.Ceiling((double)this.logService.LogsCount() / 20); var currentPage = pageNumber; if (search != null) { logs = logs.Where(l => l.User.ToLower().Equals(search.ToLower())); } return View(new LogPaginationModel { Logs = logs, CurrentPage = currentPage, TotalPages = totalPages }); } [Authorize] [Route("logs/delete")] public IActionResult Delete() { this.logService.DeleteAllLogs(); return Redirect("/logs/all/1"); } } }
Python
UTF-8
212
3.171875
3
[]
no_license
def calcula_fibonacci (n): fibo=[] n1=1 n2=1 fibo.append(n1) fibo.append(n2) i=0 while i<(n-2): tot=fibo[i]+fibo[i+1] fibo.append(tot) i+=1 return fibo
Python
UTF-8
414
3.6875
4
[ "CC-BY-4.0" ]
permissive
# coding=utf-8 __author__ = 'ipetrash' # EN: Least Common Multiple. # RU: Наименьшее общее кратное (НОК). def gcd(a, b): "Нахождение НОД" while a != 0: a,b = b%a,a # параллельное определение return b if __name__ == '__main__': a = int(raw_input("a = ")) b = int(raw_input("b = ")) print("LCM: %s" % ((a * b) / gcd(a, b)))
Java
UTF-8
2,283
3.046875
3
[]
no_license
package com.tanay.thunderbird.databasedemo; import androidx.appcompat.app.AppCompatActivity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { SQLiteDatabase myDatabase = this.openOrCreateDatabase("Users", MODE_PRIVATE, null); myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users (name VARCHAR, age INT(3))"); //myDatabase.execSQL("INSERT INTO users (name, age) VALUES ('Arvind', 64)"); //myDatabase.execSQL("INSERT INTO users (name, age) VALUES ('Deepti', 55)"); myDatabase.execSQL("DELETE FROM users WHERE name = 'Tanay'"); // command to delete a tuple myDatabase.execSQL("UPDATE users SET age = 20 WHERE name = 'Tanuj'"); // command to update a tuple // now to fetch the data out of the database, cursor allows us to loop through all the particular results of a query and do something with them // Cursor c = myDatabase.rawQuery("SELECT * FROM users WHERE age < 30", null); // for null, there exists a signal/method that can cancel a query in progress //Cursor c = myDatabase.rawQuery("SELECT * FROM users WHERE name = 'Tanay' AND age = 20", null); //Cursor c = myDatabase.rawQuery("SELECT * FROM users WHERE name LIKE 'T%'", null); //for names starting with T Cursor c = myDatabase.rawQuery("SELECT * FROM users WHERE name LIKE 'T%' LIMIT 1", null); //to display just one name int nameIndex = c.getColumnIndex("name"); int ageIndex = c.getColumnIndex("age"); c.moveToFirst(); while(c != null) { Log.i("UserResults - Name", c.getString(nameIndex)); Log.i("UserResults - Age", Integer.toString(c.getInt(ageIndex))); c.moveToNext(); } } catch(Exception e) { e.printStackTrace(); } } }
PHP
UTF-8
516
2.5625
3
[]
no_license
<?php if(isset($_POST['book_id'])){ $cookie_name = "book_id"; $data = json_decode($_COOKIE[$cookie_name]); var_dump($data); // now removing the book id from specific $index = array_search($_POST['book_id'],$data ); array_splice($data,$index,1); $cookie_value = $data ; setcookie($cookie_name, json_encode($cookie_value), time()+3600); echo "Cookie updated. The values in the array are: "; var_dump($data); } else echo "Post didnot worked!"; ?>
Java
UTF-8
4,618
3.8125
4
[]
no_license
package com.isa.section2.chapter1.exercises; public class Warmup { public static void main(String[] args) { String[] a = {"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"}; SelectionSort.sort(a, DIRECTION.ASC); assert SelectionSort.isSorted(a); SelectionSort.show(a); a = new String[]{"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"}; SelectionSort.sort(a, DIRECTION.DESC); assert SelectionSort.isSorted(a); SelectionSort.show(a); a = new String[]{"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"}; InsertionSort.sort(a, DIRECTION.ASC); assert InsertionSort.isSorted(a); InsertionSort.show(a); a = new String[]{"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"}; InsertionSort.sort(a, DIRECTION.DESC); assert InsertionSort.isSorted(a); InsertionSort.show(a); } public enum DIRECTION { ASC, DESC; } public static class SelectionSort { public static void sort(Comparable[] values, DIRECTION direction) { if (direction == DIRECTION.ASC) { sortAscending(values); } else { } } private static void sortAscending(Comparable[] values) { for (int i = 0; i < values.length; i++) { int minIndex = i; for (int k = i + 1; k < values.length; k++) { if (less(values[k], values[minIndex])) { minIndex = k; } } exch(values, i, minIndex); } } private static void sortDescending(Comparable[] values) { for (int i = 0; i < values.length; i++) { int maxIndex = i; for (int k = i + 1; k < values.length; k++) { if (less(values[maxIndex], values[k])) { maxIndex = k; } } exch(values, i, maxIndex); } } public static boolean less(Comparable first, Comparable second) { return first.compareTo(second) < 0; } public static void exch(Comparable[] values, int first, int second) { Comparable temp = values[first]; values[first] = values[second]; values[second] = temp; } public static void show(Comparable[] a) { // Print the array, on a single line. for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public static boolean isSorted(Comparable[] a) { // Test whether the array entries are in order. for (int i = 1; i < a.length; i++) if (less(a[i], a[i - 1])) return false; return true; } } public static class InsertionSort { public static void sort(Comparable[] values, DIRECTION direction) { if (direction == DIRECTION.ASC) { sortAscending(values); } else { sortDescending(values); } } private static void sortAscending(Comparable[] values) { for (int i = 0; i < values.length; i++) { for (int k = i; k > 0 && less(values[k], values[k - 1]); k--) { exch(values, k, k - 1); } } } private static void sortDescending(Comparable[] values) { for (int i = 0; i < values.length; i++) { for (int k = i; k > 0 && !less(values[k], values[k - 1]); k--) { exch(values, k, k - 1); } } } public static boolean less(Comparable first, Comparable second) { return first.compareTo(second) < 0; } public static void exch(Comparable[] values, int first, int second) { Comparable temp = values[first]; values[first] = values[second]; values[second] = temp; } public static void show(Comparable[] a) { // Print the array, on a single line. for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public static boolean isSorted(Comparable[] a) { // Test whether the array entries are in order. for (int i = 1; i < a.length; i++) if (less(a[i], a[i - 1])) return false; return true; } } }
C#
ISO-8859-1
5,564
2.6875
3
[ "Apache-2.0" ]
permissive
namespace BoletoNet { using System; #region EnumInstrucoes_Sicoob enum public enum EnumInstrucoes_Sicoob { AusenciaDeInstrucoes = 0, CobrarJuros = 1, Protestar3DiasUteis = 3, Protestar4DiasUteis = 4, Protestar5DiasUteis = 5, NaoProtestar = 7, Protestar10DiasUteis = 10, Protestar15DiasUteis = 15, Protestar20DiasUteis = 20, ConcederDescontoApenasAteDataEstipulada = 22, DevolverApos15DiasVencido = 42, DevolverApos30DiasVencido = 43, CobrarTaxaDeMulta = 9999 } #endregion public class Instrucao_Sicoob : AbstractInstrucao, IInstrucao { #region Construtores public Instrucao_Sicoob() { try { this.Banco = new Banco(756); } catch (Exception ex) { throw new Exception("Erro ao carregar objeto", ex); } } public Instrucao_Sicoob(int codigo) { this.carregar(codigo, 0, 0); } public Instrucao_Sicoob(int codigo, int nrDias) { this.carregar(codigo, nrDias, (double)0.0); } public Instrucao_Sicoob(int codigo, double percentualMultaDia) { this.carregar(codigo, 0, percentualMultaDia); } public Instrucao_Sicoob(int codigo, int nrDias, double percentualMultaDia) { this.carregar(codigo, nrDias, percentualMultaDia); } #endregion #region Metodos Privados private void carregar(int idInstrucao, int nrDias, double percentualMultaOuJuroAoMes) { try { this.Banco = new Banco_Sicoob(); switch ((EnumInstrucoes_Sicoob)idInstrucao) { case EnumInstrucoes_Sicoob.AusenciaDeInstrucoes: break; case EnumInstrucoes_Sicoob.CobrarJuros: this.Codigo = (int)EnumInstrucoes_Sicoob.CobrarJuros; this.Descricao = string.Format("Aps vencimento cobrar juros de {0}% ao ms.", percentualMultaOuJuroAoMes.ToString("F2")); break; case EnumInstrucoes_Sicoob.CobrarTaxaDeMulta: this.Codigo = (int)EnumInstrucoes_Sicoob.CobrarTaxaDeMulta; this.Descricao = string.Format("Aps vencimento cobrar multa de {0}% ao ms", percentualMultaOuJuroAoMes.ToString("F2")); break; case EnumInstrucoes_Sicoob.Protestar3DiasUteis: this.Codigo = (int)EnumInstrucoes_Sicoob.Protestar3DiasUteis; this.Descricao = "Protestar 3 dias teis aps vencimento"; break; case EnumInstrucoes_Sicoob.Protestar4DiasUteis: this.Codigo = (int)EnumInstrucoes_Sicoob.Protestar4DiasUteis; this.Descricao = "Protestar 4 dias teis aps vencimento"; break; case EnumInstrucoes_Sicoob.Protestar5DiasUteis: this.Codigo = (int)EnumInstrucoes_Sicoob.Protestar5DiasUteis; this.Descricao = "Protestar 5 dias teis aps vencimento"; break; case EnumInstrucoes_Sicoob.NaoProtestar: this.Codigo = (int)EnumInstrucoes_Sicoob.NaoProtestar; this.Descricao = "No protestar"; break; case EnumInstrucoes_Sicoob.Protestar10DiasUteis: this.Codigo = (int)EnumInstrucoes_Sicoob.Protestar10DiasUteis; this.Descricao = "Protestar 10 dias teis aps vencimento"; break; case EnumInstrucoes_Sicoob.Protestar15DiasUteis: this.Codigo = (int)EnumInstrucoes_Sicoob.Protestar15DiasUteis; this.Descricao = "Protestar 15 dias teis aps vencimento"; break; case EnumInstrucoes_Sicoob.Protestar20DiasUteis: this.Codigo = (int)EnumInstrucoes_Sicoob.Protestar20DiasUteis; this.Descricao = "Protestar 20 dias teis aps vencimento"; break; case EnumInstrucoes_Sicoob.ConcederDescontoApenasAteDataEstipulada: this.Codigo = (int)EnumInstrucoes_Sicoob.ConcederDescontoApenasAteDataEstipulada; this.Descricao = "Conceder desconto s at a data estipulada"; break; case EnumInstrucoes_Sicoob.DevolverApos15DiasVencido: this.Codigo = (int)EnumInstrucoes_Sicoob.DevolverApos15DiasVencido; this.Descricao = "Devolver aps 15 dias vencido"; break; case EnumInstrucoes_Sicoob.DevolverApos30DiasVencido: this.Codigo = (int)EnumInstrucoes_Sicoob.DevolverApos30DiasVencido; this.Descricao = "Devolver aps 30 dias vencido"; break; default: this.Codigo = 0; this.Descricao = " (Selecione) "; break; } this.QuantidadeDias = nrDias; } catch (Exception ex) { throw new Exception("Erro ao carregar objeto", ex); } } public override void Valida() { base.Valida(); } #endregion } }
TypeScript
UTF-8
1,030
2.796875
3
[ "MIT" ]
permissive
/*! * Jodit Editor (https://xdsoft.net/jodit/) * Released under MIT see LICENSE.txt in the project root for license information. * Copyright (c) 2013-2023 Valeriy Chupurnov. All rights reserved. https://xdsoft.net */ /** * @module plugins/size */ import { Config } from 'jodit/config'; declare module 'jodit/config' { interface Config { saveHeightInStorage: boolean; minWidth: number | string; minHeight: number | string; maxWidth: number | string; maxHeight: number | string; } } Config.prototype.minWidth = 200; Config.prototype.maxWidth = '100%'; /** * Editor's min-height * * @example * ```javascript * Jodit.make('.editor', { * minHeight: '30%' //min-height: 30% * }) * ``` * @example * ```javascript * Jodit.make('.editor', { * minHeight: 200 //min-height: 200px * }) * ``` */ Config.prototype.minHeight = 200; Config.prototype.maxHeight = 'auto'; /** * if set true and height !== auto then after reload editor will be have latest height */ Config.prototype.saveHeightInStorage = false;
JavaScript
UTF-8
18,806
2.546875
3
[]
no_license
Game.Battle.Ai = { iteration: 0, fullStats: { attack: 0, healers: 0, spells: 0 }, turnStep: function() { Game.Battle.Grid.clearGrid( BATTLE_GRID[ gameData.battle.selection.player ] ); gameData.battle.gui.cords = []; var monsters = Game.Battle.Ai.anybodyHere(); var success = false; success = Game.Battle.Ai.healers( monsters ); success = ( success !== true ) ? Game.Battle.Ai.spells( monsters ) : success; success = ( success !== true ) ? Game.Battle.Ai.attack( monsters ) : success; success = ( success !== true ) ? Game.Battle.Ai.move( monsters ) : success; if( gameData.animation.run === false && ( success !== true || monsters.attack.length < 1 ) ) { console.log( 'kaslu na to :)' ); torch.position.x -= 10000; gameData.battle.selection.endTurn = true; return; } }, anybodyHere: function() { var spellName; var lowCostSpell = 0; var currentCost = 0; var character; var monsters = { 'healers': [], 'spells': [], 'attack': [], 'healing': [], 'enemy-spells': [], 'enemy-healers': [], 'enemy-attack': [], 'enemy-intruders': [] }; var limit = []; if( gameData.battle.selection.player === "left" ) { limit = [ 0, Math.round( gameData.battle.plane.gridWidth / 3 ) ]; } else { limit = [ Math.round( gameData.battle.plane.gridWidth - ( gameData.battle.plane.gridWidth / 3 ) ), gameData.battle.plane.gridWidth ]; } //Trace battle grid for( x in gameData.battle.selection.hero.monsters ) { for( y in gameData.battle.selection.hero.monsters[x] ) { //Enemy monsters if( gameData.battle.selection.enemyHero.monsters[x][y] !== 0 ) { character = gameData.battle.selection.enemyHero.monsters[x][y]; character['cords'] = [ x, y ]; monsters['enemy-attack'].push( character ); //Enemy Intruders if( x >= limit[0] && x <= limit[1] ) monsters['enemy-intruders'].push( character ); //Enemy Healer if( gameData.battle.selection.enemyHero.monsters[x][y].stats.healing === true && gameData.battle.selection.enemyHero.monsters[x][y].manaRemain >= gameData.battle.selection.enemyHero.monsters[x][y].stats.magic ) monsters['enemy-healers'].push( character ); for( spell in gameData.battle.selection.enemyHero.monsters[x][y].stats.spellsList ) { spellName = gameData.battle.selection.enemyHero.monsters[x][y].stats.spellsList[ spell ]; currentCost = spellsList[spellName].manaCost * gameData.battle.selection.enemyHero.monsters[x][y].stats.magic; lowCostSpell = ( currentCost < lowCostSpell ) ? currentCost : lowCostSpell; } //Enemy Magican if( gameData.battle.selection.enemyHero.monsters[x][y].stats.spell === true && gameData.battle.selection.enemyHero.monsters[x][y].manaRemain >= lowCostSpell ) monsters['enemy-spells'].push( character ); } //Nothing if( gameData.battle.selection.hero.monsters[x][y] === 0 ) continue; //Friendly monsters character = gameData.battle.selection.hero.monsters[x][y]; character['cords'] = [ x, y ]; //First Aid:D if( character.stats.health > character.healthRemain ) monsters.healing.push( character ); //No speed if( character.speedRemain < 1 ) continue; //Friendly healer with mana if( character.stats.healing === true && character.manaRemain > 0 ) monsters.healers.push( character ); //Friendly magican with mana lowCostSpell = 0; currentCost = 0; for( spell in character.stats.spellsList ) { spellName = character.stats.spellsList[ spell ]; currentCost = spellsList[spellName].manaCost * character.stats.magic; lowCostSpell = ( currentCost < lowCostSpell ) ? currentCost : lowCostSpell; } if( character.stats.spell === true && character.manaRemain >= lowCostSpell ) monsters.spells.push( character ) //Attack! monsters.attack.push( character ); } } //Save stats from full battlefield if( Game.Battle.Ai.iteration === 0 ) { Game.Battle.Ai.fullStats.attack = monsters.attack.length; Game.Battle.Ai.fullStats.healers = monsters.healers.length; Game.Battle.Ai.fullStats.spells = monsters.spells.length; } //Remove healers from attack, if is anybody other to attack + 1 /* if( Game.Battle.Ai.fullStats.attack > Game.Battle.Ai.fullStats.healers + 1 ) { var newAttack = []; for( i in monsters.attack ) if( monsters.stats.healing === false ) newAttack.push( monsters.attack[ i ] ); monsters.attack = newAttack; }*/ Game.Battle.Ai.iteration++; return monsters; }, healers: function( monsters ) { try { //No healers or nobody to heal if( monsters['healing'].length < 1 || monsters['healers'].length < 1 ) throw "nobody to heal"; //Find healer monsters['healers'].sort( function( a, b ){ return b['manaRemain'] - a['manaRemain'] } ); if( monsters['healers'][0].manaRemain < monsters['healers'][0].stats.magic ) throw "no mana"; //Find best friend for him:) monsters['healing'].sort( function( a, b ){ return a['healthRemain'] - b['healthRemain'] } ); var healing = Game.Battle.calcHealing( monsters['healers'][0], monsters['healing'][0] ); if( healing.health === 0 ) throw "nobody to heal"; var cords1 = monsters['healers'][0]['cords']; var cords2 = monsters['healing'][0]['cords']; var settings = { 'x': cords1[0], 'y': cords1[1], 'xT': cords2[0], 'yT': cords2[1], 'grid': gameData.battle.selection.hero.grid, 'enemyGrid': gameData.battle.selection.hero.grid, 'withAttack': false, 'withHealing': true, 'withDeath': false, 'damage': 0, 'heal': healing.health, 'nearAttack': false, 'withSpell': false }; gameData.battle.selection.path = []; gameData.battle.selection.selected = true; gameData.battle.selection.x = cords1[0]; gameData.battle.selection.y = cords1[1]; gameData.battle.gui.cords = cords2; torch.position.x = monstersModels[gameData.battle.selection.x][gameData.battle.selection.y].root.position.x; torch.position.z = monstersModels[gameData.battle.selection.x][gameData.battle.selection.y].root.position.z; monsters['healing'][0].healthRemain += healing.health; monsters['healers'][0].manaRemain = ( monsters['healers'][0].manaRemain >= monsters['healers'][0].stats.magic ) ? monsters['healers'][0].manaRemain - monsters['healers'][0].stats.magic : 0; monsters['healers'][0].speedRemain = 0; Game.Battle.Animation.animate( settings ); } catch ( e ) { //Noheal action? return false; } return true; }, spells: function( monsters ) { try { var enemy = false; //If no magican:( go away if( monsters['spells'].length < 1 ) throw "no more magican"; //Find magican with many mana! var attacker = Game.Battle.Ai.findBest( monsters['spells'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestManaFormula ); var lowCostSpell = 0; var lowCostSpellName = ''; var highCostSpell = 0; var highCostSpellName = ''; var currentCost = 0; var spellName; var init = true; for( spell in attacker.stats.spellsList ) { spellName = attacker.stats.spellsList[ spell ]; currentCost = spellsList[spellName].manaCost; if( attacker.manaRemain < currentCost ) continue; if( init ) { init = false; lowCostSpell = highCostSpell = currentCost; lowCostSpellName = highCostSpellName = spellName; continue; } if( currentCost < lowCostSpell ) { lowCostSpell = currentCost; lowCostSpellName = spellName; } else if( currentCost > highCostSpell ) { highCostSpell = currentCost; highCostSpellName = spellName; } } if( lowCostSpell === 0 ) throw "no spell"; var isCaster = ( attacker.stats.attack < attacker.stats.magic ) ? true : false; var homelandDefend = ( isCaster === false && monsters['enemy-intruders'].length > 0 ) ? true : false; if( monsters['enemy-intruders'].length > 0 && isCaster === true ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-intruders'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyIntruder ); } if( enemy === false && monsters['enemy-spells'].length > 0 && homelandDefend === false ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-spells'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyMagican ); } if( enemy === false && monsters['enemy-attack'].length > 0 && homelandDefend === false ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-attack'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyAttack ); } if( enemy === false && monsters['enemy-healers'].length > 0 && homelandDefend === false ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-healers'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyHealer ); } if( enemy === false ) throw "no enemy for magican"; if( enemy.healthRemain <= lowCostSpell ) { attacker.stats.activeSpell = lowCostSpellName; } else if( highCostSpell > 0 ) { attacker.stats.activeSpell = highCostSpellName; } var spell = Game.Battle.calcSpell( attacker, enemy ); var cords1 = attacker['cords']; var cords2 = enemy['cords']; var settings = { 'x': cords1[0], 'y': cords1[1], 'xT': cords2[0], 'yT': cords2[1], 'grid': gameData.battle.selection.hero.grid, 'enemyGrid': gameData.battle.selection.enemyHero.grid, 'withAttack': false, 'withSpell': true, 'withHealing': false, 'withDeath': spell.death, 'damage': spell.damage, 'spell': spellsList[ monsters['spells'][0].stats.activeSpell ], 'nearAttack': true }; Game.Battle.Grid.select( { x: cords1[0], y: cords1[1] } ); gameData.battle.selection.selected = true; gameData.battle.selection.x = cords1[0]; gameData.battle.selection.y = cords1[1]; gameData.battle.gui.cords = cords2; enemy.healthRemain = ( enemy.healthRemain >= spell.damage ) ? enemy.healthRemain - spell.damage : 0; attacker.manaRemain = ( spellsList[ gameData.battle.selection.hero.monsters[gameData.battle.selection.x][gameData.battle.selection.y].stats.activeSpell ].manaCost <= attacker.manaRemain ) ? attacker.manaRemain - spellsList[ gameData.battle.selection.hero.monsters[gameData.battle.selection.x][gameData.battle.selection.y].stats.activeSpell ].manaCost : 0; attacker.speedRemain = 0; Game.Battle.Animation.animate( settings ); } catch ( e ) { //Mo magic action? return false; } return true; }, attack: function( monsters ) { try { if( monsters['attack'].length < 1 ) throw "no attacker here"; var paths; var enemy = false; var move = []; var attacker = Game.Battle.Ai.findBest( monsters['attack'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestAttack ); enemy = false; if( monsters['enemy-intruders'].length > 0 && ( attacker.stats.healing === false || ( attacker.stats.healing === true && attacker.manaRemain < 5 ) ) ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-intruders'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyIntruder, attacker ); } if( enemy === false && monsters['enemy-spells'].length > 0 ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-spells'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyMagican, attacker ); } if( enemy === false && monsters['enemy-healers'].length > 0 ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-healers'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyHealer, attacker ); } if( enemy === false && monsters['enemy-attack'].length > 0 ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-attack'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyAttack, attacker ); } if( enemy === false ) throw "nobody to attack"; var cords1 = attacker['cords']; var cords2 = enemy.monster['cords']; Game.Battle.Grid.select( { x: cords1[0], y: cords1[1] } ); Game.Battle.Grid.showGrid( BATTLE_GRID.enemy, { x: cords2[0], y: cords2[1] } ); gameData.battle.selection.path = ( enemy.path === true ) ? [] : enemy.path; var xFrom = parseInt( gameData.battle.selection.x ); var yFrom = parseInt( gameData.battle.selection.y ); var monsterTarget = ( gameData.battle.selection.path.length > 0 ) ? gameData.battle.selection.path[ gameData.battle.selection.path.length - 1 ] : monsterTarget; var attack = Game.Battle.calcAttack( attacker, enemy.monster ); var nearAttack = false; if( Game.Battle.findInGrid( { x: cords2[0], y: cords2[1], x2: xFrom, y2: yFrom } ) === true ) { nearAttack = true; enemy.path = []; gameData.battle.selection.path = []; } else { Game.Battle.Grid.showGridPath( BATTLE_GRID.enemy, gameData.battle.selection.path ); } if( enemy.path !== true && typeof monsterTarget !== "undefined" ) { //Nothing } else { //if( enemy.path === true ) nearAttack = true; } if( nearAttack === true || enemy.path.length > 0 ) { var move = ( nearAttack === true ) ? false : true; var settings = { 'x': cords1[0], 'y': cords1[1], 'xT': cords2[0], 'yT': cords2[1], 'move': move, 'moveX': monsterTarget.x, 'moveY': monsterTarget.y, 'grid': gameData.battle.selection.hero.grid, 'enemyGrid': gameData.battle.selection.enemyHero.grid, 'withAttack': true, 'withHealing': false, 'withDeath': attack.death, 'damage': attack.damage, 'nearAttack': nearAttack, 'withSpell': false }; gameData.battle.gui.cords = cords2; attacker.speedRemain = 0; if( nearAttack === false ) gameData.battle.selection.movePath = Game.Battle.Animation.monsterCordsPath(); Game.Battle.Animation.animate( settings ); return true; } } catch ( e ) { //No attack action? } return false; }, move: function( monsters ) { try { if( monsters['attack'].length < 1 ) throw "no attack"; var enemy = false; var attacker; var attacker = monsters['attack'][0]; if( monsters['enemy-healers'].length > 0 ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-healers'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyHealer, attacker, true ); } if( enemy === false && monsters['enemy-spells'].length > 0 ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-spells'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyMagican, attacker, true ); } if( enemy === false && monsters['enemy-attack'].length > 0 ) { enemy = Game.Battle.Ai.findBest( monsters['enemy-attack'], BATTLE_AI[ gameData.battle.selection.hero.level ].findBestEnemyAttack, attacker, true ); } if( enemy === false ) throw "nobody to attack"; var cords1 = attacker['cords']; var whereMove = enemy.path[ enemy.path.length - 1 ]; gameData.battle.selection.selected = true; gameData.battle.selection.x = cords1[0]; gameData.battle.selection.y = cords1[1]; gameData.battle.selection.path = enemy.path; Game.Battle.Grid.showGrid( BATTLE_GRID.free, { x: cords1[0], y: cords1[1] } ); Game.Battle.Grid.showGridPath( BATTLE_GRID.free, gameData.battle.selection.path ); torch.position.x = monstersModels[gameData.battle.selection.x][gameData.battle.selection.y].root.position.x; torch.position.z = monstersModels[gameData.battle.selection.x][gameData.battle.selection.y].root.position.z; var settings = { 'x': cords1[0], 'y': cords1[1], 'xT': whereMove.x, 'yT': whereMove.y, 'move': true, 'moveX': whereMove.x, 'moveY': whereMove.y, 'grid': gameData.battle.selection.hero.grid, 'enemyGrid': gameData.battle.selection.enemyHero.grid, 'withAttack': false, 'withHealing': false, 'withDeath': false, 'damage': 0, 'nearAttack': false, 'withSpell': false }; attacker.speedRemain = 0; gameData.battle.selection.movePath = Game.Battle.Animation.monsterCordsPath(); Game.Battle.Animation.animate( settings ); return true; } catch ( e ) { } return false; }, findBest: function( monsters, formula, attacker, divided ) { monsters.sort( formula ); return ( typeof attacker === "undefined" ) ? monsters[0] : Game.Battle.Ai.findBestAttackPath( monsters, attacker, divided ); }, findBestAttackPath: function( monsters, attacker, divided ) { var enemy = false; for( j in monsters ) { var path = Game.Battle.Ai.findNearEmpty( attacker['cords'], monsters[j]['cords'], divided ); if( path.length > 0 && path.length < ( attacker.speedRemain + 1 ) ) { enemy = monsters[j]; break; } } return ( enemy === false ) ? false : { monster: enemy, path: path }; }, findNearEmpty: function( from, to, divided ) { divided = ( typeof divided === "undefined" ) ? false : true; from[0] = parseInt( from[0] ); from[1] = parseInt( from[1] ); to[0] = parseInt( to[0] ); to[1] = parseInt( to[1] ); var x, y; var tempTo; var paths = []; var x1 = ( ( to[0] - 1 ) >= 0 ) ? to[0] - 1 : 0; var x2 = ( ( to[0] + 1 ) < ( gameData.battle.plane.gridWidth - 1 ) ) ? ( to[0] + 1 ) : ( gameData.battle.plane.gridWidth - 1 ); var y1 = ( ( to[1] - 1 ) >= 0 ) ? to[1] - 1 : 0; var y2 = ( ( to[1] + 1 ) < ( gameData.battle.plane.gridHeight - 1 ) ) ? ( to[1] + 1 ) : ( gameData.battle.plane.gridHeight - 1 ); for( x = x1; x <= x2; x++ ) { for( y = y1; y <= y2; y++ ) { if( gameData.battle.plane.grid[x][y] !== 0 ) continue; if( x == from[0] && y == from[1] ) return true; tempTo = [ x, y ]; var path = aStar( from, tempTo, gameData.battle.plane.grid, gameData.battle.plane.gridWidth, gameData.battle.plane.gridHeight, true ); if( path.length > 0 && ( gameData.battle.selection.hero.monsters[from[0]][from[1]].speedRemain >= path.length || divided === true ) ) { if( divided === true && gameData.battle.selection.hero.monsters[from[0]][from[1]].speedRemain < path.length ) { var dividedCount = gameData.battle.selection.hero.monsters[from[0]][from[1]].speedRemain; var newPath = []; for( i in path ) { newPath.push( path[i] ); --dividedCount; if( dividedCount === 0 ) { break; } } paths.push( newPath ); } else { paths.push( path ); } } } } if( paths.length > 0 ) { paths.sort( function( a, b ){ return ( a.length ) - ( b.length ) } ); return paths[0]; } return []; } };
C#
UTF-8
327
2.890625
3
[ "MIT" ]
permissive
namespace CSharpScriptingExample { using System; using CSharpScriptingExample.Interfaces; internal class DummyComponent : IScriptableComponent { public void DoSomething(string parameter) { Console.WriteLine("DummyComponent.DoSomething called: {0}", parameter); } } }
C
UTF-8
205
2.609375
3
[]
no_license
#include <stdio.h> #include<string.h> int main() { int i=0,len=0; char a[20]; scanf("%s",&a); scanf("%d",len); for(i=0;i<len,i++) { printf("%s",a); } return 0; }
JavaScript
UTF-8
314
3.609375
4
[]
no_license
"use strict"; //whatever we put in parameters and ... they continue to excist ...that closure function createAddingFunction(num1, num2) { let num3 = 2; return function () { return num1 + num2 + num3; }; } let AddingFunction = createAddingFunction(1, 2); console.log(AddingFunction()); console.log();
Java
UTF-8
1,476
1.984375
2
[]
no_license
package com.stu.fastStep.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.stu.fastStep.service.CouponService; @Controller public class CouponController { @Resource(name="CouponService") private CouponService couponService; @RequestMapping("/getCouponArr") public @ResponseBody String getCouponArr(HttpServletRequest request,HttpServletResponse response)throws Exception { JSONArray json=couponService.getCouponArr(); return json.toJSONString(); } @RequestMapping("/searchCoupon_ready") public @ResponseBody String searchCoupon_ready(HttpServletRequest request,HttpServletResponse response)throws Exception { String input=request.getParameter("inputReady"); JSONArray json=couponService.searchCoupon_ready(input); return json.toJSONString(); } @RequestMapping("/searchCoupon") public @ResponseBody String searchCoupon(HttpServletRequest request,HttpServletResponse response)throws Exception { String input=request.getParameter("input"); JSONArray json=couponService.searchCoupon(input); System.out.println(json); return json.toJSONString(); } }
Python
UTF-8
242
3.3125
3
[]
no_license
def myMin(a,b): return a if a<=b else b import sys input=sys.stdin.readline n=int(input()) c2=0 c5=0 for _ in range(1,n+1): while(_%2==0): _/=2 c2+=1 while(_%5==0): _/=5 c5+=1 print(myMin(c2,c5))
Python
UTF-8
686
3.296875
3
[]
no_license
def getnum(): nums=[] n=input("请输入一个数字,按回车退出:") while n!="": nums.append(eval(n)) n=input("请输入一个数字,按回车退出:") return nums def mean(nums): s=0 for i in nums: s=s+i a=s/len(nums) return a def fanc(nums,mean): d=0.0 for n in nums: d=d+(n-mean)**2 return pow(d/(len(nums)-1),0.5) def mudium(nums): sorted(nums) if len(nums)%2==0: m= nums[len(nums)//2] else: m= (nums[len(nums)//2-1]+nums[len(nums)//2])/2 return m n=getnum() m=mean(n) print("平均数:{},方差:{},中位数:{}".format(m,fanc(n,m),mudium(n)))
Python
UTF-8
3,695
2.796875
3
[]
no_license
import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from .defense import get_aug_data class AdversarialDt(DecisionTreeClassifier): def __init__(self, ord=np.inf, sep_measure=None, attack_model=None, train_type='adv', **kwargs): """Decision Tree Classifier with defense Keyword Arguments: ord {float} -- adversarial example perturbation measure (default: {np.inf}) sep_measure {float} -- The distance measure for data, if None, it will be the same as `ord` (default: {None}) attack_model {Attack Model} -- The Attack Model, only use when `train_type` is 'adv' (default: {None}) train_type {str} -- None for undefended classifier, 'robustv2' for adversarial pruning, 'adv' for adversarial training (default: {'adv'}) Other Arguments follows the original scikit-learn argument (sklearn.tree.DecisionTreeClassifier). """ self.ord = ord self.sep_measure = sep_measure self.attack_model = attack_model self.train_type = train_type if self.train_type is None: pass elif self.train_type == 'adv': self.eps = kwargs.pop('eps') elif self.train_type == 'robust': kwargs['splitter'] = 'robust' #kwargs['eps'] = self.eps elif self.train_type[:7] == 'robust_': # for hybrid kwargs['splitter'] = 'robust' #kwargs['eps'] = self.eps self.train_type = self.train_type[7:] # The modified DecisionTreeClassifier eats the esp argument super().__init__(**kwargs) def fit(self, X, y, eps:float=None): print("original X", np.shape(X), len(y)) self.augX, self.augy = get_aug_data(self, X, y, eps) print("number of augX", np.shape(self.augX), len(self.augy)) return super().fit(self.augX, self.augy) class AdversarialRf(RandomForestClassifier): def __init__(self, ord=np.inf, sep_measure=None, attack_model=None, train_type='adv', **kwargs): """Random Forest Classifier with defense Keyword Arguments: ord {float} -- adversarial example perturbation measure (default: {np.inf}) sep_measure {float} -- The distance measure for data, if None, it will be the same as `ord` (default: {None}) attack_model {Attack Model} -- The Attack Model, only use when `train_type` is 'adv' (default: {None}) train_type {str} -- None for undefended classifier, 'robustv2' for adversarial pruning, 'adv' for adversarial training (default: {'adv'}) Other Arguments follows the original scikit-learn argument (sklearn.tree.RandomForestClassifier). """ self.ord = ord self.sep_measure = sep_measure self.attack_model = attack_model self.train_type = train_type if self.train_type is None: pass elif self.train_type == 'adv': self.eps = kwargs.pop('eps') elif self.train_type == 'robust': kwargs['splitter'] = 'robust' elif self.train_type[:7] == 'robust_': # for hybrid kwargs['splitter'] = 'robust' self.train_type = self.train_type[7:] # The modified RandomForestClassifier eats the esp argument super().__init__(**kwargs) def fit(self, X, y, eps:float=None): print("original X", np.shape(X), len(y)) self.augX, self.augy = get_aug_data(self, X, y, eps) print("number of augX", np.shape(self.augX), len(self.augy)) return super().fit(self.augX, self.augy)
C
UTF-8
2,106
2.734375
3
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
/* $Id: menu.h,v 1.3 2005/07/31 15:30:41 soyt Exp $ ****************************************************************************** Universal menu for ggi Written in 1998 by Hartmut Niemann This software is placed in the public domain and can be used freely for any purpose. It comes without any kind of warranty, either expressed or implied, including, but not limited to the implied warranties of merchantability or fitness for a particular purpose. Use it at your own risk. the author is not responsible for any damage or consequences raised by use or inability to use this program. ****************************************************************************** */ #ifndef _MENU_H #define _MENU_H #include <ggi/ggi.h> #include "window.h" #define MAXENTRIES 9 /* indexes 0 .. 8 but keys 1 ..9. ** any good solution for this?? */ struct menuentry { char * text ; /* menu text to be printed */ char * shortcut ; /* Shortcut key(s) */ int x; /* printing position */ int y; }; struct menu { struct window w; int lastentry ; /* number of last used entry */ struct menuentry entry[MAXENTRIES] ; ggi_color entrycolor; ggi_color selectedcolor; ggi_color selectedbackgroundcolor; /* menu formatting. you should leave the defaults untouched. */ int titleleftskip; /* space left inner border <-> title */ int titlerightskipmin; /* title <-> right inner border */ int entryleftskip; /**/ int entryrightskipmin; int firstlineskip; int entrylineskip; int lastlineskip; const char * toptext; int toptextx; int toptexty; ggi_color toptextcolor; const char * bottomtext; int bottomtextx; int bottomtexty; ggi_color bottomtextcolor; int titlex, titley; /* automatically calculated ! */ }; int default_menu(struct menu *m, ggi_visual_t vis); int calculate_menu(struct menu *m); /* calculates size and positions of elements */ int center_menu(struct menu *m); /* moves menu to center of screen */ int do_menu(struct menu *m , int selected); /* returns -1 for `quit' */ #endif /* _MENU_H */
PHP
UTF-8
5,725
3.078125
3
[ "MIT" ]
permissive
<?php /** * AbstractSearch Class * * Abstract class for the representation of a state search algorithm * @author Lucas Acosta <lucasmacosta@gmail.com> * @version 0.1 * @package peg_solitaire */ include_once 'Problem.php'; include_once 'State.php'; abstract class AbstractSearch { private $problem, $visited_states = array(), $codes_hash = array(); protected $options, $already_visited_states = 0, $is_searching = TRUE, $final_states = array(); function __construct($problem, $options = array()) { if (!($problem instanceof Problem)) throw new Exception("The problem must be a subclass of Problem"); $this->problem = $problem; $this->options = array_merge(array('max_solutions' => 2, 'max_states' => 1000, 'debug' => TRUE), $options); } /** * Returns the search problem * @return Problem */ function getProblem() { return $this->problem; } /** * Return the number of visited states so far * @return integer */ function getVisitedStatesCount() { return count($this->visited_states); } /** * Return the solution states problem * @return array */ function getFinalStates() { return $this->final_states; } /** * Checks if a state was already visited * @return boolean */ function isVisited(&$state) { return $this->__binarySearch($state->getMinCode(), $this->visited_states) !== FALSE; } /** * Set a state as visited. * @param State $state */ function setVisited(&$state) { # For space reasons, only the numeric representation of the state is stored $code = $state->getMinCode(); # This search takes O(log(n)) when the element is not in the list (wich is # always the case for this algorithm) $index = $this->__binarySearch($code, $this->visited_states, true); # This displacement takes at most O(n) for ($i = count($this->visited_states) - 1; $i >= $index; $i--) $this->visited_states[$i+1] = $this->visited_states[$i]; $this->visited_states[$index] = $code; # The total time for the above piece of code is O(log(n)+n), wich is better # than the O(log(n)*n) of quicksort /* $this->visited_states[] = $code; usort($this->visited_states, 'gmp_cmp');*/ $this->codes_hash[gmp_strval($code)] = $state; } /** * Returns a visited state by its code * @param resource $code * @return State */ protected function __getStateFromCode($code) { return $this->codes_hash[gmp_strval($code)]; } /** * Returns all the possible paths that leads to the given state * by using its predecessors * @param State $state * @return array */ function getAllPaths(&$state) { $all_paths = array(); if (count($predecessors = $state->getPredecessors()) == 0) { $all_paths[] = array($state); } else { foreach ($predecessors as $predecessor) { $partial_routes = $this->getAllPaths($predecessor); foreach ($partial_routes as $partial_route) { $partial_route[] = $state; $all_paths[] = $partial_route; } } } return $all_paths; } /** * Builds all the possible paths that are equivalent to the ones found as solutions */ function buildAllPossiblePaths() { foreach($this->final_states as $final_state) { foreach($this->getAllPaths($final_state) as $path) { $next_level_states = array(); for($i = 0; $i < count($path) - 1; $i++) { $current_level_states = array_merge(array($path[$i]), $next_level_states); $next_level_states = array(); foreach($current_level_states as $state) { foreach($this->getProblem()->nextStates($state) as $next_state) { if (gmp_cmp($path[$i+1]->getCode(), $next_state->getCode()) == 0) { if ($state === $path[$i]) continue; $next_state = $path[$i+1]; } if (gmp_cmp($path[$i+1]->getMinCode(), $next_state->getMinCode()) == 0) { $next_state->addPredecessor($state); $next_level_states[] = $next_state; } } } } foreach($next_level_states as $new_final_state) { $this->final_states[] = $new_final_state; } } } } /** * Prints debug info for the search * @param resource $code */ function debug($state = NULL) { echo "Effectively visited states: " . $this->getVisitedStatesCount() . "\n"; echo "Already visited and discarded states: {$this->already_visited_states}\n"; if ($state) { echo "Current state: \n"; echo "$state\n\n"; } } /** * Starts the search */ abstract function doSearch(); /** * Performs a binary search of $needle in $haystack * @param resource $needle * @param array $haystack * @return integer|boolean */ protected function __binarySearch($needle, $haystack, $index_on_false = FALSE) { $max = count($haystack) - 1; $min = 0; while ($min <= $max) { $mid = $min + floor(($max - $min) / 2); if (($result = gmp_cmp($needle, $haystack[$mid])) > 0) { $min = $mid + 1; } elseif ($result < 0) { $max = $mid - 1; } else { return $mid; } } if ($index_on_false) { if (count($haystack) == 0) return 0; return gmp_cmp($needle, $haystack[$mid]) > 0 ? $mid + 1 : $mid; } else return FALSE; } } ?>
C#
UTF-8
1,073
3.828125
4
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Division { class Division { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var count1 = 0; var count2 = 0; var count3 = 0; for (int i = 0; i < n; i++) { var number = int.Parse(Console.ReadLine()); if (number % 2 == 0) { count1++; } if (number % 3 == 0) { count2++; } if (number % 4 == 0) { count3++; } } var p1 = count1 * 100.0 / n; var p2 = count2 * 100.0 / n; var p3 = count3 * 100.0 / n; Console.WriteLine("{0:f2}%", p1); Console.WriteLine("{0:f2}%", p2); Console.WriteLine("{0:f2}%", p3); } } }
PHP
UTF-8
2,823
2.875
3
[]
no_license
<?php // подключаем БД include $_SERVER['DOCUMENT_ROOT'] . '/configs/db.php'; // если есть POST-запрос loginReg? if( isset($_POST["loginReg"]) && isset($_POST["passwordReg"]) && $_POST["loginReg"] != "" && $_POST["passwordReg"] != "" ) { // подготовим запрос в БД $sql = "SELECT * FROM `users` WHERE `login` LIKE '" . $_POST["loginReg"] . "'"; // результаты запроса в переменную $result = mysqli_query($connect, $sql); // подсчитаем найденных пользователей $col_user = mysqli_num_rows($result); // если найден 1 пользователь if($col_user == 1) { ?> <!-- выводим сообщение --> <div class="alert alert-dark" role="alert"> Пользователь уже существует </div> <?php // иначе } else { // создадим запрос в БД $sql = "INSERT INTO users (login, password, lastname) VALUES ('" . $_POST["loginReg"] . "', '" . $_POST["passwordReg"] . "', '" . $_POST["lastname"] . "')"; // если успешно выполнен запрос в БД if(mysqli_query($connect, $sql)) { // переход на главную header("Location: /"); // иначе - сообщение об ошибке } else { echo "<h2>Произошла ошибка</h2>" . mysqli_error($connect); } } } ?> <!-- прорисуем форму регистрации --> <div class="modal fade" id="exampleModalRegistration" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Регистрация</h5> </div> <div class="modal-body"> <form action="/" method="POST"> <div class="form-group"> <label for="exampleInputPassword1">Lastname</label> <input type="text" class="form-control" id="exampleInputPassword1" name="lastname"> </div> <div class="form-group"> <label for="exampleInputEmail1">Login</label> <input type="text" class="form-control" name="loginReg"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="passwordReg"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> </div> </div>
Java
UTF-8
1,804
2.28125
2
[]
no_license
package fsl.ta.toms.roms.service.impl; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.StringUtils; import org.springframework.transaction.annotation.Transactional; import fsl.ta.toms.roms.dao.DAOFactory; import fsl.ta.toms.roms.dataobjects.CDEventDO; import fsl.ta.toms.roms.dataobjects.CDEventRefTypeDO; import fsl.ta.toms.roms.dataobjects.EventAuditDO; import fsl.ta.toms.roms.service.EventAuditService; @Transactional public class EventAuditServiceImpl implements EventAuditService{ private DAOFactory daoFactory; public void setDaoFactory(DAOFactory daoFactory) { this.daoFactory = daoFactory; } @Transactional(readOnly=false) public boolean saveEventAuditDO(EventAuditDO eventAuditDO){ boolean saved = false; Calendar calendar = Calendar.getInstance(); Date currentDate = calendar.getTime(); CDEventDO cdEventDO = new CDEventDO(); CDEventRefTypeDO eventRefType1 = new CDEventRefTypeDO(); CDEventRefTypeDO eventRefType2 = new CDEventRefTypeDO(); cdEventDO = (CDEventDO) daoFactory.getEventAuditDAO().find(CDEventDO.class, eventAuditDO.getEventCode()); eventAuditDO.setEvent(cdEventDO); if(StringUtils.isNotBlank(eventAuditDO.getRefType1Code())){ eventRefType1 = (CDEventRefTypeDO) daoFactory.getEventAuditDAO().find(CDEventRefTypeDO.class, eventAuditDO.getRefType1Code()); eventAuditDO.setRefType1(eventRefType1); } if(StringUtils.isNotBlank(eventAuditDO.getRefType2Code())){ eventRefType2 = (CDEventRefTypeDO) daoFactory.getEventAuditDAO().find(CDEventRefTypeDO.class, eventAuditDO.getRefType2Code()); eventAuditDO.setRefType2(eventRefType2); } eventAuditDO.getAuditEntry().setCreateDTime(currentDate); saved = daoFactory.getEventAuditDAO().saveEventAuditDO(eventAuditDO); return saved; } }
C++
UTF-8
2,092
3.21875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void buildTree(int *arr, int *tree, int treeNode, int start, int end){ if(start == end){ tree[treeNode] = arr[start]; return; } int mid = (start + end)/2; buildTree(arr,tree,2*treeNode,start,mid); buildTree(arr,tree,2*treeNode+1,mid+1,end); int bits = end-mid; int mul = pow(2,bits); tree[treeNode] = (mul*tree[2*treeNode] + tree[2*treeNode+1])%3; } void updateTree(int *arr, int *tree, int treeNode, int start, int end, int index){ if(start == end){ arr[start] = 1; tree[treeNode] = 1; return; } int mid = (start + end)/2; if(index > mid) updateTree(arr,tree,2*treeNode+1,mid+1,end,index); else updateTree(arr,tree,2*treeNode,start,mid,index); int bits = end - mid; int mul = pow(2,bits); tree[treeNode] = (mul*tree[2*treeNode] + tree[2*treeNode+1])%3; } int query(int *tree, int treeNode, int start, int end, int left, int right){ if(start > right || end < left) return 0; if(start >= left && end <= right){ int bits = right-end; int mul = pow(2,bits); return (tree[treeNode]*mul)%3; } int mid = (start + end)/2; int left_child = query(tree,2*treeNode,start,mid,left,right); int right_child = query(tree,2*treeNode+1,mid+1,end,left,right); return (left_child + right_child)%3; } int main(){ int n; cin >> n; int *arr = new int[n]; for(int i = 0; i < n; i++) cin >> arr[i]; int *tree = new int[4*n](); int q; cin >> q; for(int i = 0; i < q; i++){ int t; cin >> t; if(t == 0){ int left,right; int result = query(tree,1,0,n-1,left-1,right-1); std::cout << result << '\n'; } else{ int index; cin >> index; updateTree(arr,tree,1,0,n-1,index); } } delete[] arr; delete[] tree; return 0; }
Python
UTF-8
980
3.5625
4
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 10 21:27:24 2020 @author: jaga """ ''' Solution of Second order ODE using RK4 method ''' import matplotlib.pyplot as plt import numpy as np # r is an array with r[0]=y and r[1]=z(=dy/dx) def f(x,r): dydx=r[1] dzdx=2*r[1]-r[0]+x*(np.exp(x)-1) return np.array([dydx,dzdx]) # initial values of [y , y'] r=np.array([0.0,0.0]) h=0.001 y_sol=[] x_sol=[] x=0 # initial value of x x_f=1 while x<=x_f + h: # h is added to to append the y(x_f) y_sol.append(r[0]) x_sol.append(x) # RK4 formula for the y(x(i+1)) k1=h*f(x,r) k2=h*f(x+0.5*h,r+0.5*k1) k3=h*f(x+0.5*h,r+0.5*k2) k4=h*f(x+h,r+k3) r=r+(k1+2*k2+2*k3+k4)/6.0 x=x+h plt.plot(x_sol,y_sol,label="Numerical solution") plt.xlabel('x', fontsize=13) plt.ylabel('y(x)', fontsize=13) plt.title('Solution Using RK4 Method') plt.legend() plt.show()
Java
UTF-8
7,904
1.679688
2
[ "Apache-2.0" ]
permissive
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.gateway.reactive.debug.policy.steps; import com.google.common.base.Stopwatch; import io.gravitee.definition.model.debug.DebugStepError; import io.gravitee.definition.model.debug.DebugStepStatus; import io.gravitee.gateway.debug.reactor.handler.context.AttributeHelper; import io.gravitee.gateway.reactive.api.ExecutionFailure; import io.gravitee.gateway.reactive.api.ExecutionPhase; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Single; import java.io.Serializable; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @author Yann TAVERNIER (yann.tavernier at graviteesource.com) * @author Guillaume LAMIRAND (guillaume.lamirand at graviteesource.com) * @author GraviteeSource Team */ public abstract class PolicyStep<T> { public static final String DIFF_KEY_HEADERS = "headers"; public static final String DIFF_KEY_PARAMETERS = "parameters"; public static final String DIFF_KEY_PATH = "path"; public static final String DIFF_KEY_PATH_PARAMETERS = "pathParameters"; public static final String DIFF_KEY_METHOD = "method"; public static final String DIFF_KEY_CONTEXT_PATH = "contextPath"; public static final String DIFF_KEY_ATTRIBUTES = "attributes"; public static final String DIFF_KEY_BODY_BUFFER = "bodyBuffer"; public static final String DIFF_KEY_BODY = "body"; public static final String DIFF_KEY_STATUS_CODE = "statusCode"; public static final String DIFF_KEY_REASON = "reason"; protected final String id; protected final String policyId; protected final ExecutionPhase executionPhase; protected final String flowPhase; protected final Stopwatch stopwatch; protected DebugStepStatus status; protected String condition; protected DebugStepError error; protected boolean ended = false; private PolicyStepState inputState; private Map<String, Object> diffMap; protected PolicyStep(final String policyId, final ExecutionPhase executionPhase, final String flowPhase) { this.id = UUID.randomUUID().toString(); this.policyId = policyId; this.executionPhase = executionPhase; this.flowPhase = flowPhase; this.stopwatch = Stopwatch.createUnstarted(); } public Completable pre(final T source, final Map<String, Object> attributes) { return saveInputState(source, AttributeHelper.filterAndSerializeAttributes(attributes)) .doOnSuccess(policyStepState -> { this.inputState = policyStepState; starTimeWatch(); }) .ignoreElement(); } protected abstract Single<PolicyStepState> saveInputState(final T source, final Map<String, Serializable> inputAttributes); public Completable post(final T source, final Map<String, Object> attributes) { return Completable .fromRunnable(this::stopTimeWatch) .andThen(computeDiff(source, this.inputState, AttributeHelper.filterAndSerializeAttributes(attributes))) .doOnSuccess(computedDiffMap -> { this.diffMap = computedDiffMap; this.inputState = null; this.status = this.status == null ? DebugStepStatus.COMPLETED : this.status; }) .ignoreElement(); } protected abstract Single<Map<String, Object>> computeDiff( final T source, final PolicyStepState inputState, final Map<String, Serializable> outputAttributes ); public Map<String, Object> getDiff() { if (diffMap == null) { diffMap = new HashMap<>(); } return diffMap; } protected PolicyStepState getInputState() { return inputState; } protected void starTimeWatch() { if (!stopwatch.isRunning()) { this.stopwatch.start(); } } protected void stopTimeWatch() { if (stopwatch.isRunning()) { this.stopwatch.stop(); } } public Completable error(Throwable ex) { return Completable.fromRunnable(() -> { stopTimeWatch(); this.status = DebugStepStatus.ERROR; this.error = new DebugStepError(); this.error.setMessage(ex.getMessage()); }); } public Completable error(ExecutionFailure executionFailure) { return Completable.fromRunnable(() -> { stopTimeWatch(); this.status = DebugStepStatus.ERROR; this.error = new DebugStepError(); this.error.setMessage(executionFailure.message()); this.error.setKey(executionFailure.key()); this.error.setStatus(executionFailure.statusCode()); this.error.setContentType(executionFailure.contentType()); }); } public void onConditionFilter(String condition, boolean isConditionTruthy) { this.condition = condition; if (!isConditionTruthy) { this.status = DebugStepStatus.SKIPPED; } } public String getId() { return id; } public String getPolicyId() { return policyId; } public ExecutionPhase getExecutionPhase() { return executionPhase; } public String getFlowPhase() { return flowPhase; } public Duration elapsedTime() { return this.stopwatch.elapsed(); } public DebugStepStatus getStatus() { return status; } public String getCondition() { return condition; } public DebugStepError getError() { return error; } public boolean isEnded() { return ended; } public void end() { this.ended = true; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PolicyStep<?> that = (PolicyStep<?>) o; return ( ended == that.ended && Objects.equals(id, that.id) && Objects.equals(policyId, that.policyId) && executionPhase == that.executionPhase && Objects.equals(flowPhase, that.flowPhase) && Objects.equals(stopwatch, that.stopwatch) && status == that.status && Objects.equals(condition, that.condition) && Objects.equals(error, that.error) && Objects.equals(inputState, that.inputState) && Objects.equals(diffMap, that.diffMap) ); } @Override public int hashCode() { return Objects.hash(id, policyId, executionPhase, flowPhase, stopwatch, status, condition, error, ended, inputState, diffMap); } @Override public String toString() { return ( getClass().getSimpleName() + "{" + "id='" + id + '\'' + "policyId='" + policyId + '\'' + ", executionPhase=" + executionPhase + ", stopwatch=" + stopwatch.elapsed(TimeUnit.NANOSECONDS) + " ns" + ", diffMap='" + diffMap + '\'' + '}' ); } }
Java
UTF-8
301
1.96875
2
[]
no_license
package game.db.access; /** * 数据库存取异常 * * @author ming 创建时间:2013-11-19 */ public class DataAccessException extends RuntimeException { private static final long serialVersionUID = 1L; public DataAccessException(Throwable cause) { super(cause); } }
Java
UTF-8
756
1.914063
2
[]
no_license
package com.limon.http.coder; import com.limon.http.xml.XmlNode; @XmlNode(name="PayOrderReq") public class PayOrderReq { @XmlNode(name="Uid") private String Uid; @XmlNode(name="Oid") private String Oid; @XmlNode(name="PayNo") private String PayNo; @XmlNode(name="PayType") private String PayType; public String getUid() { return Uid; } public void setUid(String uid) { Uid = uid; } public String getOid() { return Oid; } public void setOid(String oid) { Oid = oid; } public String getPayNo() { return PayNo; } public void setPayNo(String payNo) { PayNo = payNo; } public String getPayType() { return PayType; } public void setPayType(String payType) { PayType = payType; } }
JavaScript
UTF-8
1,148
2.515625
3
[]
no_license
'use strict'; const ElasticSearchConfigError = require('./elasticsearch-config-error'); const ELASTICSEARCH_CONFIG_STRUCT = { protocol: 'string', host: 'string', port: 'number', user: 'string', password: 'string', limit: 'number', prefix: 'string', awsCredentials: 'boolean', requestTimeout: 'number', maxRetries: 'number' }; /** * @class ConfigValidator * @classdesc Validates config struct */ class ConfigValidator { /** * Validate the received config struct * @throws if the struct is invalid */ static validate(config) { if(!config || typeof config !== 'object' || Array.isArray(config)) throw new ElasticSearchConfigError('Invalid config: Should be an object.', ElasticSearchConfigError.codes.INVALID_CONFIG); for(const [setting, type] of Object.entries(ELASTICSEARCH_CONFIG_STRUCT)) { if(config[setting] && typeof config[setting] !== type) { // eslint-disable-line throw new ElasticSearchConfigError(`Invalid setting '${setting}': Expected ${type} but received ${typeof config[setting]}.`, ElasticSearchConfigError.codes.INVALID_SETTING); } } } } module.exports = ConfigValidator;
Python
UTF-8
9,412
2.640625
3
[]
no_license
import datetime import matplotlib.pyplot as plt from scipy.misc import imread import numpy as np def parseNL(path): f = open(path, 'r') names = [] labels = [] lines = f.readlines() for line in lines: if len(line.split()) == 1: name = line.split() names.append(name[0]) if len(line.split()) == 2: [name, label] = line.split() names.append(name) labels.append(label) if len(labels) == 0: return names else: return names, labels def timeDiff(name1, name2): # formate: N20031221G030001 date1 = datetime.datetime(int(name1[1:5]), int(name1[5:7]), int(name1[7:9]), int(name1[10:12]), int(name1[12:14]), int(name1[14:16])) date2 = datetime.datetime(int(name2[1:5]), int(name2[5:7]), int(name2[7:9]), int(name2[10:12]), int(name2[12:14]), int(name2[14:16])) return (date2-date1).seconds def sampleImages(names, mode='Uniform', timediff = 60, sampleNum = 500): if mode == 'Uniform': lastImg = names[0] sampledImgs = [] ids = [] # sampledLabels = [] sampledImgs.append(lastImg) ids.append(0) # sampledLabels.append(labels[0]) id = 0 for name in names: if timeDiff(sampledImgs[-1], name) >= timediff: sampledImgs.append(name) ids.append(id) # sampledLabels.append(labels[id]) id = id + 1 return ids, sampledImgs if mode == 'random': import random # sampledImgs = [] # ids = [] # idx = range(len(names)) random.shuffle(names) # for i in range(sampleNum): # sampledImgs.append(names[idx[i]]) # ids.append(idx[i]) return names[:sampleNum] def writeArrangeImgsToFile(arrangeImgs, filePath, labelAdjust=None, addType=None): with open(filePath, 'w') as f: for label, images in arrangeImgs.iteritems(): if labelAdjust is not None: label = str(int(label) + labelAdjust) for name in images: if addType is not None: name += addType f.write(name + ' ' + label + '\n') return 0 def arrangeToClasses(names, labels, classNum=4, classLabel=[['1'], ['2'], ['3'], ['4']]): arrangeImgs = {} rawTypes = {} for i in range(classNum): arrangeImgs[str(i+1)] = [] rawTypes[str(i+1)] = [] for i in range(len(names)): for j in range(classNum): if labels[i] in classLabel[j]: arrangeImgs[str(j+1)].append(names[i]) rawTypes[str(j+1)].append(labels[i]) if classNum == 4: return arrangeImgs if classNum < 4: return arrangeImgs, rawTypes def arrangeToDays(names, labels): name_days = {} label_days = {} days = [] names_num = len(names) for i in xrange(names_num): name = names[i] label = labels[i] day = name[1:9] if day not in name_days: name_days[day] = [] label_days[day] = [] days.append(day) name_days[day].append(name) label_days[day].append(label) return name_days, label_days, days def splitConfigFile(sourceFile, savePathes=['../../Data/train_day16.txt', '../../Data/test_day3.txt'], splitGroups=[range(15), range(15, 19)], isBalabceSamples=[True, False], labelAdjust=None, addType=None): [names, labels] = parseNL(sourceFile) names_days, labels_days, days = arrangeToDays(names, labels) groups_num = len(splitGroups) for i in xrange(groups_num): group_i = splitGroups[i] savePath_i = savePathes[i] isBalance_i = isBalabceSamples[i] group_i_dayNum = len(group_i) names_i = [] labels_i = [] for j in xrange(group_i_dayNum): names_i += names_days[days[group_i[j]]] labels_i += labels_days[days[group_i[j]]] arrangeImgs_i = arrangeToClasses(names_i, labels_i, classNum=4, classLabel=[['1'], ['2'], ['3'], ['4']]) if isBalance_i: max_balance_num = min([len(x) for x in arrangeImgs_i.values()]) arrangeImgs_i = balanceSample(arrangeImgs_i, max_balance_num) writeArrangeImgsToFile(arrangeImgs_i, savePath_i, labelAdjust, addType) return 0 def balanceSample(arrangedImgs, sampleNum): for c in arrangedImgs: arrangedImgs[c] = sampleImages(arrangedImgs[c], mode='random', sampleNum=sampleNum) return arrangedImgs def compareLabeledFile(file_std, file_compare, labelAdjust=None, addType=None): [names_std, labels_std] = parseNL(file_std) [names_compare, labels_compare] = parseNL(file_compare) flag = True for i in range(len(names_compare)): name_c = names_compare[i] if addType is not None: name_c = name_c[:-len(addType)] std_idx = names_std.index(name_c) label_c = labels_compare[i] if labelAdjust is not None: label_c = str(int(label_c)+labelAdjust) label_std = labels_std[std_idx] if label_std != label_c: flag = False break return flag def findTypes(sourceFile, names): [sourceNames, sourceTypes] = parseNL(sourceFile) types = [] for n in names: idx = sourceNames.index(n) types.append(sourceTypes[idx]) return types def splitToClasses(sourceFile, names): types = findTypes(sourceFile, names) cs = set(types) # typesNum = len(cs) splitImgs = {} for i in cs: splitImgs[i] = [] for j in range(len(names)): splitImgs[types[j]].append(names[j]) return splitImgs def showGrid(im, gridList): fig, ax = plt.subplots(figsize=(12, 12)) if len(im.shape) == 2: ax.imshow(im, aspect='equal', cmap='gray') else: ax.imshow(im, aspect='equal') for grid in gridList: ax.add_patch( plt.Rectangle((grid[1], grid[0]), grid[3], grid[2], fill=False, edgecolor='yellow', linewidth=1) ) plt.axis('off') plt.tight_layout() plt.draw() def showProposals(im, proposals): # box format: [x1, x2, y1, y2] fig, ax = plt.subplots(figsize=(12, 12)) if len(im.shape) == 2: ax.imshow(im, aspect='equal', cmap='gray') else: ax.imshow(im, aspect='equal') for i in xrange(proposals.shape[0]): box_i = proposals[i, :] ax.add_patch( plt.Rectangle((box_i[0], box_i[1]), box_i[2] - box_i[0], box_i[3] - box_i[1], fill=False, edgecolor='yellow', linewidth=0.35) ) plt.axis('off') plt.tight_layout() plt.draw() def calculateImgsMean(imgsFile, dataFolder, imgType=None): [names, labels] = parseNL(imgsFile) mean = 0. for name in names: if imgType is not None: imgFile = dataFolder + name + imgType else: imgFile = dataFolder + name im = imread(imgFile) mean += im.mean() mean = mean / len(names) print(imgsFile,'mean:',mean) return mean def adjustLables(labelFile, adjust=-1): [names, labels] = parseNL(labelFile) labels_num = [int(x) for x in labels] labels_num = list(np.array(labels_num) + adjust) labels = [str(x) for x in labels_num] with open(labelFile, 'w') as f: for i in range(len(labels)): name = names[i] label = labels[i] f.write(name + ' ' + label + '\n') return 0 def selectTypeImages(labelFile, select_types, savePath=None, withExt=None): [names, labels] = parseNL(labelFile) imgs_dic = arrangeToClasses(names, labels) imgs_select = {} for t in select_types: imgs_select[t] = imgs_dic[t] if savePath is not None: f = open(savePath, 'w') for k, v in imgs_select.iteritems(): for img in v: if withExt is not None: f.write(img + withExt + ' ' + k + '\n') else: f.write(img + ' ' + k + '\n') f.close() return imgs_select if __name__ == '__main__': allLabels = '../../Data/Alllabel2003_38044.txt' savePathes = ['../../Data/train_day16_all.txt', '../../Data/test_day3_all.txt'] imgType = '.jpg' # days = ['20031221', '20031222', '20031223', '20031224', '20031225', '20031226', '20031227', '20031228', '20031229', # '20031230', '20031231', '20040101', '20040102', '20040103', '20040112', '20040114', '20040116', '20040117', # '20040118'] [names, labels] = parseNL(allLabels) names_days, labels_days, days = arrangeToDays(names, labels) splitConfigFile(allLabels, savePathes=savePathes, labelAdjust=-1, addType=imgType, isBalabceSamples=[True, False]) # calculateImgsMean(savePathes[0], dataFolder='../../Data/all38044JPG/') print(compareLabeledFile(allLabels, savePathes[0], labelAdjust=1, addType=imgType)) print(compareLabeledFile(allLabels, savePathes[1], labelAdjust=1, addType=imgType)) print(days) # labelFile1 = '../../Data/train_16_3_7_2663.txt' # adjustLables(labelFile1) # select = '../../Data/all_arc.txt' # selectTypeImages(allLabels, ['1'], select, withExt='.jpg')
JavaScript
UTF-8
4,237
2.546875
3
[]
no_license
import React, { Component } from "react"; import "./App.css"; import axios from "axios"; import Header from "./components/header/Header"; import Players from "./components/players/Players"; import NewPlayer from "./components/newPlayer/NewPlayer"; import Team from "./components/team/Team"; import Filter from "./components/filter/Filter"; class App extends Component { constructor() { super(); this.state = { players: [], team: [], totalValue: 0, position: "", teamPlaying: "", }; } getPlayers = () => { let position = this.state.position === "All positions" ? undefined : this.state.position; let team = this.state.teamPlaying === "All teams" ? undefined : this.state.teamPlaying; let queries = { position, team, }; let queryString = ""; for (let key in queries) { if (queries[key]) { queryString += "&" + key + "=" + queries[key]; } } axios.get(`http://localhost:4040/api/players?${queryString}`).then(res => { // console.log(res.data); this.setState({ players: res.data, }); }); }; componentDidMount() { this.getPlayers(); } handleDelete = id => { axios.delete(`http://localhost:4040/api/players/${id}`).then(res => { // console.log(res.data); this.setState({ players: res.data, }); }); }; handleAddToTeam = id => { const index = this.state.players.findIndex(e => e.id === +id); const found = this.state.team.find( e => e.name === this.state.players[index].name ); if (found) { alert("The player is already in the list"); } else { const newTeammate = this.state.players[index]; this.setState({ team: [...this.state.team, newTeammate], totalValue: this.state.totalValue + newTeammate.value, }); } //AQUI TERMINA MI CODIGO // const filteredPlayer = this.state.players.filter(e => e.id === +id); // console.log({ filteredPlayer }); // let updatedTeam = [...this.state.team, ...filteredPlayer]; // console.log({ updatedTeam }); // // console.log(filteredTeam); // const totalValue = updatedTeam.reduce((acc, cur) => { // return (acc += cur.value); // }, 0); // this.setState({ // team: updatedTeam, // totalValue, // }); }; handleRemoveTeam = id => { const filteredTeam = this.state.team.filter(e => e.id !== +id); const totalValue = filteredTeam.reduce((acc, cur) => { return (acc += cur.value); }, 0); this.setState({ team: filteredTeam, totalValue, }); }; handlePositionSelection = e => { // console.log(e.target.value); this.setState({ position: e.target.value, }); }; handleTeamPlaying = e => { // console.log(e.target.value); this.setState({ teamPlaying: e.target.value, }); }; componentDidUpdate(prevProps, prevState) { if ( prevState.position !== this.state.position || prevState.teamPlaying !== this.state.teamPlaying ) { this.getPlayers(); } } render() { // console.log(this.state.teamPlaying); const { players, team, totalValue, position, teamPlaying } = this.state; return ( <div> <Header /> <div className="main"> <section className="body"> <NewPlayer getPlayers={this.getPlayers} /> <Filter handlePositionSelection={this.handlePositionSelection} position={position} handleTeamPlaying={this.handleTeamPlaying} teamPlaying={teamPlaying} /> <Players playersList={players} delete={this.handleDelete} getPlayers={this.getPlayers} handleAddToTeam={this.handleAddToTeam} handleRemoveTeam={this.handleRemoveTeam} /> </section> <aside className="sidebar"> <Team teamToBuild={team} handleRemoveTeam={this.handleRemoveTeam} totalValue={totalValue} /> </aside> </div> </div> ); } } export default App;
Python
UTF-8
1,297
4.84375
5
[]
no_license
#!/usr/bin/python3 """ Objectives Familiarize the student with: using basic instructions related to lists; creating and modifying lists. Scenario There once was a hat. The hat contained no rabbit, but a list of five numbers: 1, 2, 3, 4, and 5. Your task is to: write a line of code that prompts the user to replace the middle number in the list with an integer number entered by the user (step 1) write a line of code that removes the last element from the list (step 2) write a line of code that prints the length of the existing list (step 3.) """ hatList = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat. print("Current list: ", hatList) print("Current list lenght: ",len(hatList)) # Step 1: write a line of code that prompts the user # to replace the middle number with an integer number entered by the user. hatList[2] = input("Please enter a integer number to replace the middle number: ") print("Current list: ", hatList) print("Current list lenght: ",len(hatList)) # Step 2: write a line of code here that removes the last element from the list. del(hatList[len(hatList) - 1]) # Step 3: write a line of code here that prints the length of the existing list. print("Current list: ", hatList) print("Current list lenght: ",len(hatList))
PHP
UTF-8
711
3.734375
4
[]
no_license
<?php /** * En klass som beskriver ett namn */ class Name { /** * Instansvariabler */ private $firstName; private $lastName; private $gender; /** * Konstruktor */ public function __construct($firstName, $lastName, $gender) { $this->firstName = $firstName; $this->lastName = $lastName; $this->gender = $gender; } /** * En metdod som konverterar ett objekt till en array */ public function toArray() { $array = array( "firstname" => $this->firstName, "lastname" => $this->lastName, "gender" => $this->gender, ); return $array; } }
PHP
UTF-8
970
2.765625
3
[]
no_license
<?php declare(strict_types=1); namespace adeynes\PM84\functions; use pocketmine\math\Vector3; class BulbFlower implements PM84Function { /** @return float[] */ public function getXDomainBounds(): array { return [-2, 2]; } /** @return float[] */ public function getYDomainBounds(): array { return [-2, 2]; } /** @return float[] */ public function getZDomainBounds(): array { return [-2.5, 2.5]; } /** @return float[] */ public function getUBounds(): array { return [0, pi()]; } /** @return float[] */ public function getVBounds(): array { return [0, 2*pi()]; } public function function_(float $u, float $v): Vector3 { $r = sin(4*$u)**3 + cos(2*$u)**3 + sin(6*$v)**2 + cos(6*$v)**4; return new Vector3( $r * sin($u) * sin($v), $r * sin($u) * cos($v), $r * cos($u) ); } }
C
UTF-8
466
3.03125
3
[]
no_license
#include <stdio.h> #include <errno.h> #include <fcntl.h> int main(void) { char buf[1024]; int n; int flags; flags = fcntl(0, F_GETFL); flags = flags | O_NONBLOCK; fcntl(0, F_SETFL, flags); again: n = read(0, buf, 1024); if(n == -1){ if(errno == EWOULDBLOCK){ printf("no data...\n"); sleep(3); goto again; }else return -1; } write(1, buf, n); return 0; }
Python
UTF-8
1,159
2.578125
3
[]
no_license
import peewee # import sqlite3 # import psycopg2 # import PyMySQL from peewee import * print "connect db" # db = MySQLDatabase('space_team', user='root',passwd='3421') db = SqliteDatabase('space_team.db') class ShipModel(peewee.Model): name = CharField() json = TextField() class Meta: database = db class Ship(peewee.Model): name = CharField() json = TextField() manufacture_date = DateField() model = ForeignKeyField(ShipModel, related_name='instances') class Meta: database = db class ShipModuleTask(peewee.Model): module = CharField() task = TextField() ship = ForeignKeyField(Ship, related_name='modules') class Meta: database = db tables_list = [ShipModel, Ship, ShipModuleTask] def create_table_if_necessary(table): if not table.table_exists(): print(table.__name__, "does not exist, creating...") db.create_table(table) print(table.__name__, "created") else: print(table.__name__, "found") print("checking db tables existence") for table in tables_list: create_table_if_necessary(table) print("db tables are ready")
PHP
UTF-8
995
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Listeners; use App\Events\DiscountEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use App\User; use Illuminate\Support\Facades\File; class SendEmailDiscountEvent implements ShouldQueue { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param DiscountEvent $event * @return void */ public function handle(DiscountEvent $event) { // $users = User::all(); // foreach ($users as $user) { // Mail::to($user->email) // ->send(new DiscountEvent($event->discount)); // } $fileName = $event->discount->id . '.txt'; $data = 'Đây là title: '. $event->discount->title . ' ------ với content: ' . $event->discount->content; File::put(public_path('/txt/' . $fileName), $data); return true; } }
TypeScript
UTF-8
783
2.703125
3
[]
no_license
import { PurchaseRecordDTO } from '../contracts/purchased-item-dto'; import { PurchasedItemBase } from '../contracts/purchased-item-base'; export class PurchasedItemVM implements PurchasedItemBase { public id: string; public name: string; public description: string; public isSelected: boolean; constructor(private dto: PurchaseRecordDTO, public isNew = false) { isNew ? this.initNew() : this.initFromDto(dto); this.isSelected = false; } private initNew() { this.id = ''; this.name = 'New Purchase Record'; this.description = ''; } private initFromDto(dto: PurchaseRecordDTO) { this.id = this.dto.id; this.name = this.dto.name; this.description = this.dto.description; } }
PHP
UTF-8
1,366
2.8125
3
[]
no_license
<?php //1. DB接続します try { $pdo = new PDO('mysql:dbname=gs_f01_db13;charset=utf8;host=localhost','root',''); } catch (PDOException $e) { exit('dbError:'.$e->getMessage()); } $stmt = $pdo->prepare("SELECT * FROM gs_bm_table ORDER BY 'date' DESC LIMIT 3"); $status = $stmt->execute(); $last=""; if($status==false){ errorMsg($stmt); }else{ while( $result = $stmt->fetch(PDO::FETCH_ASSOC)){ $last .= '<p><a href="detail.php?id='.$result['id'].'">'; $last .= $result["book"]." -URL:".$result["url"]." -".$result["comment"]." -".$result["date"]; $last .= "</a>"; $last .= ' '; $last .= '<a href="delete.php?id='.$result['id'].'">'; $last .= '[削除]</a></p>'; } } ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>ブックマークアプリ</title> <style>div{padding: 10px;font-size:16px;}</style> </head> <body> <div> <?=$last?> </div> <form method="post" action="insert.php"> <div> <fieldset> <legend>ブックマーク</legend> <label>書籍名:<input type="text" name="book"></label><br> <label>書籍URL:<input type="text" name="url"></label><br> <label>書籍コメント:<textArea name="detail" rows="4" cols="40"></textArea></label><br> <input type="submit" value="送信"> </fieldset> </div> </form> </body> </html>
Python
UTF-8
1,592
3.515625
4
[]
no_license
class Solution: def calculate(self, s: str) -> int: stack = [] # 符号栈 ans = 0 number = 0 # 当前正在合并的数字 for ch in s: if ch.isdigit(): number = number * 10 + int(ch) elif ch == "+" or ch == "-": if stack.count("-") % 2 == 0: ans += number number = 0 else: ans -= number number = 0 if stack and stack[-1] != "(": stack.pop() stack.append(ch) elif ch == "(": stack.append(ch) elif ch == ")": if stack.count("-") % 2 == 0: ans += number number = 0 else: ans -= number number = 0 if stack and stack[-1] != "(": stack.pop() stack.pop() # 删除左括号 if stack: stack.pop() # 删除左括号前的符号 if stack.count("-") % 2 == 0: ans += number else: ans -= number return ans if __name__ == "__main__": print(Solution().calculate("1 + 1")) # 2 print(Solution().calculate(" 2-1 + 2 ")) # 3 print(Solution().calculate("(1+(4+5+2)-3)+(6+8)")) # 23 print(Solution().calculate("2147483647")) # 2147483647 print(Solution().calculate("2-(5-6)")) # 3 print(Solution().calculate("2-4-(8+2-6+(8+4-(1)+8-10))")) # -15
Java
UTF-8
1,161
3.078125
3
[]
no_license
import java.util.ArrayList; import java.util.List; public class ERList { private List<ExchangeRequest> exchangeRequests; private int minDate; private ExchangeRequest minExchangeRequest; public ERList() { exchangeRequests = new ArrayList<>(); minDate = Integer.MAX_VALUE; minExchangeRequest = null; } @Override public String toString() { String ret = "["; for (ExchangeRequest p : exchangeRequests) { ret += p.toString(); } ret += "]"; return ret; } public void addExchangeRequest(ExchangeRequest p) { exchangeRequests.add(p); if (p.getCreated_at() < minDate) { minDate = p.getCreated_at(); minExchangeRequest = p; } } public int getMinDate() { return minDate; } public ExchangeRequest getMinExchangeRequest() { return minExchangeRequest; } public boolean equalsERL(ERList exchangesRequests) { int j = 0; boolean res = true; for (ExchangeRequest er : exchangesRequests.exchangeRequests) { j = 0; for (ExchangeRequest erThis : this.exchangeRequests) { if (er.equalsER(erThis)) { j = -1; break; } } if (j == 0) { res = false; break; } } return res; } }
Python
UTF-8
457
3.78125
4
[]
no_license
""" Given a sorted array (sorted in non-decreasing order) of positive numbers, find the smallest positive integer value that cannot be represented as sum of elements of any subset of given set. Expected time complexity is O(n). """ def findSmallestNum(array): arrayLen = len(array) res = 1 i=0 while i < arrayLen and array[i] <= res: res += array[i] i += 1 return res array = [1, 1, 1, 1] print findSmallestNum(array)
Swift
UTF-8
2,393
3.09375
3
[]
no_license
// // ViewController.swift // greatNumberGame // // Created by SP on 3/7/18. // Copyright © 2018 Soumya. All rights reserved. // import UIKit class ViewController: UIViewController { var randomNumber = Int(arc4random_uniform(100)+1) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBOutlet weak var guessTextField: UITextField! @IBAction func submitButton(_ sender: UIButton) { print(guessTextField.text) if let guessedNum = guessTextField.text { let guess:Int? = Int(guessedNum) if let num = guess { print(num) print(randomNumber) if num > randomNumber { let alert = UIAlertController(title: "Incorrect", message: "\(num) is too high.", preferredStyle: .alert) alert.view.backgroundColor = .red alert.addAction(UIAlertAction(title: "Guess Again", style: .default, handler: nil)) guessTextField.text = "" self.present(alert, animated: true) } else if num < randomNumber { let alert = UIAlertController(title: "Incorrect", message: "\(num) is too low.", preferredStyle: .alert) alert.view.backgroundColor = .red alert.addAction(UIAlertAction(title: "Guess Again", style: .default, handler: nil)) guessTextField.text = "" self.present(alert, animated: true) } else if num == randomNumber { let alert = UIAlertController(title: "Correct", message: "\(num) is correct.", preferredStyle: .alert) alert.view.backgroundColor = .green alert.addAction(UIAlertAction(title: "Play Again", style: .default, handler: nil)) guessTextField.text = "" randomNumber = Int(arc4random_uniform(100)+1) self.present(alert, animated: true) } } } } }
JavaScript
UTF-8
159
2.8125
3
[ "MIT" ]
permissive
let fire = 0 let start = new Date() let timer = setInterval(() => { if (new Date() - start > 1000) { clearInterval(timer) console.log(fire) } fire++ })
TypeScript
UTF-8
569
2.703125
3
[ "Apache-2.0" ]
permissive
/* tslint:disable */ /* eslint-disable */ /* * Cloud Governance Api * * Contact: support@avepoint.com */ /** * * @export * @enum {string} */ export enum ExpirationType { Duration = 0, Date = 1 } export function ExpirationTypeFromJSON(json: any): ExpirationType { return ExpirationTypeFromJSONTyped(json, false); } export function ExpirationTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): ExpirationType { return json as ExpirationType; } export function ExpirationTypeToJSON(value?: ExpirationType | null): any { return value as any; }
Java
UTF-8
1,507
2.703125
3
[]
no_license
package robertefry.firespread.model.cell; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import robertefry.firespread.model.spread.Spread; import robertefry.firespread.model.terrain.Terrain; import robertefry.firespread.util.GraphicUtil; import robertefry.penguin.target.TargetBlank; /** * @author Robert E Fry * @date 22 Feb 2019 */ public class Cell extends TargetBlank { private Point location; private Terrain terrain; private final Rectangle bounds = new Rectangle(); public Cell( Point location, Terrain terrain ) { this.location = location; this.terrain = terrain; } public Cell( Cell cell ) { this.location = new Point( cell.location ); this.terrain = new Terrain( cell.terrain ); } public synchronized boolean trySpread( Cell cell ) { boolean ignite = false; if ( Spread.pass( this, cell ) ) { if ( terrain.isBurning() ) { ignite = cell.getTerrain().tryIgnite(); } } return ignite; } @Override public void update() { terrain.update(); } @Override public void render( Graphics g ) { if ( ( bounds.width | bounds.height ) > 2 ) GraphicUtil.drawRect( g, bounds, Color.DARK_GRAY ); GraphicUtil.drawCross( g, bounds, terrain.getState().getDrawColor() ); } public Point getLocation() { return location; } public Terrain getTerrain() { return terrain; } public Rectangle getBounds() { return bounds; } public void setBounds( Rectangle r ) { bounds.setBounds( r ); } }
C++
UTF-8
849
3.625
4
[]
no_license
#include <iostream> #include <vector> #include <type_traits> using namespace std; // 3rd - using enable_if to provide specialization template <typename T, typename Enable = void> class A { public: A() { cout << "Primary template\n"; } }; // partial specialization for floating point template <typename T> class A<T, std::enable_if_t<std::is_floating_point_v<T>>> { //class A<T, std::enable_if_t<std::is_floating_point_v<T>, int>> public: A() { cout << "Partial specialization template for floating point\n"; } }; int main(int argc, char* argv[]) { A<int> a1; // int is not floating point, so partial specialization doesnt even exist for it. A<double> a2; // two template class will be found one A<double, void> and the other also A<double, void>, but // the second one is choosen as it is more specialized. return 0; }
C#
UTF-8
963
3.125
3
[]
no_license
public class CompoundWriter:TextWriter { public readonly List<TextWriter> Writers = new List<TextWriter>(); public override void WriteLine(string line) { if(Writers.Any()) foreach(var writer in Writers) writer.WriteLine(line); } //override other TextWriter methods as necessary } ... //When the program starts, get the default Console output stream var consoleOut = Console.Out; //Then replace it with a Compound writer set up with a file writer and the normal Console out. var compoundWriter = new CompoundWriter(); compoundWriter.Writers.Add(consoleOut); compoundWriter.Writers.Add(new TextWriter("c:\temp\myLogFile.txt"); Console.SetOut(compoundWriter); //From now on, any calls to Console's Write methods will go to your CompoundWriter, //which will send them to the console and the file.
PHP
UTF-8
445
2.828125
3
[]
no_license
<?php class VerseOfTheDay extends Database { public function insertVerse ($verset) { $req=$this->getPDO()->prepare("INSERT INTO verse_of_the_day(verse,date) VALUES(?,NOW())"); $req->execute(array($verset)); echo"<p class='text-success'>Verse send</p>"; } public function getVerse() { $req=$this->getPDO()->query("SELECT * FROM verse_of_the_day ORDER BY id DESC"); $res=$req->fetchAll(PDO::FETCH_OBJ); return $res; } }
Java
UTF-8
5,588
1.726563
2
[]
no_license
package com.evs.foodexp.commonPkg.viewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.paging.PagedList; import com.evs.foodexp.models.BookingModel; import com.evs.foodexp.models.CashoutModel; import com.evs.foodexp.models.GoGetModel; import com.evs.foodexp.models.OrderModel; import com.evs.foodexp.models.RequestModel; import com.evs.foodexp.models.ReviewModel; import java.util.List; public class RestaurentRepository { LiveData<PagedList<ReviewModel>> reviews; LiveData<PagedList<OrderModel>> earningitemList ; LiveData<PagedList<BookingModel>> serviceearnings ; LiveData<PagedList<BookingModel>> serviceearningsWeekly ; LiveData<PagedList<GoGetModel>> toGeteearnings ; LiveData<PagedList<GoGetModel>> toGeteearningsWeekly ; LiveData<PagedList<BookingModel>> requestsService ; LiveData<PagedList<RequestModel>> foodrewuest ; LiveData<PagedList<GoGetModel>> togetRequests ; LiveData<PagedList<OrderModel>> spots; LiveData<PagedList<CashoutModel>> cashouts; MutableLiveData<List<OrderModel>> deliverdorderList = new MutableLiveData<>(); MutableLiveData<List<OrderModel>> orderList = new MutableLiveData<>(); MutableLiveData<List<RequestModel>> requestList = new MutableLiveData<>(); MutableLiveData<OrderModel> orderDetials = new MutableLiveData<>(); //////////////////////////////////////////////////////////////////////////////////////////////////// public LiveData<PagedList<BookingModel>> getServiceearningsWeekly() { return serviceearningsWeekly; } public void setServiceearningsWeekly(LiveData<PagedList<BookingModel>> serviceearningsWeekly) { this.serviceearningsWeekly = serviceearningsWeekly; } public LiveData<PagedList<GoGetModel>> getToGeteearnings() { return toGeteearnings; } public void setToGeteearnings(LiveData<PagedList<GoGetModel>> toGeteearnings) { this.toGeteearnings = toGeteearnings; } public LiveData<PagedList<GoGetModel>> getToGeteearningsWeekly() { return toGeteearningsWeekly; } public void setToGeteearningsWeekly(LiveData<PagedList<GoGetModel>> toGeteearningsWeekly) { this.toGeteearningsWeekly = toGeteearningsWeekly; } public LiveData<PagedList<CashoutModel>> getCashouts() { return cashouts; } public void setCashouts(LiveData<PagedList<CashoutModel>> cashouts) { this.cashouts = cashouts; } public LiveData<PagedList<OrderModel>> getSpots() { return spots; } public void setSpots(LiveData<PagedList<OrderModel>> spots) { this.spots = spots; } public MutableLiveData<List<RequestModel>> getRequestList() { return requestList; } public void setRequestList(MutableLiveData<List<RequestModel>> requestList) { this.requestList = requestList; } public LiveData<PagedList<BookingModel>> getRequestsService() { return requestsService; } public void setRequestsService(LiveData<PagedList<BookingModel>> requestsService) { this.requestsService = requestsService; } public LiveData<PagedList<RequestModel>> getFoodrewuest() { return foodrewuest; } public void setFoodrewuest(LiveData<PagedList<RequestModel>> foodrewuest) { this.foodrewuest = foodrewuest; } public LiveData<PagedList<ReviewModel>> getReviews() { return reviews; } public void setReviews(LiveData<PagedList<ReviewModel>> reviews) { this.reviews = reviews; } public LiveData<PagedList<OrderModel>> getEarningitemList() { return earningitemList; } public void setEarningitemList(LiveData<PagedList<OrderModel>> earningitemList) { this.earningitemList = earningitemList; } public void setEarningitemList(MutableLiveData<PagedList<OrderModel>> earningitemList) { this.earningitemList = earningitemList; } public LiveData<PagedList<BookingModel>> getServiceearnings() { return serviceearnings; } public void setServiceearnings(LiveData<PagedList<BookingModel>> serviceearnings) { this.serviceearnings = serviceearnings; } public MutableLiveData<List<OrderModel>> getDeliverdorderList() { return deliverdorderList; } public void setDeliverdorderList(MutableLiveData<List<OrderModel>> deliverdorderList) { this.deliverdorderList = deliverdorderList; } public MutableLiveData<List<OrderModel>> getOrderList() { return orderList; } public void setOrderList(MutableLiveData<List<OrderModel>> orderList) { this.orderList = orderList; } public MutableLiveData<OrderModel> getOrderDetials() { return orderDetials; } public void setOrderDetials(MutableLiveData<OrderModel> orderDetials) { this.orderDetials = orderDetials; } public LiveData<PagedList<GoGetModel>> getTogetRequests() { return togetRequests; } public void setTogetRequests(LiveData<PagedList<GoGetModel>> togetRequests) { this.togetRequests = togetRequests; } private static RestaurentRepository modelRepository; public static RestaurentRepository getInstance() { if (modelRepository != null) { return modelRepository; } else { modelRepository = new RestaurentRepository(); return modelRepository; } } //////////////////////////////////////////////////////////////////////////////////////////////////// }
C#
UTF-8
1,069
3.21875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; /* Matthew Watada * July 27th 2017 * Version 0.6 - Inherits fromt the CardList class... */ namespace LessonA { public class Hand : CardList { // Private Instance variables // Public Properties // (No need for) Constructors // Private Methods protected override void _initialize() { throw new NotImplementedException(); } // Public Methods /// <summary> /// Overrides the base ToString() method. /// </summary> /// <returns></returns> public override string ToString() { string outputString = ""; outputString += "The hand contains: /n"; outputString += "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"; foreach (Card card in this) { outputString += "The " + card.Face + " of " + card.Suit + "\n"; } return outputString; } } }