branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>ashimasingla20/twitter<file_sep>/public/js/script.js
$(document).ready(function() {
trends_selected = [
[],
[],
[]
];
var selected_1 = 0;
var selected_2 = 0;
$.ajax({
type: "GET",
url: 'http://localhost:3001/countries/',
dataType: "JSON",
async: false,
success: function(data) {
$.each(data.countries, function(key, name) {
//appending json data to dropdown country one and country two
$("#country1").append($('<option></option>').val(name).html(name));
$("#country2").append($('<option></option>').val(name).html(name));
});
$('#country1, #country2').change(function() {
//remove the svg so as to plot new each time
d3.select("#chart").selectAll("svg").remove();
// to check if one of the country is selected or both
var country_selected = $(this).attr('id') == 'country1' ? "first_country" : "second_country";
if (country_selected == "first_country") {
selected_1 = 1;
}
if (country_selected == "second_country") {
selected_2 = 1;
}
var country = $(this).val();
//finding common trends
$.ajax({
type: "GET",
url: 'http://localhost:3001/countries/' + country + '/trends/',
dataType: "JSON",
async: false,
success: function(data) {
trends_selected[country_selected] = data.trends.map(function(a) {
return a.name;
});
if (selected_2 && selected_1) {
trends_selected["common"] = trends_selected["first_country"].filter(function(trend) {
return $.inArray(trend, trends_selected["second_country"]) != -1;
});
} else if (selected_1) {
trends_selected["common"] = trends_selected["first_country"];
} else if (selected_2) {
trends_selected["common"] = trends_selected["second_country"];
}
var common_trends = '<ul>';
for (var i = 0; i < trends_selected["common"].length; i++) {
common_trends += '<li>' + trends_selected["common"][i] + '</li>';
}
common_trends += '</ul>';
//displaying common trends info
$('#info').html(common_trends);
plotGraph(trends_selected["common"]);
}
});
});
}
});
function plotGraph() {
var data = [],
sum = 0;
$.each(trends_selected["common"], function() {
sum += this.length;
});
$.each(trends_selected["common"],function(key, value) {
data.push({
"country_name": value,
"percentage": (value.length / sum * 100).toFixed(1)
});
});
var pie = d3.layout.pie()
.value(function(d) {
return d.percentage
})
.sort(null);
var w = 800,
h = 500;
var outer_radius = 250;
var inner_radius = 200;
var color = d3.scale.category10();
//dounut graph
var arc = d3.svg.arc()
.outerRadius(outer_radius)
.innerRadius(inner_radius);
var svg = d3.select("#chart")
.append("svg")
.attr({
width: w,
height: h,
class: 'shadow'
}).append('g')
.attr({
transform: 'translate(' + outer_radius + ',' + h / 2 + ')'
});
var path = svg.selectAll('path')
.data(pie(data))
.enter()
.append('path')
.attr({
d: arc,
fill: function(d, i) {
return color(d.data.country_name);
}
});
//legends
var createLegends = function() {
var text = svg.selectAll('text')
.data(pie(data))
.enter()
.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("dy", ".4em")
.attr("text-anchor", "middle")
.text(function(d) {
return d.data.percentage + "%";
})
.style({
fill: '#fff',
'font-size': '10px'
});
var legend_rect_size = 20;
var legend_spacing = 7;
var legend_height = legend_rect_size + legend_spacing;
var legend = svg.selectAll('.legend')
.data(color.domain())
.enter()
.append('g')
.attr({
class: 'legend',
transform: function(d, i) {
//Just a calculation for x & y position
return 'translate(355,' + ((i * legend_height) - 100) + ')';
}
});
legend.append('rect')
.attr({
width: legend_rect_size,
height: legend_rect_size,
rx: 20,
ry: 20
})
.style({
fill: color,
stroke: color
});
legend.append('text')
.attr({
x: 30,
y: 15
})
.text(function(d) {
return d;
}).style({
'font-size': '14px'
});
};
setTimeout(createLegends, 1000);
}
});
| dd264c1b1deb2d935b0bf30525c3ebf97d6f5876 | [
"JavaScript"
] | 1 | JavaScript | ashimasingla20/twitter | c7ebdd37658a728bf97bc14ebf9985dda1d8e10f | 10f1a0b98fb20e0514de59e2b0bf54574c8977c0 |
refs/heads/master | <file_sep>import React from 'react';
import classes from './Cockpit.css';
const cockpit = (props) => {
const assignedClasses = [];
let btnClass = '';
if (props.showMonths) {
btnClass = classes.Red;
}
if (props.months.length <= 2) {
assignedClasses.push(classes.orange); // assignedClasses = ['orange']
}
if (props.months.length <= 1) {
assignedClasses.push(classes.bold); // assignedClasses = ['orange', 'bold']
}
return (
<div className={classes.cockpit}>
<header className={classes.Appheader}>
<img src="../lime.png" className={classes.Applogo} alt="logo" />
<h1 className={classes.Apptitle}>Weekend React App</h1>
</header>
<p className={assignedClasses.join(' ')}>Dreams, vacations plans, and more...</p>
<p className={classes.Appintro}>
Something is coming soon...
</p>
<button
className={btnClass}
onClick={props.clicked}>Show months</button>
</div>
);
};
export default cockpit;<file_sep>import React, { Component } from 'react';
import classes from './App.css';
import Dates from '../components/Dates/Dates';
import Cockpit from '../components/Cockpit/Cockpit';
import Car from '../components/Car/Car';
class App extends Component {
state = {
months: [
{ id: 'ghjr', month:'May', day:17 },
{ id: 'lkhr', month:'June', day:1 },
{ id: 'svnw', month:'July', day:4 }
],
otherState: 'some other value',
showDays: false
}
monthChangedHandler = (event, id) => {
const dayIndex = this.state.months.findIndex(p => {
return p.id === id;
});
const day = {
...this.state.months[dayIndex]
};
day.name = event.target.value;
const days = [...this.state.months];
days[dayIndex] = day;
this.setState({days: days})
}
deleteDayHandler = (dayIndex) => {
const days = [...this.state.months];
days.splice(dayIndex, 1);
this.setState({months: days});
}
toggleMonthsHandler = () => {
const doesShow = this.state.showMonths;
this.setState({ showMonths: !doesShow}); // to adjust the state
}
render() {
let months = null;
if (this.state.showMonths) {
months = <Dates
months={this.state.months}
clicked={this.deleteDayHandler}
changed={this.monthChangedHandler}/>;
}
return (
<div className={classes.App}>
<Cockpit showMonths={this.state.showMonths}
months={this.state.months}
clicked={this.toggleMonthsHandler}/>
{months}
<Car/>
</div>
);
}
}
export default App;
<file_sep>import React from 'react';
import classes from './Day.css';
const day = (props) => {
const style = {
backgroundColor: 'rgba(245, 232, 28, 0.76)',
font: 'inherit',
borderRadius: '9px',
padding:'8px',
textAlign: 'center',
color: 'inherit'
};
return (
<div className={classes.Day}>
<p onClick={props.click}>I'm {props.month} {props.day}, 2018!</p>
<p>{props.children}</p>
<input style={style} type="text" onChange={props.changed} value={props.month}/>
</div>
)
};
export default day;<file_sep>import React from 'react';
import Day from './Day/Day';
const dates = (props) => props.months.map((day, index) => {
return <Day
click={() => props.clicked(index)}
month={day.month}
day={day.day}
key={day.id}
changed={(event) => props.changed(event, day.id)}/>
});
export default dates;
| d9506a6ae04386d676206b28526f4817b553f826 | [
"JavaScript"
] | 4 | JavaScript | Loratadin/react-weekend-app | 1b24b1f1b8d9435b9c3de6909d09b48a0593fe27 | 28baf50c9fffee2e85262b31f47246d881e10ca1 |
refs/heads/master | <file_sep>package com.example.firebaseauthentication
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.list_items.view.*
class BanditAdapter(val bandits : List<BanditDetail>): RecyclerView.Adapter<BanditAdapter.BanditView>() {
// the viewholder shows the cards described on list items
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BanditView {
return BanditView(LayoutInflater.from(parent.context)
.inflate(R.layout.list_items, parent, false)
)
}
// item count is the number of elements in array of information provided
override fun getItemCount(): Int {
return bandits.size
}
// attach the information from the array into the cards
override fun onBindViewHolder(holder: BanditView, position: Int) {
val bandit = bandits[position]
holder.itemview.banditName.text = bandit.name
holder.itemview.banditDesc.text = bandit.desc
// Glide.with(holder.itemview.context){
// .load(bandit.image)
// .into(holder.itemview,banditImage)
// }
}
class BanditView( val itemview : View) : RecyclerView.ViewHolder(itemview)
}<file_sep>package com.example.firebaseauthentication
import android.app.ProgressDialog
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
// define database connection
val myAuth = FirebaseAuth.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnLogin.setOnClickListener {
// initiate log in process
View -> logIn()
}
logReg.setOnClickListener {
// direct to the register page
startActivity(Intent(this, RegisterActivity:: class.java))
}
}
private fun logIn(){
val progress = ProgressDialog(this)
progress.setTitle("Logging in")
progress.setMessage("Please wait....")
// retrieve data from layout activity
val emailTxt = findViewById<View>(R.id.editMail) as EditText
val passwordTxt = findViewById<View>(R.id.editPassword) as EditText
// extract the email and password as strings
val email = emailTxt.text.toString()
val password = passwordTxt.text.toString()
// check for filled inputs
if(email.isEmpty() or password.isEmpty()){
// display warning text
Toast.makeText(this, "Please fill out all the inputs", Toast.LENGTH_LONG).show()
} else{
// execute log in
progress.show()
myAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, OnCompleteListener { task ->
if (task.isSuccessful){
progress.dismiss()
// confirm log in and redirect
Toast.makeText(this, "Log in Successful", Toast.LENGTH_LONG).show()
startActivity(Intent(this, LandingPage::class.java))
} else{
// Toast.makeText(this, "Log In Error, try again", Toast.LENGTH_LONG).show()
dialogBox("Log In Error", "Wrong credentials. Please try again.")
// clear all fields
emailTxt.setText(null)
passwordTxt.setText(null)
}
})
}
}
private fun dialogBox(title: String, message: String){
val mydialog = AlertDialog.Builder(this)
mydialog.setTitle(title)
mydialog.setMessage(message)
mydialog.setCancelable(false)
mydialog.setPositiveButton("Ok", DialogInterface.OnClickListener{ dialog, which ->
dialog.dismiss()
})
mydialog.create().show()
}
}
<file_sep>rootProject.name='Firebase Authentication'
include ':app'
<file_sep>package com.example.firebaseauthentication
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_bandit_list.*
class BanditList : AppCompatActivity() {
// retrieve the database instance for logging out
val myAuth = FirebaseAuth.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bandit_list)
// manually created list to fit into the cards of the recycler view
val bandits = listOf(
BanditDetail("","<NAME>", "He was infamous for robbery with violence"),
BanditDetail("","<NAME>", "He was infamous for robbery with violence"),
BanditDetail("","<NAME>", "He was infamous for robbery with violence"),
BanditDetail("","<NAME>", "He was infamous for robbery with violence"),
BanditDetail("","<NAME>", "He was infamous for robbery with violence"),
BanditDetail("","<NAME>", "He was infamous for robbery with violence")
)
myRecycler.layoutManager = LinearLayoutManager(this)
myRecycler.adapter = BanditAdapter(bandits)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item!!.itemId == R.id.signOut) {
myAuth.signOut()
Toast.makeText(this, "You have been signed out", Toast.LENGTH_LONG).show()
startActivity(Intent(this, MainActivity::class.java))
}
return super.onOptionsItemSelected(item)
}
}
<file_sep>package com.example.firebaseauthentication
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
class LandingPage : AppCompatActivity() {
// *** Database instance and reference
lateinit var myUsers : DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_landing_page)
// refer to welcome text
val displaytxt = findViewById<View>(R.id.welcomeText) as TextView
// target the information from database
myUsers = FirebaseDatabase.getInstance().getReference("Names")
var user = FirebaseAuth.getInstance().currentUser
var uid = user!!.uid
myUsers.child(uid).child("Name").addValueEventListener( object: ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
TODO("Not yet implemented")
}
@SuppressLint("SetTextI18n")
override fun onDataChange(snapshot: DataSnapshot) {
// import user name and display it on landing page
val result = snapshot.value.toString()
displaytxt.text = "Welcome $result"
}
})
Handler().postDelayed({
startActivity(Intent(this, BanditList::class.java))
finish()
},2000)
}
}
<file_sep>package com.example.firebaseauthentication
import android.app.ProgressDialog
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_register.*
class RegisterActivity : AppCompatActivity() {
// connect to the database
val myAuth = FirebaseAuth.getInstance()
// *** Database reference
lateinit var myUsers : DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
btnReg.setOnClickListener {
// initiate registration
View -> Register()
}
// option to return to the log in menu
regLog.setOnClickListener {
startActivity(Intent(this, MainActivity:: class.java))
}
}
private fun Register(){
// initialise a progress bar
var progress = ProgressDialog(this)
progress.setTitle("Registration")
progress.setMessage("Please wait....")
// *** create the database to hold the user name
myUsers = FirebaseDatabase.getInstance().getReference("Names")
val nameTxt = findViewById<View>(R.id.regName) as EditText
val emailTxt = findViewById<View>(R.id.regMail) as EditText
val passwordTxt = findViewById<View>(R.id.regPass) as EditText
val pcTxt = findViewById<View>(R.id.regPC) as EditText
var name = nameTxt.text.toString()
var email = emailTxt.text.toString()
var password = passwordTxt.text.toString()
var passconfirm = pcTxt.text.toString()
if (name.isEmpty() or email.isEmpty() or password.isEmpty() or passconfirm.isEmpty()){
Toast.makeText(this, "Please fill out all inputs", Toast.LENGTH_LONG).show()
} else{
// check that the passwords match
if (password != passconfirm){
// Toast.makeText(this, "Passwords don't match", Toast.LENGTH_LONG).show()
dialogbox("Password Error", "Passwords don't match!")
clear() // clear fields
} else{
progress.show()
// create user in database
myAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, OnCompleteListener { task ->
progress.dismiss()
if (task.isSuccessful){
// *** add the info to the database using the uid as a reference id
val user = myAuth.currentUser
val uid = user!!.uid
myUsers.child(uid).child("Name").setValue(name)
Toast.makeText(this, "Registration Successful", Toast.LENGTH_LONG).show()
startActivity(Intent(this, MainActivity:: class.java))
} else{
Toast.makeText(this, "Error with registration", Toast.LENGTH_LONG).show()
// clear all fields
clear()
}
})
}
}
}
private fun dialogbox(title: String, message: String){
var mydialog = AlertDialog.Builder(this)
mydialog.setTitle(title)
mydialog.setMessage(message)
mydialog.setCancelable(false)
mydialog.setPositiveButton("Ok", DialogInterface.OnClickListener{ dialog, which ->
dialog.dismiss()
})
mydialog.create().show()
}
private fun clear(){
val nameTxt = findViewById<View>(R.id.regName) as EditText
val emailTxt = findViewById<View>(R.id.regMail) as EditText
val passwordTxt = findViewById<View>(R.id.regPass) as EditText
val pcTxt = findViewById<View>(R.id.regPC) as EditText
emailTxt.setText(null)
nameTxt.setText(null)
passwordTxt.setText(null)
pcTxt.setText(null)
}
}
<file_sep>package com.example.firebaseauthentication
import android.media.Image
data class BanditDetail (
var image: String,
var name: String,
var desc: String
) | 4b7d8f721b928002e421a9ed0a438874f5511e57 | [
"Kotlin",
"Gradle"
] | 7 | Kotlin | lembuss/My-FireBase-Authentication | 2de3ba12ea496685fb6b8a7889ea650916dce0cc | 3d541ec0d080837e652263018ee16abeb3c870ae |
refs/heads/master | <file_sep>package com.alienvault.report.github;
import com.alienvault.model.SimpleIssue;
import com.alienvault.model.SimpleRepo;
import com.alienvault.service.RepositoryService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class GitHubIssueReportTest {
List<SimpleRepo> repoList = new ArrayList<SimpleRepo>();
String expectedReport = "{\n \"issues\" : [ {\"id\":1, \"state\":\"closed\", \"title\":\"test\", \"repository\":\"test/test\", \"create_at\":\"1971-02-28T00:42:11Z\"} ]\n,\"top_day\":{\"day\":\"1971-02-28\", \"occurences\": {\"test/test\": 1}}\n}";
@BeforeEach
void setUp(){
Calendar c1 = Calendar.getInstance();
c1.set(Calendar.MONTH, 1);
c1.set(Calendar.DAY_OF_MONTH, 27);
c1.set(Calendar.YEAR, 1971);
c1.set(Calendar.HOUR, 12);
c1.set(Calendar.MINUTE, 42);
c1.set(Calendar.SECOND, 11);
Date date = c1.getTime();
List<SimpleIssue> issues = new ArrayList<SimpleIssue>();
SimpleIssue issue = new SimpleIssue();
issue.setCreateDate(date);
issue.setId(1);
issue.setRepository("test/test");
issue.setState("closed");
issue.setTitle("test");
issues.add(issue);
SimpleRepo repo = new SimpleRepo("test/test", issues);
this.repoList.add(repo);
}
@Test
void generateReport() {
RepositoryService service = mock(RepositoryService.class);
GitHubIssueReport issueReport = new GitHubIssueReport(service);
String[] repos = {"test/test", "test/test"};
try {
when(service.getRepositoryInformation(Arrays.asList(repos))).thenReturn(this.repoList);
String report = issueReport.generateReport(Arrays.asList(repos));
assertEquals(expectedReport, report);
} catch (Exception e) {
fail("No Exception should be thrown");
}
}
}<file_sep># alienvault
Interview Test
This was a fun little exercise.
So basically the model represents the 3 things I'm working with - Repositories, Issues and the Top Day. I modeled it so the
Repo has a bunch of issues and a top day.
The SimpleIssue implements Comparable so I can sort the Issues based on date in reverse order. Probably the only thing of note in that
class.
The SimpleRepo class does all the figuring out for the Top Day. There I use a LinkedHashMap to store a sorted Map. The map is
sorted based on the count of issues for that day. The highest number of issues reported for any given date is the first
entry in the map.
Top Day is just basically a structure to hold the 3 pieces of information I need - Date, count and repo name.
I broke out the Report into a couple of classes to demonstrate how I would decouple the work and modularize the code. Tried
to show some simple dependency injection without going to the next level to use Google Guice or Spring or something else.
I did some basic Unit testing. Threw in a Mock so you all would know I know how to do that kind of thing. (Even though it is a
pretty basic example).
The only other thing of note is that I threaded the calls out to GitHub to make things a little faster. Each repo argument
creates a separate thread so the calls can be made simultaneously and then collected back before processing the data.
That's the summary. Thank you for the opportunity.
Mark
<file_sep>package com.alienvault.report.github;
import com.alienvault.model.SimpleIssue;
import com.alienvault.model.SimpleRepo;
import com.alienvault.model.TopDay;
import com.alienvault.report.Reportable;
import com.alienvault.service.RepositoryService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This is an implementation of the Reportable interface. Allows the report generator to generate reports given a s
* specific implementation. This one builds the report as specified in the requirements.
*
* This class uses a RepositoryService interface to get the data needed for the report. Using an interface here we can
* separate this class from the data layer and perform some dependency injection.
*/
public class GitHubIssueReport implements Reportable {
//The service that will provide the data.
private RepositoryService repositoryService;
public GitHubIssueReport(RepositoryService service){
this.repositoryService = service;
}
/**
* Inherits this method from the interface. Basically creates a String representation of the report
*
* @param parameters
* @return
* @throws Exception
*/
@Override
public String generateReport(List<String> parameters) throws Exception {
//Get the data from the service.
List<SimpleRepo> repoList = this.repositoryService.getRepositoryInformation(parameters);
//Build the issue list and get the top day.
List<SimpleIssue> issueList = new ArrayList<SimpleIssue>();
TopDay currentTopDay = new TopDay();
for(SimpleRepo repo : repoList){
issueList.addAll(repo.getIssues());
TopDay topDay = repo.getTopDay();
if (topDay.getCount() > currentTopDay.getCount()) {
currentTopDay = topDay;
}
}
//Sort the issues
Collections.sort(issueList);
//Build the report
StringBuilder report = new StringBuilder();
//Build the issue section
report.append(buildIssueSection(issueList));
report.append(",");
//Build the Top Day summary
report.append(buildTopDaySection(repoList, currentTopDay));
report.append("\n}");
return report.toString();
}
/**
* Builds the TopDay Summary section given a list of SimpleRepos and the Current Top Day
* @param repoList
* @param currentTopDay
* @return
*/
private String buildTopDaySection(List<SimpleRepo> repoList, TopDay currentTopDay) {
if(currentTopDay.getDate() == null){
return "\"top_day\": { }";
}else {
StringBuilder topDay = new StringBuilder("\"top_day\": { \"day\": \"" + currentTopDay.getDate() + "\", \"occurences\": { ");
for (int i = 0; i < repoList.size(); i++) {
TopDay td = repoList.get(i).getTopDay(currentTopDay.getDate());
topDay.append("\"" + td.getRepoName() + "\": " + td.getCount());
if (i != repoList.size() - 1) {
topDay.append(",");
}
}
topDay.append(" } } ");
return topDay.toString();
}
}
/**
* Builds the Issue Section of the report given a list of issues. The issues will have been sorted prior to being
* passed into this method. This method just builds the string.
* @param issueList
* @return
*/
private String buildIssueSection(List<SimpleIssue> issueList) {
StringBuilder builder = new StringBuilder("{\n \"issues\" : [ ");
for(int i = 0; i < issueList.size(); i++){
builder.append(issueList.get(i).toJson());
if(i != issueList.size() -1){
builder.append(",");
}
}
builder.append(" ]\n");
return builder.toString();
}
}
<file_sep>package com.alienvault.service;
import com.alienvault.model.SimpleRepo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* The GitHub Service object. This class implements the RepositoryService interface. It uses the GitHubIssueService
* to get the data from GitHub.
*/
public class GitHubService implements RepositoryService{
public List<SimpleRepo> getRepositoryInformation(List<String> repositoryNames) throws Exception{
//Create a list of Callables
List<Callable<SimpleRepo>> callables = new ArrayList<Callable<SimpleRepo>>();
//Basically this will create a thread for each repository that is passed in.
for(String param : repositoryNames){
//Check to see if the repo names are good. If not throw an exception.
if(param.isEmpty() || !param.contains("/")){
throw new IllegalArgumentException("Parameters must be in the format username/repository name.");
}
String[] path = param.split("/");
String user = path[0];
String repository = path[1];
//TODO Abstract this dependecy
callables.add(new GitHubIssueGrabber(user, repository));
}
//Create a threadpool
ExecutorService executorService = Executors.newCachedThreadPool();
//Couple of ArrayLists to hold the results
List<Future<SimpleRepo>> futures = executorService.invokeAll(callables);
List<SimpleRepo> repositories = new ArrayList<SimpleRepo>();
//Get the top day and build the list of issues.
for (Future<SimpleRepo> f : futures) {
repositories.add(f.get());
}
executorService.shutdown();
return repositories;
}
}
| 7896847d39f20982f6328bf25aa08117c5bf4db0 | [
"Markdown",
"Java"
] | 4 | Java | markmaz/alienvault | a71b3c0ded3d75cf14d0a555a1067c266a80f25a | 3fe5a06300a8a4d3ad86437f8da63d21bc72762c |
refs/heads/master | <repo_name>mojojoss/redline_site<file_sep>/src/review-slider/review-slider.js
$(document).ready(function () {
$(".review-slider").slick({
slidesToShow: 2,
slidesToScroll: 2,
dots: true
});
});
| aa88b030417ff6c9b8073b5c62347accb81e02c2 | [
"JavaScript"
] | 1 | JavaScript | mojojoss/redline_site | 2c6f333bf0d9889e70c183d856d047352677ef79 | ee1e267d4d2e14bc179a449742fb08e99ab5510f |
refs/heads/main | <repo_name>ChGunay/Buffer-Overflow<file_sep>/bufferowerflow.py
import socket
from time import sleep
import sys
numberOfCharacters = 100
stringToSend = "TRUN /.:/" + "A" * numberOfCharacters
while True:
try:
mySocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mySocket.connet(("10.0.2.1" ,9999))
bytes = stringToSend.encode(encoding = "latin1")
mySocket.send(bytes)
mySocket.close()
stringToSend = stringToSend + "A" * numberOfCharacters
sleep(1)
except KeyboardInterrupt:
print("Crashed at: " + str(len(stringToSend())))
sys.exit()
except Exception as e :
print("Crashed at: " + str(len(stringToSend())))
print(e)
sys.exit()
| e7ab31e47fcac07e1b14b2d4715f31788ea72f91 | [
"Python"
] | 1 | Python | ChGunay/Buffer-Overflow | ebc67d09ace9ec4e3328b64ca6cf0304e5b1103b | 21f79d4a801b00ebca366daee59073e26b6e24b6 |
refs/heads/master | <repo_name>zoharromm/Merchant-Management-System<file_sep>/Project bargainballoons/palyerborndate/palyerborndate/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using bestbuy;
using System.Text.RegularExpressions;
using System.Net;
using WatiN.Core;
namespace palyerborndate
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region booltypevariable
bool _IsProduct = false;
bool _IsCategory = true;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
#endregion booltypevariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
#endregion Buinesslayervariable
#region intypevariable
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "";
string Category1 = "";
string Category2 = "";
decimal Weight = 0;
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _ProductUrl = new List<string>();
List<string> _Name = new List<string>();
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> allCategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> Producturl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
ExtendedWebClient _Client2 = new ExtendedWebClient();
ExtendedWebClient _Client1 = new ExtendedWebClient();
ExtendedWebClient _Client3 = new ExtendedWebClient();
ExtendedWebClient _Client4 = new ExtendedWebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
StreamWriter writer = new StreamWriter(Application.StartupPath + "/log.txt");
#endregion htmlagility
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void Form1_Load(object sender, EventArgs e)
{
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
/****************BackGround worker *************************/
}
public void tim(int t)
{
time = 0;
timer1.Start();
try
{
while (time <= t)
{
Application.DoEvents();
}
}
catch (Exception) { }
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
time++;
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public void GetCategoryInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string category)
{
try
{
allCategoryUrl.Add(url, category);
}
catch
{ }
if (_doc.DocumentNode.SelectNodes("//span[@class=\"styJumpToPage1\"]") != null)
{
foreach (HtmlNode node in _doc.DocumentNode.SelectNodes("//span[@class=\"styJumpToPage1\"]"))
{
if (node.SelectNodes(".//a") != null)
{
foreach (HtmlNode node1 in node.SelectNodes(".//a"))
{
foreach (HtmlAttribute attr in node1.Attributes)
{
if (attr.Name == "href")
{
try
{
allCategoryUrl.Add(_ScrapeUrl + "/" + attr.Value, category);
}
catch
{
}
}
}
}
}
}
}
else
WriteLogEvent(url, "No any paging exist");
}
public void GetProductInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string Category)
{
if (_doc.DocumentNode.SelectNodes("//table[@class=\"ProdTable\"]") != null)
{
foreach (HtmlNode node in _doc.DocumentNode.SelectNodes("//table[@class=\"ProdTable\"]"))
{
BusinessLayer.Product product = new BusinessLayer.Product();
try
{
#region title
if (node.SelectNodes(".//span[@class=\"styProductName\"]") != null)
product.Name = System.Net.WebUtility.HtmlDecode(node.SelectNodes(".//span[@class=\"styProductName\"]")[0].InnerText.Trim());
else
WriteLogEvent(url, "title not found");
#endregion title
#region price
if (node.SelectNodes(".//span[@class=\"styPriceVal\"]") != null)
product.Price = node.SelectNodes(".//span[@class=\"styPriceVal\"]")[0].InnerText.Replace("$", "").Trim();
else
{
product.Price = "0";
WriteLogEvent(url, "Price not found");
}
#endregion price
#region Brand
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "JZ HOLDINGS";
#endregion Brand
#region Category
product.Category = Category;
#endregion Category
product.Currency = "CAD";
#region description
string Description = "";
string BulletPoint1 = "";
try
{
if (node.SelectNodes(".//span[@class=\"styProductDescShort\"]") != null)
{
foreach (HtmlNode node1 in node.SelectNodes(".//span[@class=\"styProductDescShort\"]"))
{
if (node1.PreviousSibling.Name == "b")
{
Description = Description + node1.PreviousSibling.InnerText + " " + node1.InnerText + " ";
}
}
Description = Removeunsuaalcharcterfromstring(StripHTML(Description).Trim());
BulletPoint1 = Description;
try
{
if (BulletPoint1.Length > 500)
BulletPoint1 = BulletPoint1.Substring(0, 496) + "...";
if (Description.Length > 2000)
Description = Description.Substring(0, 1997) + "...";
}
catch
{
}
}
else
{
WriteLogEvent(url, "Description not found");
Description = product.Name;
BulletPoint1 = product.Name;
}
}
catch
{
Description = product.Name;
BulletPoint1 = product.Name;
}
product.Description = Description;
product.Bulletpoints1 = BulletPoint1;
#endregion description
#region Image
if (node.SelectNodes(".//img") != null)
{
string ImageUrl = "";
string alt = "";
foreach (HtmlNode node1 in node.SelectNodes(".//td[@class=\"prodImage\"]"))
{
if (node1.SelectNodes(".//img") != null)
{
foreach (HtmlNode node2 in node.SelectNodes(".//img"))
{
foreach (HtmlAttribute attr in node2.Attributes)
{
if (attr.Name == "src")
ImageUrl = attr.Value.Trim();
else if (attr.Name == "alt")
alt = attr.Value.Trim();
}
if (!string.IsNullOrEmpty(alt))
{
product.Image = _ScrapeUrl + "/" + ImageUrl;
break;
}
}
}
}
}
else
WriteLogEvent(url, "Main Images not found");
#endregion Image
#region sku
if (node.SelectNodes(".//span[@class=\"styProductCodeVal\"]") != null)
{
product.SKU = "BBALCA" + node.SelectNodes(".//span[@class=\"styProductCodeVal\"]")[0].InnerText.Trim();
product.parentsku = "BBALCA" + node.SelectNodes(".//span[@class=\"styProductCodeVal\"]")[0].InnerText.Trim();
}
#endregion sku
product.Isparent = true;
product.Stock = "0";
if (node.SelectNodes(".//td[@class=\"bg\"]") != null)
{
foreach (HtmlNode node1 in node.SelectNodes(".//td[@class=\"bg\"]")[0].SelectNodes(".//b"))
{
if (node1.InnerText.Trim().ToLower().Contains("quantity in stock:"))
{
string quantityText = node1.InnerText.Trim().ToLower().Replace("quantity in stock:", "");
int quantity = 0;
int.TryParse(quantityText, out quantity);
product.Stock = quantity.ToString();
}
else
WriteLogEvent(url, "quantity in stock: is not exist in quantity node");
}
}
var count = (from prd in Products
where prd.SKU == product.SKU
select prd).FirstOrDefault();
if (count == null)
{
product.URL = url;
//double priceCheck = 0;
//double minimumPrice = 1.5;
//double.TryParse(product.Price, out priceCheck);
//if (priceCheck > minimumPrice)
Products.Add(product);
}
}
catch
{ }
}
}
else
WriteLogEvent(url, "App failed to read product on given url");
}
public string GetUPC(string Response)
{
string Result = "";
foreach (var ch in Response.ToCharArray())
{
if (char.IsNumber(ch))
Result = Result + ch;
else
break;
}
Int64 n;
bool isNumeric = Int64.TryParse(Result, out n);
if (n != 0)
return Result;
else
return "";
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public void WriteLogEvent(string url, string Detail)
{
writer.WriteLine(Detail + "/t" + url);
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
int checkcounter = 0;
do
{
try
{
counterReload++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url1, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc, Url1, Category1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading produts from category page"); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / CategoryUrl.Count));
/****************end*******************/
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc, Url1, Category1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading product Info."); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / allCategoryUrl.Count));
/****************end*******************/
}
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int checkcounter = 0;
int counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url2, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc2, Url2, Category2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading produts from category page"); }
gridindex++;
_Work1.ReportProgress((gridindex * 100 / CategoryUrl.Count));
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc2, Url2, Category2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading product Info."); }
gridindex++;
_Work1.ReportProgress((gridindex * 100 / allCategoryUrl.Count));
}
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
private void Go_Click(object sender, EventArgs e)
{
_IsProduct = false;
_percent.Visible = false;
_Bar1.Value = 0;
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
#region bargainballoons.ca
_ScrapeUrl = "http://www.bargainballoons.ca";
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category Link for bargainballoons.ca Website";
int counterReload = 0;
bool isError = false;
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _CollectionCatLink = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"subMenuList\"]");
if (_CollectionCatLink != null)
{
try
{
foreach (HtmlNode node in _CollectionCatLink)
{
foreach (HtmlNode node1 in node.SelectNodes(".//a"))
{
foreach (HtmlAttribute attr in node1.Attributes)
{
if (attr.Name == "href")
{
try
{
CategoryUrl.Add(_ScrapeUrl + "/" + attr.Value, "BBALCA" + node1.InnerText.Trim());
}
catch
{
}
}
}
}
}
}
catch
{ }
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (CategoryUrl.Count > 0)
{
gridindex = 0;
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read paging from category page.";
_Stop = false;
time = 0;
_IsCategory = true;
tim(3);
totalrecord.Visible = true;
totalrecord.Text = "Total No Pages :" + CategoryUrl.Count.ToString();
foreach (var url in CategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key;
Category1 = url.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
Category2 = url.Value;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product info.";
_IsCategory = false;
_IsProduct = true;
gridindex = 0;
totalrecord.Text = "Total No Category Pages :" + allCategoryUrl.Count.ToString();
foreach (var url in allCategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key;
Category1 = url.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
Category2 = url.Value;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#region InsertScrappedProductInDatabase
if (Products.Count() > 0)
{
_Prd.ProductDatabaseIntegration(Products, "bargainballoons.ca", 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='bargainballoons.ca'");
_Prd.ProductDatabaseIntegration(Products, "bargainballoons.ca", 1);
_Mail.SendMail("OOPS there is no any product scrapped by app for bargainballoons.ca Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#endregion InsertScrappedProductInDatabase
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Prd.ProductDatabaseIntegration(Products, "bargainballoons.ca", 1);
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='bargainballoons.ca'");
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for bargainballoons.ca Website";
/****************Email****************/
_Mail.SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for bargainballoons.ca Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
/*******************End********/
}
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Prd.ProductDatabaseIntegration(Products, "bargainballoons.ca", 1);
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='bargainballoons.ca'");
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for bargainballoons.ca Website";
/****************Email****************/
_Mail.SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for bargainballoons.ca Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
/*******************End********/
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='bargainballoons.ca'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data bargainballoons.ca Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
# endregion bargainballoons.ca
writer.Close();
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Form1_Shown(object sender, EventArgs e)
{
base.Show();
this.Go_Click(null, null);
}
}
public class ExtendedWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = 120000;
return w;
}
}
}<file_sep>/Project 16 TigerDirect/Crawler_WithouSizes_Part2/Form1.cs
using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using Crawler_Without_Sizes_Part2;
using WatiN.Core;
using System.Text.RegularExpressions;
namespace Crawler_WithouSizes_Part2
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.APPConfig Config = new BusinessLayer.APPConfig();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
#endregion Buinesslayervariable
StreamWriter _writer = new StreamWriter(Application.StartupPath + "/test.csv");
#region booltypevariable
bool _IStigerdirect = true;
bool _IsProduct = false;
bool _IsCategorypaging = false;
bool _IsSubcat = false;
bool _Stop = false;
bool Erorr_401_1 = true;
bool Erorr_401_2 = true;
#endregion booltypevariable
#region intypevariable
int FindCounter = 0;
int _Workindex = 0;
int _WorkIndex1 = 0;
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
int _401index = 0;
#endregion intypevariable
#region stringtypevariable
string BrandName1 = "";
string BrandName2 = "";
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "";
string _Description1 = "";
string _Description2 = "";
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
Dictionary<string, string> Url = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrlthread1 = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrlthread2 = new Dictionary<string, string>();
List<string> _Name = new List<string>();
Dictionary<string, string> subCategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
#region IeVariable
IE _Worker1 = null;
IE _Worker2 = null;
#endregion IeVariable
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public void DisplayRecordProcessdetails(string Message, string TotalrecordMessage)
{
_lblerror.Visible = true;
_lblerror.Text = Message;
totalrecord.Visible = true;
totalrecord.Text = TotalrecordMessage;
}
public void Process()
{
_IsProduct = false;
_Name.Clear();
CategoryUrl.Clear();
_ProductUrlthread1.Clear();
_ProductUrlthread1.Clear();
Url.Clear();
_percent.Visible = false;
_Bar1.Value = 0;
_Url.Clear();
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_Stop = false;
time = 0;
#region tigerdirect.ca
_IStigerdirect = true;
_ScrapeUrl = "http://tigerdirect.ca/";
try
{
_Worker1 = new IE();
_Worker2 = new IE();
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category url of " + chkstorelist.Items[0].ToString() + " Website";
_Worker1.GoTo(_ScrapeUrl);
_Worker1.WaitForComplete();
System.Threading.Thread.Sleep(10);
_Work1doc.LoadHtml(_Worker1.Html);
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"mastNav-subCats\"]/li/a");
if (_Collection != null)
{
foreach (HtmlNode node in _Collection)
{
foreach (HtmlAttribute att in node.Attributes)
{
if (att.Name == "href")
try
{
CategoryUrl.Add("http://www.tigerdirect.ca" + (att.Value.Contains("?") ? att.Value + "&recs=30" : att.Value + "?recs=30"), "TGRDRCT" + node.InnerText.Trim());
}
catch
{ }
}
}
}
try
{
CategoryUrl.Add("http://www.tigerdirect.ca/applications/Category/guidedSearch.asp?CatId=21&sel=Detail%3B358_1565_8718_8718&cm_re=Printers-_-Spot%2001-_-Laser%20Printers&pagesize=30", "printer");
CategoryUrl.Add("http://www.tigerdirect.ca/applications/Category/guidedSearch.asp?CatId=21&sel=Detail%3B358_1565_84868_84868&cm_re=Printers-_-Spot%2002-_-Inkjet%20Printers&pagesize=30", "printer");
CategoryUrl.Add("http://www.tigerdirect.ca/applications/Category/guidedSearch.asp?CatId=25&name=scanners&cm_re=Printers-_-Spot%2003-_-Scanners&pagesize=30", "printer");
CategoryUrl.Add("http://www.tigerdirect.ca/applications/category/category_slc.asp?CatId=243&cm_re=Printers-_-Spot%2004-_-Label%20Printers&pagesize=30", "printer");
CategoryUrl.Add("http://www.tigerdirect.ca/applications/Category/guidedSearch.asp?CatId=21&sel=Detail%3B358_36_84863_84863&cm_re=Printers-_-Spot%2005-_-Mobile&pagesize=30", "printer");
}
catch
{ }
DisplayRecordProcessdetails("We are going to read product url from category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
if (File.Exists(Application.StartupPath + "/Files/Url.txt"))
{
FileInfo _Info = new FileInfo(Application.StartupPath + "/Files/Url.txt");
int Days = 14;
try
{
Days = Convert.ToInt32(Config.GetAppConfigValue("tigerdirect.ca", "FrequencyOfCategoryScrapping"));
}
catch
{
}
if (_Info.CreationTime < DateTime.Now.AddDays(-Days))
_IsCategorypaging = true;
else
_IsCategorypaging = false;
}
else
_IsCategorypaging = true;
if (_IsCategorypaging)
{
int i = 0;
foreach (var Caturl in CategoryUrl)
{
try
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Caturl.Key;
BrandName1 = Caturl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = Caturl.Key;
BrandName2 = Caturl.Value;
_Work1.RunWorkerAsync();
}
}
catch { }
i++;
//if (i == 3)
// break;
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
DisplayRecordProcessdetails("We are going to read product url from sub-category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
_401index = 0;
_IsSubcat = true;
foreach (var Caturl in subCategoryUrl)
{
try
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Caturl.Key;
BrandName1 = Caturl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = Caturl.Key;
BrandName2 = Caturl.Value;
_Work1.RunWorkerAsync();
}
}
catch (Exception exp)
{
}
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
System.Threading.Thread.Sleep(1000);
_Bar1.Value = 0;
_401index = 0;
#region Code to get and write urls from File
if (File.Exists(Application.StartupPath + "/Files/Url.txt"))
{
using (StreamReader Reader = new StreamReader(Application.StartupPath + "/Files/Url.txt"))
{
string line = "";
while ((line = Reader.ReadLine()) != null)
{
try
{
Url.Add(line.Split(new[] { "@#$#" }, StringSplitOptions.None)[0], line.Split(new[] { "@#$#" }, StringSplitOptions.None)[1]);
}
catch
{
}
}
}
}
foreach (var url in _ProductUrlthread1)
{
try
{
if (!Url.Keys.Contains(url.Key.ToLower()))
Url.Add(url.Key.ToLower(), url.Value);
}
catch
{
}
}
foreach (var url in _ProductUrlthread2)
{
try
{
if (!Url.Keys.Contains(url.Key.ToLower()))
Url.Add(url.Key.ToLower(), url.Value);
}
catch
{
}
}
// Code to write in file
if (_IsCategorypaging)
{
using (StreamWriter writer = new StreamWriter(Application.StartupPath + "/Files/Url.txt"))
{
foreach (var PrdUrl in Url)
{
writer.WriteLine(PrdUrl.Key + "@#$#" + PrdUrl.Value);
}
}
}
#endregion Code to get and write urls from File
_IsCategorypaging = false;
DisplayRecordProcessdetails("We are going to read Product information for " + chkstorelist.Items[0].ToString() + " Website", "Total products :" + Url.Count());
_IsProduct = true;
foreach (var PrdUrl in Url)
{
try
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = PrdUrl.Key;
BrandName1 = PrdUrl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = PrdUrl.Key;
BrandName2 = PrdUrl.Value;
_Work1.RunWorkerAsync();
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (Products.Count() > 0)
{
System.Threading.Thread.Sleep(1000);
_lblerror.Visible = true;
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
_Prd.ProductDatabaseIntegration(Products, "tigerdirect.ca", 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='tigerdirect.ca'");
_Mail.SendMail("OOPS there is no any product scrapped by app for tigerdirect.ca Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='tigerdirect.ca'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data tigerdirect.ca Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#region closeIEinstance
try
{
_Worker1.Close();
_Worker2.Close();
}
catch
{
}
#endregion closeIEinstance
#endregion
_writer.Close();
this.Close();
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
Erorr_401_1 = true;
if (_IStigerdirect && _IsCategorypaging)
{
try
{
int CounterError = 0;
do
{
try
{
_Worker1.GoTo(Url1);
Erorr_401_1 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_1 && CounterError < 20);
}
catch
{
_Iserror = true;
}
}
int index = 0;
#region tigerdirect.ca
if (_IStigerdirect)
{
if (_IsCategorypaging)
{
#region 401categorypaging
if (!Erorr_401_1)
{
try
{
_Worker1.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
Erorr_401_1 = true;
if (_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"breadcrumbs\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"breadcrumbs\"")) && checkcounter < 25);
}
_Work1doc.LoadHtml(_Worker1.Html);
checkcounter = 0;
#region getChildCat
if (!_IsSubcat)
{
HtmlNodeCollection _SubCat = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"innerWrap\"]/ul[@class=\"filterItem\"]");
if (_SubCat != null)
{
foreach (HtmlNode node in _SubCat[0].SelectNodes(".//a"))
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "href")
{
try
{
subCategoryUrl.Add("http://www.tigerdirect.ca" + (attr.Value.Contains("?") ? attr.Value + "&pagesize=30" : attr.Value + "?pagesize=30"), "TGRDRCT" + node.InnerText.Trim());
}
catch
{ }
}
}
}
}
}
#endregion getChildCat
#endregion CheckPageLoaded
int TotalRecords = 0;
int TotalPages = 0;
int CurrentPage = 1;
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"itemsShowresult\"]/strong");
if (_Collection != null)
{
int.TryParse(_Collection[1].InnerText.Trim(), out TotalRecords);
if (TotalRecords != 0)
{
if (TotalRecords % 40 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 10);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 10) + 1;
}
}
else
_writer.WriteLine(Url1 + " " + "workerexp1 " + "Total records Tags Not found");
}
HtmlNodeCollection _Collection1 = _Work1doc.DocumentNode.SelectNodes("//a[@class=\"itemImage\"]");
if (_Collection1 != null)
{
foreach (HtmlNode _Node in _Collection1)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
try
{
_ProductUrlthread1.Add("http://www.tigerdirect.ca" + _Attribute.Value.Replace("../", "/"), BrandName1);
}
catch
{
}
}
}
}
}
else
_writer.WriteLine(Url1 + " " + "workerexp1 " + "product not found for given category");
string ClickTest = "Next";
bool Isexist = false;
if (TotalPages > 1)
{
while (!Isexist)
{
Isexist = true;
try
{
IElementContainer Div = (IElementContainer)_Worker1.Element(Find.ByClass("itemsPagination"));
LinkCollection _Links = Div.Links;
foreach (Link _Link in _Links)
{
if (_Link.InnerHtml.Trim().Contains("Next"))
{
Isexist = false;
_Link.Click();
_Worker1.WaitForComplete();
if (ClickTest == "Next")
{
checkcounter = 0;
if (_Worker1.Html == null || _Worker1.Html.ToLower().Contains(_ProductUrlthread1.ToArray()[_ProductUrlthread1.Count - 1].Key.ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"breadcrumbs\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker1.Html == null || _Worker1.Html.ToLower().Contains(_ProductUrlthread1.ToArray()[_ProductUrlthread1.Count - 1].Key.ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"breadcrumbs\"")) && checkcounter < 10);
}
_Work1doc.LoadHtml(_Worker1.Html);
HtmlNodeCollection _Collection2 = _Work1doc.DocumentNode.SelectNodes("//a[@class=\"itemImage\"]");
if (_Collection2 != null)
{
foreach (HtmlNode _Node in _Collection2)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
try
{
_ProductUrlthread1.Add("http://www.tigerdirect.ca" + _Attribute.Value.Replace("../", "/"), BrandName1);
}
catch
{
}
}
}
}
}
else
_writer.WriteLine(Url1 + " " + "workerexp1 " + "product not found for given category");
}
else
{
ClickTest = "Next";
}
break;
}
}
}
catch (Exception exp)
{
Isexist = false;
if (ClickTest == "Next")
{
if (!WebUtility.UrlDecode(_Worker1.Url).ToLower().Contains("page=1&"))
{
ClickTest = "Previous";
}
}
else
{
ClickTest = "Next";
}
_writer.WriteLine(Url1 + " " + "worker1exp3" + exp.Message);
}
}
}
}
catch (Exception exp)
{
_writer.WriteLine(Url1 + " " + "workerexp4 " + exp.Message);
}
}
_401index++;
_Work.ReportProgress((_401index * 100 / (_IsSubcat == false ? CategoryUrl.Count() : subCategoryUrl.Count())));
#endregion 401categorypaging
}
else if (_IsProduct)
{
try
{
_Client1.Headers["Accept"] = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
_Client1.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)";
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
//_Worker1.WaitForComplete();
//int checkcounter = 0;
//Erorr_401_1 = true;
//if (_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"breadcrumb\""))
//{
// do
// {
// System.Threading.Thread.Sleep(20);
// Application.DoEvents();
// checkcounter++;
// } while ((_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"breadcrumb\"")) && checkcounter < 10);
//}
//_Work1doc.LoadHtml(_Worker1.Html);
GetProductInfo(_Work1doc, Url1, BrandName1);
}
catch (Exception exp)
{
_writer.WriteLine(Url1 + " " + " product page exception workerexp4 " + exp.Message);
}
_401index++;
_Work.ReportProgress((_401index * 100 / Url.Count()));
}
}
#endregion tigerdirect.ca
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
Erorr_401_2 = true;
if (_IStigerdirect && _IsCategorypaging)
{
try
{
int CounterError = 0;
do
{
try
{
_Worker2.GoTo(Url2);
Erorr_401_2 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_2 && CounterError < 20);
}
catch
{
_Iserror = true;
}
}
int index = 0;
#region tigerdirect.ca
if (_IStigerdirect)
{
if (_IsCategorypaging)
{
#region 401categorypaging
if (!Erorr_401_2)
{
try
{
_Worker2.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
Erorr_401_2 = true;
if (_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"breadcrumbs\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"breadcrumbs\"")) && checkcounter < 25);
}
_Work1doc2.LoadHtml(_Worker2.Html);
checkcounter = 0;
#region getChildCat
if (!_IsSubcat)
{
HtmlNodeCollection _SubCat = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"innerWrap\"]/ul[@class=\"filterItem\"]");
if (_SubCat != null)
{
foreach (HtmlNode node in _SubCat[0].SelectNodes(".//a"))
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "href")
{
try
{
subCategoryUrl.Add("http://www.tigerdirect.ca" + (attr.Value.Contains("?") ? attr.Value + "&pagesize=30" : attr.Value + "?pagesize=30"), "TGRDRCT" + node.InnerText.Trim());
}
catch
{ }
}
}
}
}
}
#endregion getChildCat
#endregion CheckPageLoaded
int TotalRecords = 0;
int TotalPages = 0;
int CurrentPage = 1;
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"itemsShowresult\"]/strong");
if (_Collection != null)
{
int.TryParse(_Collection[1].InnerText.Trim(), out TotalRecords);
if (TotalRecords != 0)
{
if (TotalRecords % 40 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 10);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 10) + 1;
}
}
else
_writer.WriteLine(Url2 + " " + "workerexp1 " + "Total records Tags Not found");
}
HtmlNodeCollection _Collection1 = _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"itemImage\"]");
if (_Collection1 != null)
{
foreach (HtmlNode _Node in _Collection1)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
try
{
_ProductUrlthread2.Add("http://www.tigerdirect.ca" + _Attribute.Value.Replace("../", "/"), BrandName2);
}
catch
{
}
}
}
}
}
else
_writer.WriteLine(Url2 + " " + "workerexp1 " + "product not found for given category");
string ClickTest = "Next";
bool Isexist = false;
if (TotalPages > 1)
{
while (!Isexist)
{
Isexist = true;
try
{
IElementContainer Div = (IElementContainer)_Worker2.Element(Find.ByClass("itemsPagination"));
LinkCollection _Links = Div.Links;
foreach (Link _Link in _Links)
{
if (_Link.InnerHtml.Trim().Contains("Next"))
{
Isexist = false;
_Link.Click();
_Worker2.WaitForComplete();
if (ClickTest == "Next")
{
checkcounter = 0;
if (_Worker2.Html == null || _Worker2.Html.ToLower().Contains(_ProductUrlthread2.ToArray()[_ProductUrlthread2.Count - 1].Key.ToString().ToLower()) || !_Worker2.Html.ToLower().Contains("class=\"breadcrumbs\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker2.Html == null || _Worker2.Html.ToLower().Contains(_ProductUrlthread2.ToArray()[_ProductUrlthread2.Count - 1].Key.ToString().ToLower()) || !_Worker2.Html.ToLower().Contains("class=\"breadcrumbs\"")) && checkcounter < 10);
}
_Work1doc2.LoadHtml(_Worker2.Html);
HtmlNodeCollection _Collection2 = _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"itemImage\"]");
if (_Collection2 != null)
{
foreach (HtmlNode _Node in _Collection2)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
try
{
_ProductUrlthread2.Add("http://www.tigerdirect.ca" + _Attribute.Value.Replace("../", "/"), BrandName2);
}
catch
{
}
}
}
}
}
else
_writer.WriteLine(Url2 + " " + "workerexp1 " + "product not found for given category");
}
else
{
ClickTest = "Next";
}
break;
}
}
}
catch (Exception exp)
{
Isexist = false;
if (ClickTest == "Next")
{
if (!WebUtility.UrlDecode(_Worker2.Url).ToLower().Contains("page=1&"))
{
ClickTest = "Previous";
}
}
else
{
ClickTest = "Next";
}
_writer.WriteLine(Url2 + " " + "worker1exp3" + exp.Message);
}
}
}
}
catch (Exception exp)
{
_writer.WriteLine(Url2 + " " + "workerexp4 " + exp.Message);
}
}
_401index++;
_Work1.ReportProgress((_401index * 100 / (_IsSubcat == false ? CategoryUrl.Count() : subCategoryUrl.Count())));
#endregion 401categorypaging
}
else if (_IsProduct)
{
try
{
_Client2.Headers["Accept"] = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
_Client2.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)";
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
GetProductInfo(_Work1doc2, Url2, BrandName2);
}
catch (Exception exp)
{
_writer.WriteLine(Url2 + " " + " product page exception workerexp4 " + exp.Message);
}
_401index++;
_Work1.ReportProgress((_401index * 100 / Url.Count()));
}
}
#endregion tigerdirect.ca
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public void GetProductInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string Category)
{
BusinessLayer.Product product = new BusinessLayer.Product();
try
{
string Bullets = "";
#region title
HtmlNodeCollection formColl = _doc.DocumentNode.SelectNodes("//div[@class=\"prodName\"]/h1");
if (formColl != null)
product.Name = System.Net.WebUtility.HtmlDecode(formColl[0].InnerText).Trim();
else if (_doc.DocumentNode.SelectNodes("//meta[@property=\"og:title\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//meta[@property=\"og:title\"]")[0].Attributes)
{
if (attr.Name == "content")
{
product.Name = System.Net.WebUtility.HtmlDecode(attr.Value).Trim();
break;
}
}
}
else
_writer.WriteLine(url + " " + "title not found");
#endregion title
#region Price
string priceString = "";
double Price = 0;
if (_doc.DocumentNode.SelectNodes("//span[@class=\"salePrice\"]") != null)
{
priceString = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//span[@class=\"salePrice\"]")[0].InnerText).Replace("$", "").Trim();
double.TryParse(priceString, out Price);
if (Price != 0)
product.Price = Price.ToString(); //System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//span[@class=\"regular-price\"]/span[@class=\"price\"]")[0].InnerText).re;
else
_writer.WriteLine(url + " " + "Price not found");
}
else if (_doc.DocumentNode.SelectNodes("//meta[@itemprop=\"price\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//meta[@itemprop=\"price\"]")[0].Attributes)
{
if (attr.Name == "content")
{
priceString = System.Net.WebUtility.HtmlDecode(attr.Value).Replace("$", "").Trim();
break;
}
}
double.TryParse(priceString, out Price);
if (Price != 0)
product.Price = Price.ToString(); //System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//span[@class=\"regular-price\"]/span[@class=\"price\"]")[0].InnerText).re;
else
_writer.WriteLine(url + " " + "Price not found");
}
else
_writer.WriteLine(url + " " + "Price not found");
#endregion Price
#region Brand
if (_doc.DocumentNode.SelectNodes("//div[@itemprop=\"brand\"]/meta") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//div[@itemprop=\"brand\"]/meta")[0].Attributes)
{
if (attr.Name == "content")
{
product.Brand = attr.Value.Trim();
product.Manufacturer = attr.Value.Trim();
break;
}
}
}
else
{
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "JZ HOLDINGS";
}
#endregion Brand
#region Category
product.Category = string.IsNullOrEmpty(Category) ? "TGRDRCTJZ HOLDINGS" : Category;
#endregion Category
product.Currency = "CAD";
#region description
string Description = "";
HtmlNodeCollection desCollection = _doc.DocumentNode.SelectNodes("//div[@id=\"prodinfo\"]");
if (desCollection != null)
{
try
{
Description = Removeunsuaalcharcterfromstring(StripHTML(desCollection[0].InnerText).Trim());
try
{
if (Description.Length > 2000)
Description = Description.Substring(0, 1997) + "...";
}
catch
{
}
product.Description = System.Net.WebUtility.HtmlDecode(Description.Replace("Â", ""));
}
catch
{
_writer.WriteLine(url + " " + "Description not found");
}
}
else
_writer.WriteLine(url + " " + "Description not found");
#endregion description
#region BulletPoints
string Feature = "";
HtmlNodeCollection collection = _doc.DocumentNode.SelectNodes("//table[@class=\"prodSpec\"]");
if (collection != null)
{
string Header = "";
string Value = "";
int PointCounter = 1;
try
{
foreach (HtmlNode node in collection[0].SelectNodes(".//tr"))
{
try
{
Header = System.Net.WebUtility.HtmlDecode(node.SelectNodes(".//th")[0].InnerText.Trim());
if (node.SelectNodes(".//td") != null)
{
Value = System.Net.WebUtility.HtmlDecode(node.SelectNodes(".//td")[0].InnerText.Trim());
if (Value != "")
{
Feature = " " + Header + " " + Value;
if (Feature.Length > 480)
Feature = Feature.Substring(0, 480);
if (Bullets.Length + Feature.Length + 2 <= PointCounter * 480)
Bullets = Bullets + Feature + ". ";
else
{
Bullets = Bullets + "@@" + Feature + ". ";
PointCounter++;
}
}
}
}
catch { }
}
}
catch { }
if (!string.IsNullOrEmpty(Bullets))
Bullets = Bullets.Trim();
}
else
_writer.WriteLine(url + " " + "Bullet Points not found");
if (Bullets.Length > 0)
{
Bullets = Removeunsuaalcharcterfromstring(StripHTML(Bullets).Trim());
string[] BulletPoints = Bullets.Split(new string[] { "@@" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < BulletPoints.Length; i++)
{
if (i == 0)
product.Bulletpoints1 = BulletPoints[i].ToString();
if (i == 1)
product.Bulletpoints2 = BulletPoints[i].ToString();
if (i == 2)
product.Bulletpoints3 = BulletPoints[i].ToString();
if (i == 3)
product.Bulletpoints4 = BulletPoints[i].ToString();
if (i == 4)
product.Bulletpoints5 = BulletPoints[i].ToString();
if (i > 4)
break;
}
}
if (string.IsNullOrEmpty(product.Description))
{
product.Description = product.Name;
if (string.IsNullOrEmpty(product.Bulletpoints1))
product.Bulletpoints1 = product.Name;
}
else if (string.IsNullOrEmpty(product.Bulletpoints1))
{
if (product.Description.Length >= 500)
product.Bulletpoints1 = product.Description.Substring(0, 497);
else
product.Bulletpoints1 = product.Description;
}
#endregion BulletPoints
#region Image
string Images = "";
if (_doc.DocumentNode.SelectNodes("//meta[@itemprop=\"image\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//meta[@itemprop=\"image\"]")[0].Attributes)
{
if (attr.Name == "content")
{
Images = attr.Value.Trim() + ",";
break;
}
}
}
HtmlNodeCollection imgCollection = _doc.DocumentNode.SelectNodes("//ul[@id=\"viewsImg\"]");
if (imgCollection != null)
{
foreach (HtmlNode node in imgCollection[0].SelectNodes(".//img"))
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "src")
{
Images = Images + attr.Value.Trim().Replace("/small", "/large") + ",";
break;
}
}
}
}
else
_writer.WriteLine(url + " " + "Main Images not found");
if (Images.Length > 0)
Images = Images.Substring(0, Images.Length - 1);
product.Image = Images;
#endregion Image
product.Isparent = true;
#region sku
string sku = "";
if (_doc.DocumentNode.SelectNodes("//span[@class=\"sku\"]/strong") != null)
{
try
{
foreach (HtmlNode Node in _doc.DocumentNode.SelectNodes("//span[@class=\"sku\"]/strong"))
{
if (Node.InnerText.ToLower().Contains("model#"))
product.ManPartNO = Removeunsuaalcharcterfromstring(StripHTML(Node.NextSibling.InnerText)).Replace("|", "").Trim();
else if (Node.InnerText.ToLower().Contains("item#"))
{
product.SKU = "TGRDRCT" + Removeunsuaalcharcterfromstring(StripHTML(Node.NextSibling.InnerText)).Replace("|", "").Trim();
product.parentsku = "TGRDRCT" + Removeunsuaalcharcterfromstring(StripHTML(Node.NextSibling.InnerText)).Replace("|", "").Trim();
}
}
}
catch
{ }
}
else
_writer.WriteLine(url + " " + "Model and SKU not found");
//if (_doc.DocumentNode.SelectNodes("//meta[@itemprop=\"sku\"]") != null)
//{
// foreach (HtmlAttribute node in _doc.DocumentNode.SelectNodes("//meta[@itemprop=\"sku\"]")[0].Attributes)
// {
// if (node.Name == "content")
// {
// product.SKU = "TGRDRCT" + node.Value.Trim();
// product.parentsku = "TGRDRCT" + node.Value.Trim();
// }
// }
//}
//else
// _writer.WriteLine(url + " " + "sku not found");
#endregion sku
//#region upc
//if (_doc.DocumentNode.SelectNodes("//meta[@itemprop=\"gtin14\"]") != null)
//{
// foreach (HtmlAttribute node in _doc.DocumentNode.SelectNodes("//meta[@itemprop=\"gtin14\"]")[0].Attributes)
// {
// if (node.Name == "content")
// {
// product.UPC = node.Value.Trim();
// if(product.UPC=="00000000000000")
// product.UPC="";
// break;
// }
// }
//}
//else
// _writer.WriteLine(url + " " + "upc not found");
//#endregion upc
#region stock
product.Stock = "0";
if (_doc.DocumentNode.SelectNodes("//meta[@itemprop=\"availability\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//meta[@itemprop=\"availability\"]")[0].Attributes)
{
if (attr.Name == "content")
{
if (attr.Value.ToLower() == "instock")
{
product.Stock = "1";
break;
}
}
}
}
#endregion stock
product.URL = url;
if (!string.IsNullOrEmpty(product.UPC))
product.ISGtin = true;
else
product.ISGtin = false;
Products.Add(product);
}
catch (Exception exp)
{
_writer.WriteLine(url + " " + "Issue accured in reading product info from given product url. exp: " + exp.Message);
}
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename, decimal Price, string url)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.Parameters.AddWithValue("@URL", url);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed. Record Processed " + _401index;
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed. Record Processed " + _401index;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Go_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
}
private void btnsubmit_Click(object sender, System.EventArgs e)
{
Process();
}
private void Form1_Shown(object sender, System.EventArgs e)
{
base.Show();
this.btnsubmit_Click(null, null);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
}
}
<file_sep>/Project 14 hockeysupremacy/palyerborndate/palyerborndate/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using bestbuy;
using System.Text.RegularExpressions;
using System.Net;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
namespace palyerborndate
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region booltypevariable
bool _ISBuy = false;
bool _IsProduct = false;
bool _IsCategory = true;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
int gridindex = 0;
int time = 0;
#endregion booltypevariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
#endregion Buinesslayervariable
#region intypevariable
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&keyword=keywords&search_in_description=1&product_type=&kfi_blade_length_from=0&kfi_blade_length_to=15&kfi_overall_length_from=0&kfi_overall_length_to=30&kfi_serration=ANY&kfi_is_coated=ANY&kfo_blade_length_from=0&kfo_blade_length_to=8&kfo_overall_length_from=0&kfo_overall_length_to=20&kfo_serration=ANY&kfo_is_coated=ANY&kfo_assisted=ANY&kk_blade_length_from=0&kk_blade_length_to=15&fl_lumens_from=0&fl_lumens_to=18000&fl_num_cells_from=1&fl_num_cells_to=10&fl_num_modes_from=1&fl_num_modes_to=15&sw_blade_length_from=0&sw_blade_length_to=60&sw_overall_length_from=0&sw_overall_length_to=70&inc_subcat=1&pfrom=0.01&pto=10000.00&x=36&y=6&perPage=60";
string Category1 = "";
string Category2 = "";
decimal Weight = 0;
#endregion listtypevariable
#region listtypevariable
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrl = new Dictionary<string, string>();
List<string> variationTheme = new List<string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
ExtendedWebClient _Client2 = new ExtendedWebClient();
ExtendedWebClient _Client1 = new ExtendedWebClient();
ExtendedWebClient _Client3 = new ExtendedWebClient();
ExtendedWebClient _Client4 = new ExtendedWebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
StreamWriter writer = new StreamWriter(Application.StartupPath + "/log.txt");
#endregion htmlagility
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
variationTheme.Add("select size");
variationTheme.Add("select skate width");
variationTheme.Add("select color");
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void Form1_Load(object sender, EventArgs e)
{
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
/****************BackGround worker *************************/
}
public void tim(int t)
{
time = 0;
timer1.Start();
try
{
while (time <= t)
{
Application.DoEvents();
}
}
catch (Exception) { }
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
time++;
}
public void GetCategoryInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string Category)
{
HtmlNodeCollection coll = _doc.DocumentNode.SelectNodes("//a[@class=\"product-image\"]");
if (coll != null)
{
foreach (HtmlNode node1 in coll)
{
foreach (HtmlAttribute attr in node1.Attributes)
{
if (attr.Name == "href")
{
try
{
_ProductUrl.Add(attr.Value, Category);
}
catch
{
}
}
}
}
}
else
WriteLogEvent(url, "h2[@class=\"product-name\"]/a tag is not found");
}
public void GetProductInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string Category)
{
BusinessLayer.Product product = new BusinessLayer.Product();
try
{
#region title
HtmlNodeCollection formColl = _doc.DocumentNode.SelectNodes("//meta[@property=\"og:title\"]");
if (formColl != null)
{
foreach (HtmlAttribute attr in formColl[0].Attributes)
{
if (attr.Name == "content")
product.Name = System.Net.WebUtility.HtmlDecode(attr.Value).Trim();
}
}
else if (_doc.DocumentNode.SelectNodes("//div[@class=\"product-name\"]/h1") != null)
product.Name = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//div[@class=\"product-name\"]/h1")[0].InnerText).Trim();
else
WriteLogEvent(url, "title not found");
#endregion title
#region Price
if (_doc.DocumentNode.SelectNodes("//span[@class=\"regular-price\"]/span[@class=\"price\"]") != null)
{
double Price = 0;
string priceString = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//span[@class=\"regular-price\"]/span[@class=\"price\"]")[0].InnerText).Replace("$", "").Trim();
double.TryParse(priceString, out Price);
if (Price != 0)
product.Price = Price.ToString(); //System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//span[@class=\"regular-price\"]/span[@class=\"price\"]")[0].InnerText).re;
else
WriteLogEvent(url, "Price not found");
}
else
WriteLogEvent(url, "Price not found");
#endregion Price
#region Brand
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "JZ HOLDINGS";
#endregion Brand
#region Category
product.Category = Category;
#endregion Category
product.Currency = "CAD";
#region description
string Description = "";
string BulletPoints = "";
HtmlNodeCollection desCollection = _doc.DocumentNode.SelectNodes("//ul[@class=\"slides\"]/li");
if (desCollection != null)
{
try
{
foreach (HtmlNode node in desCollection)
{
if (node.InnerText.ToLower().Contains("overview"))
Description = Description + Removeunsuaalcharcterfromstring(StripHTML(node.InnerText).Trim() + " ");
else if (node.InnerText.ToLower().Contains("specifications"))
{
if (node.SelectNodes(".//tr") != null)
{
foreach (HtmlNode node1 in node.SelectNodes(".//tr"))
{
if (node1.SelectNodes(".//td") != null)
{
string Header = "";
string Value = "";
try
{
Header = node1.SelectNodes(".//th")[0].InnerText.Trim();
Value = node1.SelectNodes(".//td")[0].InnerText.Trim();
if (Header.ToLower() == "brand")
if (Value.ToLower() != "no")
{
product.Manufacturer = Value;
product.Brand = Value;
}
BulletPoints = BulletPoints + Header + " " + Value + " ";
}
catch
{ }
}
}
}
}
}
Description = Removeunsuaalcharcterfromstring(StripHTML(Description).Trim());
try
{
if (Description.Length > 2000)
Description = Description.Substring(0, 1997) + "...";
}
catch
{
}
product.Description = System.Net.WebUtility.HtmlDecode(Description.Replace("Â", ""));
}
catch
{
WriteLogEvent(url, "Description not found");
}
if (!string.IsNullOrEmpty(BulletPoints.Trim()))
product.Bulletpoints1 = BulletPoints;
}
else
WriteLogEvent(url, "Description not found");
#endregion description
#region BulletPoints
if (string.IsNullOrEmpty(product.Description))
{
product.Description = product.Name;
if (string.IsNullOrEmpty(product.Bulletpoints1))
product.Bulletpoints1 = product.Name;
}
else if (string.IsNullOrEmpty(product.Bulletpoints1))
{
if (product.Description.Length >= 500)
product.Bulletpoints1 = product.Description.Substring(0, 497);
else
product.Bulletpoints1 = product.Description;
}
#endregion BulletPoints
#region Image
string Images = "";
HtmlNodeCollection imgCollection = _doc.DocumentNode.SelectNodes("//img[@class=\"gallery-image\"]");
if (imgCollection != null)
{
foreach (HtmlNode node in imgCollection)
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "src")
Images = Images + attr.Value.Trim() + ",";
}
}
}
else if (_doc.DocumentNode.SelectNodes("//img[@class=\"gallery-image visible\"]") != null)
{
foreach (HtmlNode node in _doc.DocumentNode.SelectNodes("//img[@class=\"gallery-image visible\"]"))
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "src")
Images = Images + attr.Value.Trim() + ",";
}
}
}
else
WriteLogEvent(url, "Main Images not found");
if (Images.Length > 0)
Images = Images.Substring(0, Images.Length - 1);
product.Image = Images;
#endregion Image
product.Isparent = true;
#region sku
string sku = "";
if (_doc.DocumentNode.SelectNodes("//input[@name=\"product\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//input[@name=\"product\"]")[0].Attributes)
{
if (attr.Name == "value")
{
product.SKU = "HCKYSUP" + attr.Value.Trim();
product.parentsku = "HCKYSUP" + attr.Value.Trim();
sku = product.SKU;
}
}
}
else
WriteLogEvent(url, "SKU not found");
#endregion sku
#region stock
product.Stock = "0";
if (_doc.DocumentNode.SelectNodes("//span[@id=\"stock-availability\"]") != null)
{
if (_doc.DocumentNode.SelectNodes("//span[@id=\"stock-availability\"]")[0].InnerText.ToLower() == "in stock")
product.Stock = "1";
}
#endregion stock
product.URL = url;
#region Variation
bool _isVariantProduct = false;
bool _isKitProduct = false;
string attributeScript = "";
string attributeCombScript = "";
HtmlNodeCollection collOption = _doc.DocumentNode.SelectNodes("//div[@class=\"product-options\"]");
if (collOption != null)
{
_isVariantProduct = true;
if (collOption[0].SelectNodes(".//label") != null)
{
if (collOption[0].SelectNodes(".//label").Count > 2)
_isKitProduct = true;
else
{
foreach (HtmlNode node in collOption[0].SelectNodes(".//label"))
{
if (!variationTheme.Contains(node.InnerText.Trim().ToLower()))
{
_isKitProduct = true;
break;
}
}
}
}
else
{
_isKitProduct = true;
WriteLogEvent(url, "option heading Not found, due to which product marked as kit. For more information please check code if(collOption[0].SelectNodes(\".//label\")!=null)");
}
}
if (!_isKitProduct)
{
HtmlNodeCollection collScript = _doc.DocumentNode.SelectNodes("//script");
if (collScript != null)
{
foreach (HtmlNode scriptNode in collScript)
{
if (scriptNode.InnerText.ToLower().Contains("spconfig"))
{
string script = scriptNode.InnerText.ToLower();
_isVariantProduct = true;
try
{
attributeScript = script.Substring(0, script.IndexOf("var allperm")).Replace("var allperm", "").Replace("\"176\":{", "\"skate_width\":{").Replace("\"197\":{", "\"size_skates\":{").Replace("\"92\":{", "\"color\":{").Replace("\"136\":{", "\"size\":{").Replace("\"198\":{", "\"size\":{").Replace("\"199\":{", "\"size\":{").Trim();
attributeScript = attributeScript.Substring(attributeScript.IndexOf("(")).Replace(");", "").Replace("(", "");
attributeCombScript = script.Substring(script.IndexOf("var allperm")).Replace("var allperm", "").Trim();
}
catch
{
_isKitProduct = true;
WriteLogEvent(url, "script tag is not in well format, due to which this product marked as kit");
}
break;
}
}
}
else
{
_isKitProduct = true;
WriteLogEvent(url, "script tag is not found, due to which product marked as kit");
}
}
if (!_isKitProduct && !_isVariantProduct)
Products.Add(product);
else if (!_isKitProduct && _isVariantProduct)
{
try
{
string color = "";
string size = "";
string stock = "";
string saleInfo = "";
string price = "";
string filterString = "";
RootObject deserializedProduct = JsonConvert.DeserializeObject<RootObject>(attributeScript.Trim());
List<Option2> option1 = deserializedProduct.attributes.color == null ? deserializedProduct.attributes.skate_width == null ? null : deserializedProduct.attributes.skate_width.options : deserializedProduct.attributes.color.options;
List<Option2> option2 = deserializedProduct.attributes.size == null ? deserializedProduct.attributes.size_skates == null ? null : deserializedProduct.attributes.size_skates.options : deserializedProduct.attributes.size.options;
int variantCounter = 1;
if (option1 != null || option2 != null)
{
if (option1 == null)
{
try
{
foreach (Option2 sizeOption in option2)
{
bool isStockStringExist = true;
try
{
filterString = attributeCombScript.Substring(attributeCombScript.IndexOf("\"" + sizeOption.id + "\":{")).ToLower();
}
catch
{
isStockStringExist = false;
}
if (isStockStringExist)
{
BusinessLayer.Product sizeProduct = new BusinessLayer.Product();
sizeProduct = (BusinessLayer.Product)product.Clone();
sizeProduct.parentsku = sku + "-parent";
sizeProduct.SKU = sku + "-" + sizeOption.id;
sizeProduct.Size = sizeOption.label;
#region getAvailability
stock = filterString.Substring(filterString.IndexOf("\"availability\"")).Replace("\"availability\"", "");
stock = stock.Substring(0, stock.IndexOf(","));
saleInfo = filterString.Substring(filterString.IndexOf("\"saleinfo\"")).Replace("\"saleinfo\"", "");
saleInfo = saleInfo.Substring(0, saleInfo.IndexOf(","));
if (stock.Contains("normal") && saleInfo.Contains("in stock"))
sizeProduct.Stock = "1";
else
sizeProduct.Stock = "0";
price = filterString.Substring(filterString.IndexOf("\"specialprice\"")).Replace("\"specialprice\"", "");
price = price.Substring(0, price.IndexOf(",")).Replace("$", "");
double specialPrice = 0;
double.TryParse(price, out specialPrice);
if (specialPrice != 0)
sizeProduct.Price = specialPrice.ToString();
else
{
WriteLogEvent(url, "issue accured in getting price info for variants");
}
if (variantCounter != 1)
sizeProduct.Isparent = false;
Products.Add(sizeProduct);
#endregion getAvailability
variantCounter++;
}
else
{
WriteLogEvent(url, "Stock string not find for size:" + sizeOption.label);
}
}
}
catch
{ WriteLogEvent(url, "issue accured in getting stock etc info for variants"); }
}
else if (option2 == null)
{
try
{
foreach (Option2 colorOption in option1)
{
bool isStockStringExist = true;
try
{
filterString = attributeCombScript.Substring(attributeCombScript.IndexOf("\"" + colorOption.id + "\":{")).ToLower();
}
catch
{
isStockStringExist = false;
}
if (isStockStringExist)
{
BusinessLayer.Product sizeProduct = new BusinessLayer.Product();
sizeProduct = (BusinessLayer.Product)product.Clone();
sizeProduct.parentsku = sku + "-parent";
sizeProduct.SKU = sku + "-" + colorOption.id;
sizeProduct.Color = colorOption.label;
#region getAvailability
filterString = attributeCombScript.Substring(attributeCombScript.IndexOf("\"" + colorOption.id + "\":{")).ToLower();
stock = filterString.Substring(filterString.IndexOf("\"availability\"")).Replace("\"availability\"", "");
stock = stock.Substring(0, stock.IndexOf(","));
saleInfo = filterString.Substring(filterString.IndexOf("\"saleinfo\"")).Replace("\"saleinfo\"", "");
saleInfo = saleInfo.Substring(0, saleInfo.IndexOf(","));
if (stock.Contains("normal") && saleInfo.Contains("in stock"))
sizeProduct.Stock = "1";
else
sizeProduct.Stock = "0";
price = filterString.Substring(filterString.IndexOf("\"specialprice\"")).Replace("\"specialprice\"", "");
price = price.Substring(0, price.IndexOf(",")).Replace("$", "");
double specialPrice = 0;
double.TryParse(price, out specialPrice);
if (specialPrice != 0)
sizeProduct.Price = specialPrice.ToString();
else
{
WriteLogEvent(url, "issue accured in getting price info for variants");
}
if (variantCounter != 1)
sizeProduct.Isparent = false;
Products.Add(sizeProduct);
variantCounter++;
}
else
{ WriteLogEvent(url, "Stock string not find for color:" + colorOption.label); }
}
#endregion getAvailability
}
catch
{ WriteLogEvent(url, "issue accured in getting stock etc info for variants"); }
}
else
{
try
{
foreach (Option2 sizeOption in option2)
{
int loopCounter = 1;
string[] cominations = attributeCombScript.Split(new string[] { "\"" + sizeOption.id + "\":{" }, StringSplitOptions.None);
bool jsonFine = false;
try
{
foreach (string comb in cominations)
{
filterString = comb;
if (filterString.Length > 13)
{
if (loopCounter == 1 && filterString.Contains("="))
{
}
else if (!filterString.Substring(0, 13).Contains("availability") && filterString.Contains("availability"))
{
jsonFine = true;
break;
}
}
loopCounter++;
}
}
catch
{
}
if (jsonFine)
{
foreach (Option2 colorOption in option1)
{
bool isStockStringExist = true;
string filterString1 = "";
try
{
filterString1 = filterString.Substring(filterString.IndexOf("\"" + colorOption.id + "\":{")).ToLower();
}
catch
{ isStockStringExist = false; }
if (isStockStringExist)
{
BusinessLayer.Product sizeProduct = new BusinessLayer.Product();
sizeProduct = (BusinessLayer.Product)product.Clone();
sizeProduct.parentsku = sku + "-parent";
sizeProduct.SKU = sku + "-" + sizeOption.id + "-" + colorOption.id;
sizeProduct.Color = colorOption.label;
sizeProduct.Size = sizeOption.label;
#region getAvailability
stock = filterString1.Substring(filterString1.IndexOf("\"availability\"")).Replace("\"availability\"", "");
stock = stock.Substring(0, stock.IndexOf(","));
saleInfo = filterString1.Substring(filterString1.IndexOf("\"saleinfo\"")).Replace("\"saleinfo\"", "");
saleInfo = saleInfo.Substring(0, saleInfo.IndexOf(","));
if (stock.Contains("normal") && saleInfo.Contains("in stock"))
sizeProduct.Stock = "1";
else
sizeProduct.Stock = "0";
price = filterString1.Substring(filterString1.IndexOf("\"specialprice\"")).Replace("\"specialprice\"", "");
price = price.Substring(0, price.IndexOf(",")).Replace("$", "").Replace(":", "").Replace("\"", "");
double specialPrice = 0;
double.TryParse(price, out specialPrice);
if (specialPrice != 0)
sizeProduct.Price = specialPrice.ToString();
else
{
WriteLogEvent(url, "issue accured in getting price info for variants");
}
if (variantCounter != 1)
sizeProduct.Isparent = false;
Products.Add(sizeProduct);
variantCounter++;
}
else
{ WriteLogEvent(url, "Stock string not find for color:" + colorOption.label); }
#endregion getAvailability
}
}
else
WriteLogEvent(url, "Not find size option in json in order to find options stocks, size option label " + sizeOption.label + " size option id " + sizeOption.id);
}
}
catch
{ WriteLogEvent(url, "issue accured in getting stock etc info for variants"); }
}
}
else
WriteLogEvent(url, "there is no any size and color in deserialize script. Please check this on urgent basis.");
}
catch (Exception exp)
{
WriteLogEvent(url, "Issue accured in deserialize script, due to which this product had not sync to db.");
}
}
#endregion Variation
}
catch (Exception exp)
{
WriteLogEvent(url, "Issue accured in reading product info from given product url. exp: " + exp.Message);
}
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public string GetUPC(string Response)
{
string Result = "";
foreach (var ch in Response.ToCharArray())
{
if (char.IsNumber(ch))
Result = Result + ch;
else
break;
}
Int64 n;
bool isNumeric = Int64.TryParse(Result, out n);
if (n != 0)
return Result;
else
return "";
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public void WriteLogEvent(string url, string Detail)
{
writer.WriteLine(Detail + "/t" + url);
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url1, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc, Url1, Category1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading produts from category page"); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / CategoryUrl.Count));
/****************end*******************/
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc, Url1, Category1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading product Info."); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / _ProductUrl.Count));
/****************end*******************/
}
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url2, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc2, Url2, Category2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading produts from category page"); }
/**********Report progress**************/
gridindex++;
_Work1.ReportProgress((gridindex * 100 / CategoryUrl.Count));
/****************end*******************/
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc2, Url2, Category2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading product Info."); }
/**********Report progress**************/
gridindex++;
_Work1.ReportProgress((gridindex * 100 / _ProductUrl.Count));
/****************end*******************/
}
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
private void Go_Click(object sender, EventArgs e)
{
//string ss="=202{203}202{567}";
//string[] cominations = ss.Split(new string[] { "202"}, StringSplitOptions.None);
_IsProduct = false;
_percent.Visible = false;
_Bar1.Value = 0;
_lblerror.Visible = false;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
#region hockeysupremacy.com
_ISBuy = true;
_ScrapeUrl = "https://hockeysupremacy.com/";
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
if (_Work1doc.DocumentNode.SelectNodes("//a[@class=\"level1 view-all\"]") != null)
{
foreach (HtmlNode node in _Work1doc.DocumentNode.SelectNodes("//a[@class=\"level1 view-all\"]"))
{
foreach (HtmlAttribute _attr in node.Attributes)
{
if (_attr.Name == "href")
{
try
{
CategoryUrl.Add(_attr.Value.Contains("?") ? _attr.Value + "&limit=all" : _attr.Value + "?limit=all", "HCKYSUP" + node.InnerText.Trim().ToLower().Replace("view all", ""));
}
catch
{
}
}
}
}
}
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category Link for hockeysupremacy.com Website";
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (CategoryUrl.Count() > 0)
{
gridindex = 0;
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read products from category page.";
_Stop = false;
time = 0;
_IsCategory = true;
tim(3);
totalrecord.Visible = true;
totalrecord.Text = "Total No Pages :" + CategoryUrl.Count.ToString();
foreach (var url in CategoryUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key;
Category1 = url.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
Category2 = url.Value;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product info.";
_IsCategory = false;
_IsProduct = true;
gridindex = 0;
totalrecord.Text = "Total No Products :" + _ProductUrl.Count.ToString();
foreach (var url in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key;
Category1 = url.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
Category2 = url.Value;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#region InsertScrappedProductInDatabase
if (Products.Count() > 0)
{
_Prd.ProductDatabaseIntegration(Products, "hockeysupremacy.com", 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='hockeysupremacy.com'");
_Prd.ProductDatabaseIntegration(Products, "hockeysupremacy.com", 1);
_Mail.SendMail("OOPS there is no any product scrapped by app for hockeysupremacy.com Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#endregion InsertScrappedProductInDatabase
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Prd.ProductDatabaseIntegration(Products, "hockeysupremacy.com", 1);
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='hockeysupremacy.com'");
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for hockeysupremacy.com Website";
/****************Email****************/
_Mail.SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for hockeysupremacy.com Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
/*******************End********/
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='hockeysupremacy.com'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data hockeysupremacy.com Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
# endregion hockeysupremacy.com
writer.Close();
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Form1_Shown(object sender, EventArgs e)
{
base.Show();
this.Go_Click(null, null);
}
}
public class ExtendedWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = 120000;
return w;
}
}
public class Option2
{
public string id { get; set; }
public string label { get; set; }
public string price { get; set; }
public string oldPrice { get; set; }
public List<string> products { get; set; }
}
public class skate_width
{
public string id { get; set; }
public string code { get; set; }
public string label { get; set; }
public List<Option2> options { get; set; }
}
public class color
{
public string id { get; set; }
public string code { get; set; }
public string label { get; set; }
public List<Option2> options { get; set; }
}
public class size
{
public string id { get; set; }
public string code { get; set; }
public string label { get; set; }
public List<Option2> options { get; set; }
}
public class size_skates
{
public string id { get; set; }
public string code { get; set; }
public string label { get; set; }
public List<Option2> options { get; set; }
}
public class Attributes
{
public skate_width skate_width { get; set; }
public size_skates size_skates { get; set; }
public color color { get; set; }
public size size { get; set; }
}
public class TaxConfig
{
public bool includeTax { get; set; }
public bool showIncludeTax { get; set; }
public bool showBothPrices { get; set; }
public double defaultTax { get; set; }
public int currentTax { get; set; }
public string inclTaxTitle { get; set; }
}
public class RootObject
{
public Attributes attributes { get; set; }
public string template { get; set; }
public string basePrice { get; set; }
public string oldPrice { get; set; }
public string productId { get; set; }
public string chooseText { get; set; }
public TaxConfig taxConfig { get; set; }
}
}
<file_sep>/Project 1/Version1/palyerborndate/palyerborndate/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
namespace palyerborndate
{
public partial class Form1 : Form
{
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1= new BackgroundWorker();
bool _Iscompleted = false;
bool _ISWarrior = false;
bool _ISchilychiles = false;
bool _IsAirsoft = false;
bool _IsKnifezone = false;
bool _IsLiveoutthere = false;
string Url1 = "";
int _Workindex = 0;
int _WorkIndex1 = 0;
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
string Url2 = "";
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
DataTable _Tbale = new DataTable();
string _ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&keyword=keywords&search_in_description=1&product_type=&kfi_blade_length_from=0&kfi_blade_length_to=15&kfi_overall_length_from=0&kfi_overall_length_to=30&kfi_serration=ANY&kfi_is_coated=ANY&kfo_blade_length_from=0&kfo_blade_length_to=8&kfo_overall_length_from=0&kfo_overall_length_to=20&kfo_serration=ANY&kfo_is_coated=ANY&kfo_assisted=ANY&kk_blade_length_from=0&kk_blade_length_to=15&fl_lumens_from=0&fl_lumens_to=18000&fl_num_cells_from=1&fl_num_cells_to=10&fl_num_modes_from=1&fl_num_modes_to=15&sw_blade_length_from=0&sw_blade_length_to=60&sw_overall_length_from=0&sw_overall_length_to=70&inc_subcat=1&pfrom=0.01&pto=10000.00&x=36&y=6&perPage=60";
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
bool _IsCategory = true;
bool _Stop = false;
int time = 0;
string Bullets = "";
string _Description = "";
public Form1()
{
InitializeComponent();
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void Form1_Load(object sender, EventArgs e)
{
/****************Code to select all check boxes*************/
for (int i = 0; i < chkstorelist.Items.Count; i++)
{
chkstorelist.SetItemChecked(i, true);
}
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
createcsvfile.Enabled = false;
_percent.Visible = false;
createcsvfile.Enabled = false;
Pause.Enabled = false;
dataGridView1.Columns.Add("RowID", "RowID");
dataGridView1.Columns.Add("SKU", "SKU");
dataGridView1.Columns.Add("Product Name", "Product Name");
dataGridView1.Columns.Add("Product Description", "Product Description");
dataGridView1.Columns.Add("Bullet Points", "Bullet Points");
dataGridView1.Columns.Add("Manufacturer","Manufacturer");
dataGridView1.Columns.Add("Brand Name", "Brand Name");
dataGridView1.Columns.Add("Price", "Price");
dataGridView1.Columns.Add("Currency", "Currency");
dataGridView1.Columns.Add("In Stock", "In Stock");
dataGridView1.Columns.Add("Image URL", "Image URL");
dataGridView1.Columns.Add("URL", "URL");
/****************BackGround worker *************************/
}
public void tim(int t)
{
time = 0;
timer1.Start();
try
{
while (time <= t)
{
Application.DoEvents();
}
}
catch (Exception) { }
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
time++;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public void Disableallstores()
{
_ISWarrior = false;
_Iscompleted = false;
_ISchilychiles = false;
_IsAirsoft = false;
_IsKnifezone = false;
_IsLiveoutthere = false;
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
}
catch
{
_Iserror = true;
}
int index = 0;
if (_ISWarrior)
{
if (_IsCategory)
{
index = gridindex;
gridindex++;
try
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//table[@id=\"catTable\"]//tr");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
if (_Node.Attributes[0].Value.ToLower() == "productlisting-odd" || _Node.Attributes[0].Value.ToLower() == "productlisting-even")
{
DataRow _Dr = _Tbale.NewRow();
_Dr[8] = "CDN";
HtmlNodeCollection _Collection1 = _Node.SelectNodes("td");
if (_Collection1 != null)
{
/***************Sku**************/
try
{
_Dr[1] = _Collection1[0].InnerText;
}
catch
{
}
/************End*****************/
/***************product name**************/
try
{
string test = _Collection1[3].SelectNodes("h3")[0].InnerText;
_Dr[2] = _Collection1[3].SelectNodes("h3")[0].InnerText;
}
catch
{
}
/************manufacturer*****************/
try
{
_Dr[5] = _Collection1[1].InnerText;
_Dr[6] = _Collection1[1].InnerText;
}
catch
{
}
/***************Price**************/
try
{
string Price = "";
if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]")[0].InnerText;
}
else if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]")[0].InnerText;
}
else
{
try
{
Price = _Collection1[4].SelectNodes("span[@class=\"product_list_price\"]")[0].InnerText;
}
catch
{
}
}
Price = Price.Replace("$", "");
Price = Price.ToLower().Replace("price", "").Replace("cdn", "").Trim();
_Dr[7] = Price;
}
catch
{
}
/***************End******************/
/***************In stock**************/
try
{
if (_Collection1[4].InnerText.ToLower().Contains("out of stock"))
{
_Dr[9] = "N";
}
else
{
_Dr[9] = "Y";
}
}
catch
{
}
/**************Image****************/
try
{
if (_Collection1[2].SelectNodes("a//img") != null)
{
_Dr[10] = "http://www.warriorsandwonders.com/" + _Collection1[2].SelectNodes("a//img")[0].Attributes[0].Value;
}
}
catch
{
}
/****************End*****************/
/**************Link**************/
try
{
if (_Collection1[2].SelectNodes("a") != null)
{
_Dr[11] = _Collection1[2].SelectNodes("a")[0].Attributes[0].Value;
}
}
catch
{
}
/*****************End*************/
}
_Tbale.Rows.Add(_Dr);
}
}
/***********Sku**************/
/**************End*************/
}
}
catch
{
}
/**********Report progress**************/
_Work.ReportProgress((gridindex * 100 / _Pages));
/****************end*******************/
}
else
{
index = gridindex;
gridindex++;
try
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productDescription\"]");
if (_Collection != null)
{
_Description = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productDescription\"]")[0].InnerHtml;
try
{
List<string> _Remove = new List<string>();
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productDescription\"]")[0].ChildNodes)
{
if (_Node.InnerText.ToLower().Contains("price:") || _Node.InnerText.ToLower().Contains("msrp:"))
{
_Remove.Add(_Node.InnerHtml);
}
}
foreach (string _rem in _Remove)
{
_Description = _Description.Replace(_rem, "");
}
}
catch
{
}
}
}
catch
{
_Description = "";
}
_Description = StripHTML(_Description);
try
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@id=\"productDetailsList\"]");
if (_Collection != null)
{
Bullets = StripHTML(_Work1doc.DocumentNode.SelectNodes("//ul[@id=\"productDetailsList\"]")[0].InnerHtml);
}
}
catch
{
Bullets = "";
}
_Iscompleted = true;
if (_Iserror)
{
_Description = "";
Bullets = "";
}
_Work.ReportProgress((gridindex * 100 / _Tbale.Rows.Count));
}
}
else if(_ISchilychiles)
{
}
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
int index = 0;
if (_ISWarrior)
{
if (_IsCategory)
{
index = gridindex;
gridindex++;
try
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//table[@id=\"catTable\"]//tr");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
if (_Node.Attributes[0].Value.ToLower() == "productlisting-odd" || _Node.Attributes[0].Value.ToLower() == "productlisting-even")
{
DataRow _Dr = _Tbale.NewRow();
_Dr[8] = "CDN";
HtmlNodeCollection _Collection1 = _Node.SelectNodes("td");
if (_Collection1 != null)
{
/***************Sku**************/
try
{
_Dr[1] = _Collection1[0].InnerText;
}
catch
{
}
/************End*****************/
/***************product name**************/
try
{
string test = _Collection1[3].SelectNodes("h3")[0].InnerText;
_Dr[2] = _Collection1[3].SelectNodes("h3")[0].InnerText;
}
catch
{
}
/************manufacturer*****************/
try
{
_Dr[5] = _Collection1[1].InnerText;
_Dr[6] = _Collection1[1].InnerText;
}
catch
{
}
/***************Price**************/
try
{
string Price = "";
if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]")[0].InnerText;
}
else if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]")[0].InnerText;
}
else
{
try
{
Price = _Collection1[4].SelectNodes("span[@class=\"product_list_price\"]")[0].InnerText;
}
catch
{
}
}
Price = Price.Replace("$", "");
Price = Price.ToLower().Replace("price", "").Replace("cdn", "").Trim();
_Dr[7] = Price;
}
catch
{
}
/***************End******************/
/***************In stock**************/
try
{
if (_Collection1[4].InnerText.ToLower().Contains("out of stock"))
{
_Dr[9] = "N";
}
else
{
_Dr[9] = "Y";
}
}
catch
{
}
/**************Image****************/
try
{
if (_Collection1[2].SelectNodes("a//img") != null)
{
_Dr[10] = "http://www.warriorsandwonders.com/" + _Collection1[2].SelectNodes("a//img")[0].Attributes[0].Value;
}
}
catch
{
}
/****************End*****************/
/**************Link**************/
try
{
if (_Collection1[2].SelectNodes("a") != null)
{
_Dr[11] = _Collection1[2].SelectNodes("a")[0].Attributes[0].Value;
}
}
catch
{
}
/*****************End*************/
}
_Tbale.Rows.Add(_Dr);
}
}
/***********Sku**************/
/**************End*************/
}
}
catch
{
}
/**********Report progress**************/
_Work1.ReportProgress((gridindex * 100 / _Pages));
/****************end*******************/
}
else
{
}
}
else if(_ISchilychiles)
{ }
}
private void Go_Click(object sender, EventArgs e)
{
_percent.Visible = false;
Go.Enabled = false;
Pause.Enabled = true;
createcsvfile.Enabled = true;
_Bar1.Value = 0;
_Url.Clear();
_Tbale.Rows.Clear();
_Tbale.Columns.Clear();
dataGridView1.Rows.Clear();
DataColumn _Dc = new DataColumn();
_Dc.ColumnName = "Rowid";
_Dc.AutoIncrement = true;
_Dc.DataType = typeof(int);
_Dc.AutoIncrementSeed = 1;
_Dc.AutoIncrementStep = 1;
_Tbale.Columns.Add(_Dc);
_Tbale.Columns.Add("SKU", typeof(string));
_Tbale.Columns.Add("Product Name", typeof(string));
_Tbale.Columns.Add("Product Description", typeof(string));
_Tbale.Columns.Add("Bullet Points", typeof(string));
_Tbale.Columns.Add("Manufacturer", typeof(string));
_Tbale.Columns.Add("Brand Name", typeof(string));
_Tbale.Columns.Add("Price", typeof(string));
_Tbale.Columns.Add("Currency", typeof(string));
_Tbale.Columns.Add("In Stock", typeof(string));
_Tbale.Columns.Add("Image URL", typeof(string));
_Tbale.Columns.Add("URL", typeof(string));
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
if (chkstorelist.GetItemChecked(0))
{
_ISWarrior = true;
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read sku and manufacturer information form category page of " + chkstorelist.Items[0].ToString() + " Website";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productsListingTopNumber\"]//strong");
if (_Collection != null)
{
_TotalRecords = Convert.ToInt32(_Work1doc.DocumentNode.SelectNodes("//div[@id=\"productsListingTopNumber\"]//strong")[2].InnerText);
_Pages = Convert.ToInt32(_TotalRecords / 60) + 1;
for (int i = 1; i <= _Pages; i++)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
tim(2);
if (!_Work.IsBusy)
{
Url1 = _ScrapeUrl + "&page=" + i;
_Work.RunWorkerAsync();
}
else
{
Url2 = _ScrapeUrl + "&page=" + i;
_Work1.RunWorkerAsync();
}
tim(2);
tim(2);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read Decsription and Bullets information from product page of " + chkstorelist.Items[0].ToString() + " Website";
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
_IsCategory = false;
tim(3);
totalrecord.Visible = true;
totalrecord.Text = "Total Products :" + _Tbale.Rows.Count.ToString();
int Counter = 0;
foreach (DataRow _Row in _Tbale.Rows)
{
while (_Work.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
_Iscompleted = false;
_Description = "";
Bullets = "";
Url1 = _Row[11].ToString();
_Work.RunWorkerAsync();
while (!_Iscompleted)
{
Application.DoEvents();
}
dataGridView1.Rows.Add();
for (int i = 0; i < 12; i++)
{
dataGridView1.Rows[Counter].Cells[i].Value = _Row[i].ToString();
}
dataGridView1.Rows[Counter].Cells[3].Value = _Description;
dataGridView1.Rows[Counter].Cells[4].Value = Bullets;
Counter++;
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_lblerror.Visible = true;
_lblerror.Text = "All Products Scrapped for " + chkstorelist.Items[0].ToString()+ " Website";
}
else
{
_lblerror.Visible = true;
_lblerror.Text = "Oops Some issue Occured in scrapping data " + chkstorelist.Items[0].ToString()+ " Website";
}
}
catch
{
_lblerror.Visible = true;
_lblerror.Text = "Oops Some issue Occured in scrapping data " + chkstorelist.Items[0].ToString()+ " Website";
}
Disableallstores();
}
else if (chkstorelist.GetItemChecked(1))
{
_ISchilychiles = true;
}
MessageBox.Show("Process Completed.");
Pause.Enabled = false;
Go.Enabled = true;
}
private void Pause_Click(object sender, EventArgs e)
{
if (Pause.Text.ToUpper() == "PAUSE")//for pause and resume process
{
_Stop = true;
Pause.Text = "RESUME";
}
else
{
_Stop = false;
Pause.Text = "Pause";
}
}
private void createcsvfile_Click(object sender, EventArgs e)
{
DataTable exceldt = new DataTable();
exceldt.Columns.Add("Rowid", typeof(int));
exceldt.Columns.Add("SKU", typeof(string));
exceldt.Columns.Add("Product Name", typeof(string));
exceldt.Columns.Add("Product Description", typeof(string));
exceldt.Columns.Add("Bullet Points", typeof(string));
exceldt.Columns.Add("Manufacturer", typeof(string));
exceldt.Columns.Add("Brand Name", typeof(string));
exceldt.Columns.Add("Price", typeof(string));
exceldt.Columns.Add("Currency", typeof(string));
exceldt.Columns.Add("In Stock", typeof(string));
exceldt.Columns.Add("Image URL", typeof(string));
for (int m = 0; m < dataGridView1.Rows.Count; m++)
{
exceldt.Rows.Add();
for (int n = 0; n < dataGridView1.Columns.Count-1; n++)
{
if (dataGridView1.Rows[m].Cells[n].Value == null || dataGridView1.Rows[m].Cells[n].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[m].Cells[n].Value.ToString()))
continue;
exceldt.Rows[m][n] = dataGridView1.Rows[m].Cells[n].Value.ToString();
}
}
try
{
using (CsvFileWriter writer = new CsvFileWriter(Application.StartupPath + "/" + "data.txt"))
{
CsvFileWriter.CsvRow row = new CsvFileWriter.CsvRow();//HEADER FOR CSV FILE
row.Add("SKU");
row.Add("Product Name");
row.Add("Product Description");
row.Add("Bullet Points");
row.Add("Manufacturer");
row.Add("Brand Name");
row.Add("Price");
row.Add("Currency");
row.Add("In Stock");
row.Add("Image URL");
writer.WriteRow(row);//INSERT TO CSV FILE HEADER
for (int m = 0; m < exceldt.Rows.Count ; m++)
{
CsvFileWriter.CsvRow row1 = new CsvFileWriter.CsvRow();
for (int n = 1; n < exceldt.Columns.Count; n++)
{
row1.Add(String.Format("{0}", exceldt.Rows[m][n].ToString().Replace("\n", "").Replace("\r", "").Replace("\t", "")));
}
writer.WriteRow(row1);
}
}
System.Diagnostics.Process.Start(Application.StartupPath + "/" + "data.txt");//OPEN THE CSV FILE ,,CSV FILE NAMED AS DATA.CSV
}
catch (Exception) { MessageBox.Show("file is already open\nclose the file"); }
return;
}
public class CsvFileWriter : StreamWriter //Writing data to CSV
{
public CsvFileWriter(Stream stream)
: base(stream)
{
}
public CsvFileWriter(string filename)
: base(filename)
{
}
public class CsvRow : List<string> //Making each CSV rows
{
public string LineText { get; set; }
}
public void WriteRow(CsvRow row)
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in row)
{
builder.Append( value.Replace("\n", "") + "\t");
}
row.LineText = builder.ToString();
WriteLine(row.LineText);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void totalrecord_Click(object sender, EventArgs e)
{
}
private void _percent_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>/WindowsFormsApplication1/WindowsFormsApplication1/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool result = false;
HtmlAgilityPack.HtmlDocument _Document2 = new HtmlAgilityPack.HtmlDocument();
List<string> urls = new List<string>();
public Form1()
{
InitializeComponent();
urls.Add("http://store.401games.ca/catalog/94040C/action-figures-apparel#st=&begin=1&nhit=40&dir=asc&cat=94040");
urls.Add("http://store.401games.ca/catalog/94040C/action-figures-apparel#st=&begin=41&nhit=40&dir=asc&cat=94040");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
_Document2.LoadHtml(webBrowser1.DocumentText.ToString());
while (!result)
{
if (_Document2.DocumentNode.SelectNodes("//div[@class=\"pages\"]/ul/li") != null)
{
result = true;
}
else
{
Application.DoEvents();
}
}
}
catch
{
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach(string url in urls)
{
result=false;
webBrowser1.Navigate(url);
while (!result)
{
Application.DoEvents();
}
}
}
}
}
<file_sep>/Project 1/palyerborndate/BusinessLayer/APPConfig.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLayer
{
public class APPConfig
{
public dynamic GetAppConfigValue(string StoreName, string ConfigName)
{
dynamic Result = null;
DB db = new DB();
try
{
SqlDataReader _Reader = null;
var _Con = db.Connection();
SqlCommand _CMD = new SqlCommand("select top 1 configvalue from appconfig join Store on store.StoreID=appconfig.storeid where appconfig.name='" + ConfigName + "' and store.StoreName='" + StoreName + "'");
if (_Con.State == ConnectionState.Closed)
_Con.Open();
_CMD.Connection = _Con;
_CMD.CommandType = CommandType.Text;
_Reader = _CMD.ExecuteReader(CommandBehavior.CloseConnection);
if (_Reader.HasRows)
{
while (_Reader.Read())
{
Result = _Reader[0];
}
}
_Reader.Close();
}
catch
{ }
return Result;
}
}
}
<file_sep>/Project5_Henry/Crawler_WithouSizes_Part3/Crawler_WithouSizes_Part3/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
namespace Crawler_WithouSizes_Part3
{
public partial class Form1 : Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
StreamWriter _writer = new StreamWriter(Application.StartupPath + "/test.csv");
#region booltypevariable
bool _ISHenry = true;
bool _IsProduct = false;
bool _IsCategory = true;
bool _IsCategorypaging = false;
bool _Stop = false;
int totalproducts = 0;
string Conditonwork1 = "";
string Conditonwork2 = "";
#endregion booltypevariable
#region intypevariable
int gridindex = 0;
int _canadadronesindex = 0;
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string BrandName1 = "";
string BrandName2 = "";
string _ScrapeUrl = "";
string Bullets = "";
string _Description1 = "";
string _Description2 = "";
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
Dictionary<string, string> _ProductUrl = new Dictionary<string, string>();
List<string> _Name = new List<string>();
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> SubCategoryUrl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
DataTable _Tbale = new DataTable();
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public void DisplayRecordProcessdetails(string Message, string TotalrecordMessage)
{
_lblerror.Visible = true;
_lblerror.Text = Message;
totalrecord.Visible = true;
totalrecord.Text = TotalrecordMessage;
}
public void Process()
{
_IsProduct = false;
_Name.Clear();
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_ProductUrl.Clear();
_percent.Visible = false;
_Bar1.Value = 0;
_Url.Clear();
_Tbale.Rows.Clear();
_Tbale.Columns.Clear();
dataGridView1.Rows.Clear();
DataColumn _Dc = new DataColumn();
_Dc.ColumnName = "Rowid";
_Dc.AutoIncrement = true;
_Dc.DataType = typeof(int);
_Dc.AutoIncrementSeed = 1;
_Dc.AutoIncrementStep = 1;
_Tbale.Columns.Add(_Dc);
_Tbale.Columns.Add("SKU", typeof(string));
_Tbale.Columns.Add("Product Name", typeof(string));
_Tbale.Columns.Add("Product Description", typeof(string));
_Tbale.Columns.Add("Bullet Points", typeof(string));
_Tbale.Columns.Add("Manufacturer", typeof(string));
_Tbale.Columns.Add("Brand Name", typeof(string));
_Tbale.Columns.Add("Price", typeof(string));
_Tbale.Columns.Add("Currency", typeof(string));
_Tbale.Columns.Add("In Stock", typeof(string));
_Tbale.Columns.Add("Image URL", typeof(string));
_Tbale.Columns.Add("Condition", typeof(string));
_Tbale.Columns.Add("URL", typeof(string));
_lblerror.Visible = false;
gridindex = 0;
_IsCategory = true;
_Stop = false;
#region Henery
_ISHenry = true;
_ScrapeUrl = "http://www.henrys.com/";
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category url for " + chkstorelist.Items[0].ToString() + " Website";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@id=\"header-menus\"]/li");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
try
{
string HeaderText = _Work1doc.DocumentNode.SelectNodes(_Node.XPath + "/a[1]")[0].InnerText.Trim().ToLower();
if (HeaderText != "on sale" && HeaderText != "learning" && HeaderText != "events")
{
HtmlNodeCollection _CollectionA = null;
_CollectionA = _Node.SelectNodes(".//div[@class=\"drop-contentA\"]/div/ul/li");
if (_CollectionA == null)
{
_CollectionA = _Node.SelectNodes(".//div[@class=\"drop-contentB\"]/div/ul/li");
}
if (_CollectionA != null)
{
foreach (HtmlNode _NodeSubCat in _CollectionA)
{
bool _IsAnchorTagExist = false;
try
{
HtmlNode Anchor = _NodeSubCat.SelectNodes(_NodeSubCat.XPath + "/a[1]")[0];
foreach (HtmlAttribute _Att in Anchor.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
_IsAnchorTagExist = true;
try
{
if (_Att.Value.ToLower().Contains(".aspx") && !_Att.Value.ToLower().Contains("schoolofimaging") && !_Att.Value.ToLower().Contains("gift-Card") && !Anchor.InnerText.ToLower().Contains("henry's"))
{
CategoryUrl.Add(System.Net.WebUtility.HtmlDecode(_Att.Value).Substring(0, _Att.Value.ToLower().IndexOf(".aspx") + 5), System.Net.WebUtility.HtmlDecode(Anchor.InnerText.Trim()) + "@@" + HeaderText);
}
}
catch
{
}
}
}
if (!_IsAnchorTagExist)
{
HtmlNodeCollection _CollectionCatlink = _NodeSubCat.SelectNodes("./div[@class=\"flyout-container\"]/p/a");
if (_CollectionCatlink != null)
{
foreach (HtmlAttribute _Attribute in _CollectionCatlink[0].Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
try
{
if (_Attribute.Value.ToLower().Contains(".aspx") && !_Attribute.Value.ToLower().Contains("schoolofimaging") && !_Attribute.Value.ToLower().Contains("gift-Card") && !Anchor.InnerText.ToLower().Contains("henry's"))
{
CategoryUrl.Add(System.Net.WebUtility.HtmlDecode(_Attribute.Value).Substring(0, _Attribute.Value.ToLower().IndexOf(".aspx") + 5), System.Net.WebUtility.HtmlDecode(Anchor.InnerText.Trim()) + "@@" + HeaderText);
}
}
catch
{
}
}
}
}
else
{
HtmlNodeCollection _CollectionCatlinks = _NodeSubCat.SelectNodes(".//div[@class=\"flyout-container\"]/ul/li/a");
foreach (HtmlNode _Nodecat in _CollectionCatlinks)
{
foreach (HtmlAttribute _Attribute in _Nodecat.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
try
{
if (_Attribute.Value.ToLower().Contains(".aspx") && !_Attribute.Value.ToLower().Contains("schoolofimaging") && !_Attribute.Value.ToLower().Contains("gift-Card") && !Anchor.InnerText.ToLower().Contains("henry's"))
{
CategoryUrl.Add(System.Net.WebUtility.HtmlDecode(_Attribute.Value).Substring(0, _Attribute.Value.ToLower().IndexOf(".aspx") + 5), System.Net.WebUtility.HtmlDecode(Anchor.InnerText.Trim()) + "@@" + HeaderText);
}
}
catch
{
}
}
}
}
}
}
}
catch
{
}
}
}
else
{
}
}
else
{
}
}
catch
{
}
}
}
if (CategoryUrl.Count() > 0)
{
#region Category
DisplayRecordProcessdetails("We are going to read paging from category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
_IsCategorypaging = true;
foreach (var Caturl in CategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = "http://www.henrys.com" + Caturl.Key;
BrandName1 = Caturl.Value.Replace("›", "").Trim();
_Work.RunWorkerAsync();
}
else
{
Url2 = "http://www.henrys.com" + Caturl.Key;
BrandName2 = Caturl.Value.Replace("›", "").Trim();
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion Category
#region ProductUrl
System.Threading.Thread.Sleep(1000);
_Bar1.Value = 0;
_canadadronesindex = 0;
_IsCategorypaging = false;
_IsCategory = true;
DisplayRecordProcessdetails("We are going to read Product url for " + chkstorelist.Items[0].ToString() + " Website", "Total category url :" + SubCategoryUrl.Count());
foreach (var CatUrl in SubCategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
BrandName1 = CatUrl.Value;
Url1 = CatUrl.Key;
_Work.RunWorkerAsync();
}
else
{
BrandName2 = CatUrl.Value;
Url2 = CatUrl.Key;
_Work1.RunWorkerAsync();
}
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion ProductUrl
#region ProductInformation
_Bar1.Value = 0;
System.Threading.Thread.Sleep(1000);
_canadadronesindex = 0;
_IsCategory = false;
_IsProduct = true;
DisplayRecordProcessdetails("We are going to read Product Information for " + chkstorelist.Items[0].ToString() + " Website", "Total Products :" + _ProductUrl.Count());
foreach (var PrdUrl in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
BrandName1 = PrdUrl.Value.Split(new string[] { "@@" }, StringSplitOptions.None)[0];
try
{
Conditonwork1 = PrdUrl.Value.Split(new string[] { "@@" }, StringSplitOptions.None)[1];
}
catch
{
}
Url1 = PrdUrl.Key;
_Work.RunWorkerAsync();
}
else
{
BrandName2 = PrdUrl.Value.Split(new string[] { "@@" }, StringSplitOptions.None)[0];
try
{
Conditonwork2 = PrdUrl.Value.Split(new string[] { "@@" }, StringSplitOptions.None)[1];
}
catch
{
}
Url2 = PrdUrl.Key;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion ProductInformation
System.Threading.Thread.Sleep(1000);
_lblerror.Visible = true;
_lblerror.Text = "Now we going to generate Csv File";
GenerateCSVFile();
MessageBox.Show("Process Completed.");
}
catch
{
}
#endregion Henery
_writer.Close();
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
int Countererror = 1;
bool _Iserror = false;
do
{
try
{
Countererror++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
}
catch
{
_Iserror = true;
}
} while (_Iserror && Countererror <= 5);
#region henrys
if (_ISHenry)
{
if (_IsCategorypaging)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"productgridview\"]");
if (_Collection != null)
{
try
{
int _TotalPages = 0;
int TotalRecords = Convert.ToInt32(Regex.Replace(_Work1doc.DocumentNode.SelectNodes("//div[@class=\"toolbar-count\"]")[0].InnerText.ToLower().Replace("\r", "").Replace("\n", "").ToLower().Replace("products", "").Replace("of", "").Trim(), "[^0-9+]", string.Empty));
if (TotalRecords % 12 == 0)
{
_TotalPages = Convert.ToInt32(TotalRecords / 12);
}
else
{
_TotalPages = Convert.ToInt32(TotalRecords / 12) + 1;
}
totalproducts = totalproducts + TotalRecords;
for (int Page = 1; Page <= _TotalPages; Page++)
{
try
{
SubCategoryUrl.Add(Url1 + "/" + Page, BrandName1);
}
catch
{
}
}
}
catch
{
try
{
SubCategoryUrl.Add(Url1, BrandName1);
}
catch
{
}
}
}
else
{
_writer.WriteLine(Url1);
}
}
else
{
_writer.WriteLine(Url1);
}
_canadadronesindex++;
_Work.ReportProgress((_canadadronesindex * 100 / CategoryUrl.Count()));
}
else if (_IsCategory)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"productgridview\"]/li/div[@class=\"img\"]/a");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
HtmlAttributeCollection _AttColl = _Node.Attributes;
foreach (HtmlAttribute _Att in _AttColl)
{
if (_Att.Name.ToLower() == "href")
{
try
{
if (!_ProductUrl.Keys.Contains("http://www.henrys.com/" + _Att.Value.ToLower().Replace("../", "")))
_ProductUrl.Add("http://www.henrys.com/" + _Att.Value.ToLower().Replace("../", ""), BrandName1);
}
catch
{
}
}
}
}
}
else
{
_writer.WriteLine(Url1);
}
_canadadronesindex++;
_Work.ReportProgress((_canadadronesindex * 100 / SubCategoryUrl.Count()));
}
else
{
_writer.WriteLine(Url1);
}
}
else
{
_canadadronesindex++;
_Work.ReportProgress((_canadadronesindex * 100 / _ProductUrl.Count()));
}
}
#endregion henrys
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
int Countererror = 1;
bool _Iserror = false;
do
{
try
{
Countererror++;
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
}
catch
{
_Iserror = true;
}
} while (_Iserror && Countererror <= 5);
#region henrys
if (_ISHenry)
{
if (_IsCategorypaging)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//ul[@class=\"productgridview\"]");
if (_Collection != null)
{
try
{
int _TotalPages = 0;
int TotalRecords = Convert.ToInt32(Regex.Replace(_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"toolbar-count\"]")[0].InnerText.ToLower().Replace("\r", "").Replace("\n", "").ToLower().Replace("products", "").Replace("of", "").Trim(), "[^0-9+]", string.Empty));
if (TotalRecords % 12 == 0)
{
_TotalPages = Convert.ToInt32(TotalRecords / 12);
}
else
{
_TotalPages = Convert.ToInt32(TotalRecords / 12) + 1;
}
totalproducts = totalproducts + TotalRecords;
for (int Page = 1; Page <= _TotalPages; Page++)
{
try
{
SubCategoryUrl.Add(Url2 + "/" + Page, BrandName2);
}
catch
{
}
}
}
catch
{
try
{
SubCategoryUrl.Add(Url2, BrandName2);
}
catch
{
}
}
}
else
{
_writer.WriteLine(Url2);
}
}
else
{
}
_canadadronesindex++;
_Work1.ReportProgress((_canadadronesindex * 100 / CategoryUrl.Count()));
}
else if (_IsCategory)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//ul[@class=\"productgridview\"]/li/div[@class=\"img\"]/a");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
HtmlAttributeCollection _AttColl = _Node.Attributes;
foreach (HtmlAttribute _Att in _AttColl)
{
if (_Att.Name.ToLower() == "href")
{
try
{
if (!_ProductUrl.Keys.Contains("http://www.henrys.com/" + _Att.Value.ToLower().Replace("../", "")))
_ProductUrl.Add("http://www.henrys.com/" + _Att.Value.ToLower().Replace("../", ""), BrandName1);
}
catch
{
}
}
}
}
}
else
{
_writer.WriteLine(Url2);
}
_canadadronesindex++;
_Work1.ReportProgress((_canadadronesindex * 100 / SubCategoryUrl.Count()));
}
else
{
}
}
else
{
_canadadronesindex++;
_Work1.ReportProgress((_canadadronesindex * 100 / _ProductUrl.Count()));
}
}
#endregion henrys
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
#region henrys
if (_ISHenry)
{
if (_IsProduct)
{
string AvailabilkityText = "";
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]")[0].InnerText.ToLower().Contains("item only available for in store shopping"))
{
AvailabilkityText = "no";
}
}
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"prodimgbuycontainer\"]") != null)
{
if (AvailabilkityText == "")
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[17].Value = Url1;
dataGridView1.Rows[index].Cells[16].Value = BrandName1;
#region title
HtmlNodeCollection _Title = _Work1doc.DocumentNode.SelectNodes("//h2[@class=\"productTitle\"]");
if (_Title != null)
{
dataGridView1.Rows[index].Cells[2].Value = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("Henrys", "").Replace("Henry's", "").Replace("HENRY'S", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "");
}
else
{
HtmlNodeCollection _Title1 = _Work1doc.DocumentNode.SelectNodes("//meta[@itemprop=\"name\"]");
if (_Title1 != null)
{
dataGridView1.Rows[index].Cells[2].Value = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("Henrys", "").Replace("Henry's", "").Replace("HENRY'S", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "");
}
}
#endregion title
#region description
_Description1 = "";
HtmlNodeCollection _description = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ProductOverviewContent\"]");
if (_description != null)
{
_Description1 = _description[0].InnerHtml.Replace("Product Description", "").Trim();
#region CodeToReMoveText
if (_Description1.Trim().Length > 0)
{
List<string> _Remove = new List<string>();
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ProductOverviewContent\"]")[0].ChildNodes)
{
if (_Node.InnerText.ToLower().Contains("special orders") || _Node.InnerText.ToLower().Contains("henry's") || _Node.InnerText.ToLower().Contains("stock is limited") || _Node.InnerText.ToLower().Contains("please note") || _Node.InnerText.ToLower().Contains("credit card"))
{
_Remove.Add(_Node.InnerHtml);
}
}
foreach (string _rem in _Remove)
{
_Description1 = _Description1.Replace(_rem, "");
}
}
#endregion CodeToReMoveText
_Description1 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_Description1).Trim());
}
else
{
}
try
{
if (_Description1.Length > 2000)
{
_Description1 = _Description1.Substring(0, 1997) + "...";
}
}
catch
{
}
string Desc = System.Net.WebUtility.HtmlDecode(_Description1.Replace("Â", "").Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("online only", "").Replace("Online Only", ""));
if (Desc.Trim() != "")
{
if (Desc.Substring(0, 1) == "\"")
{
dataGridView1.Rows[index].Cells[3].Value = Desc.Substring(1).Replace(",", " ");
}
else
{
dataGridView1.Rows[index].Cells[3].Value = Desc.Replace(",", " "); ;
}
}
#endregion description
#region Bullets
string Bullets = "";
int PointCounter = 1;
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]")[0].InnerText.ToLower().Contains("special order"))
{
Bullets = "This is special Item.Estimated delivery 3-4 weeks (subject to availability). Please note that Special Order Items cannot be cancelled or returned." + Bullets;
}
}
HtmlNodeCollection _ColectionBullet = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"attributetablecontainer\"]/table[@class=\"attributetable\"]/tr");
if (_ColectionBullet != null)
{
foreach (HtmlNode _Node in _ColectionBullet)
{
HtmlNodeCollection _Collectiontd = _Node.SelectNodes(".//td");
if (_Collectiontd != null)
{
if (_Collectiontd.Count() == 2)
{
string Feature= _Collectiontd[0].InnerText.Trim() +" " + _Collectiontd[1].InnerText.Trim();
if (Bullets.Length + Feature.Length + 2 <= PointCounter*500)
{
Bullets = Bullets + Feature + ". ";
}
else
{
PointCounter++;
Bullets = Bullets +"@@"+ Feature + ". ";
}
}
}
}
}
HtmlNodeCollection _ColectionBox = null;
_ColectionBox = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"prodtabs-9\"]/ul/li");
if (_ColectionBox == null)
_ColectionBox = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"prodtabs-9\"]/li");
if (_ColectionBox != null)
{
foreach (HtmlNode _NodeBox in _ColectionBox)
{
string Feature = _NodeBox.InnerText.Trim();
if (Feature.Length > 480)
{
Feature = Feature.Substring(0, 480);
}
if (Bullets.Length + Feature.Length + 2 <= PointCounter*500)
{
Bullets = Bullets + Feature+". ";
}
else
{
Bullets = Bullets + "@@" + Feature + ". ";
PointCounter++;
}
}
}
if (Bullets == "")
{
HtmlNodeCollection _Colectiondescli = null;
_Colectiondescli = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ProductOverviewContent\"]");
if (_Colectiondescli != null)
{
HtmlNodeCollection _Collectionul = _Colectiondescli[0].SelectNodes(".//ul");
if (_Collectionul != null)
{
HtmlNodeCollection _Collectionulli = _Collectionul[0].SelectNodes(".//li");
if (_Collectionulli != null)
{
foreach (HtmlNode _NodeBox in _Collectionulli)
{
string Feature = _NodeBox.InnerText.Trim() ;
if (Feature.Length > 480)
{
Feature = Feature.Substring(0, 480);
}
if (Bullets.Length + Feature.Length + 2 <= PointCounter*500)
{
Bullets = Bullets + Feature + ". ";
}
else
{
Bullets = Bullets + "@@" + Feature + ". ";
PointCounter++;
}
}
}
}
}
}
string[] BulletPoints=Bullets.Split(new string[] { "@@" }, StringSplitOptions.None);
for (int i = 0; i < BulletPoints.Length; i++)
{
if (i < 5)
{
if (BulletPoints[i].Trim().Length >= 500)
{
dataGridView1.Rows[index].Cells[i + 4].Value = (BulletPoints[i].Trim().Substring(0,490)+"...").Replace(",", " ");
}
else
{
dataGridView1.Rows[index].Cells[i + 4].Value = BulletPoints[i].Trim().Replace(",", " ");
}
}
}
#endregion Bullets
#region manufacturer
HtmlNodeCollection _manufacturer = _Work1doc.DocumentNode.SelectNodes("//meta[@itemprop=\"brand\"]");
if (_manufacturer == null)
{
dataGridView1.Rows[index].Cells[9].Value = BrandName1;
dataGridView1.Rows[index].Cells[10].Value = BrandName1;
}
else
{
string Brand = "";
foreach (HtmlAttribute _Att in _manufacturer[0].Attributes)
{
if (_Att.Name.ToLower() == "content")
{
Brand = _Att.Value.Trim();
}
}
if (Brand == "")
{
dataGridView1.Rows[index].Cells[9].Value = BrandName1;
dataGridView1.Rows[index].Cells[10].Value = BrandName1;
}
else
{
dataGridView1.Rows[index].Cells[9].Value = Brand;
dataGridView1.Rows[index].Cells[10].Value = Brand;
}
}
#endregion manufacturer
#region For decsription empty
try
{
if (dataGridView1.Rows[index].Cells[3].Value == null || dataGridView1.Rows[index].Cells[3].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[3].Value.ToString()))
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value.ToString().Replace(">", "").Replace("<", "");
}
}
catch
{
}
#endregion For decsription empty
#region currency
dataGridView1.Rows[index].Cells[12].Value = "CDN";
#endregion currency
#region price,stock
HtmlNodeCollection _Collectionstock = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"availability\"]");
if (_Collectionstock != null)
{
foreach (HtmlAttribute _Attribute in _Collectionstock[0].Attributes)
{
if (_Attribute.Name.ToLower() == "content")
{
if (_Attribute.Value.ToLower().Contains("instock"))
{
dataGridView1.Rows[index].Cells[13].Value = "5";
}
else
{
dataGridView1.Rows[index].Cells[13].Value = "0";
}
}
}
}
else
{
dataGridView1.Rows[index].Cells[13].Value = "0";
}
HtmlNodeCollection _NodePrice = _Work1doc.DocumentNode.SelectNodes("//meta[@itemprop=\"price\"]");
if (_NodePrice != null)
{
foreach (HtmlAttribute _Att in _NodePrice[0].Attributes)
{
if (_Att.Name.ToLower() == "content")
{
dataGridView1.Rows[index].Cells[11].Value = _Att.Value.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
}
}
if (dataGridView1.Rows[index].Cells[11].Value == null || dataGridView1.Rows[index].Cells[11].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[11].Value.ToString()))
{
dataGridView1.Rows[index].Cells[11].Value = "0";
}
#endregion price,stock
#region sku
HtmlNodeCollection _Collectionsku = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_Collectionsku != null)
{
dataGridView1.Rows[index].Cells[1].Value = "HEN"+_Collectionsku[0].InnerText.Trim();
}
#endregion sku
#region Image
string Images = "";
HtmlNodeCollection _Collectionimg = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"primaryimgcontainer\"]/a");
if (_Collectionimg != null)
{
foreach (HtmlAttribute _Node1 in _Collectionimg[0].Attributes)
{
if (_Node1.Name.ToLower() == "href")
{
if (!Images.Contains(_Node1.Value))
{
Images = Images + _Node1.Value + "@";
}
}
}
}
HtmlNodeCollection _Collectionimg2 = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"productimages\"]/li/a");
if (_Collectionimg2 != null)
{
foreach (HtmlNode _NodeImg in _Collectionimg2)
{
foreach (HtmlAttribute _Att in _NodeImg.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
if (!Images.Contains(_Att.Value))
{
Images = Images + _Att.Value + "@";
}
}
}
}
}
if (Images.Length > 0)
{
Images = Images.Substring(0, Images.Length - 1);
}
dataGridView1.Rows[index].Cells[14].Value = Images;
#endregion Image
#region Condition
if (Conditonwork1.ToLower().Trim() == "used")
{
dataGridView1.Rows[index].Cells[15].Value = "Like New";
}
else
{
HtmlNodeCollection _NodeCondition = _Work1doc.DocumentNode.SelectNodes("//meta[@itemprop=\"itemCondition\"]");
if (_NodeCondition != null)
{
foreach (HtmlAttribute _Att in _NodeCondition[0].Attributes)
{
if (_Att.Name.ToLower() == "content")
{
dataGridView1.Rows[index].Cells[15].Value = _Att.Value.Trim();
}
}
}
else
{
dataGridView1.Rows[index].Cells[15].Value = "New";
}
}
#endregion Condition
}
}
else
{
_writer.WriteLine(Url1);
}
}
else
{
}
}
#endregion henrys
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
#region henrys
if (_ISHenry)
{
if (_IsProduct)
{
string AvailabilkityText = "";
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]")[0].InnerText.ToLower().Contains("item only available for in store shopping"))
{
AvailabilkityText = "no";
}
}
if (_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"prodimgbuycontainer\"]") != null)
{
if (AvailabilkityText == "")
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[17].Value = Url2;
dataGridView1.Rows[index].Cells[16].Value = BrandName2;
#region title
HtmlNodeCollection _Title = _Work1doc2.DocumentNode.SelectNodes("//h2[@class=\"productTitle\"]");
if (_Title != null)
{
dataGridView1.Rows[index].Cells[2].Value = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("Henrys", "").Replace("Henry's", "").Replace("HENRY'S", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "");
}
else
{
HtmlNodeCollection _Title1 = _Work1doc2.DocumentNode.SelectNodes("//meta[@itemprop=\"name\"]");
if (_Title1 != null)
{
dataGridView1.Rows[index].Cells[2].Value = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("Henrys", "").Replace("Henry's", "").Replace("HENRY'S", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "");
}
}
#endregion title
#region description
_Description2 = "";
HtmlNodeCollection _description = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ProductOverviewContent\"]");
if (_description != null)
{
_Description2 = _description[0].InnerHtml.Replace("Product Description", "").Trim();
#region CodeToReMoveText
if (_Description2.Trim().Length > 0)
{
List<string> _Remove = new List<string>();
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ProductOverviewContent\"]")[0].ChildNodes)
{
if (_Node.InnerText.ToLower().Contains("special orders") || _Node.InnerText.ToLower().Contains("henry's") || _Node.InnerText.ToLower().Contains("stock is limited") || _Node.InnerText.ToLower().Contains("please note") || _Node.InnerText.ToLower().Contains("credit card"))
{
_Remove.Add(_Node.InnerHtml);
}
}
foreach (string _rem in _Remove)
{
_Description2 = _Description2.Replace(_rem, "");
}
}
#endregion CodeToReMoveText
_Description2 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_Description2).Trim());
}
else
{
}
try
{
if (_Description2.Length > 2000)
{
_Description2 = _Description2.Substring(0, 1997) + "...";
}
}
catch
{
}
string Desc = System.Net.WebUtility.HtmlDecode(_Description2.Replace("Â", "").Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("online only", "").Replace("Online Only", ""));
if (Desc.Trim() != "")
{
if (Desc.Substring(0, 1) == "\"")
{
dataGridView1.Rows[index].Cells[3].Value = Desc.Substring(1).Replace(","," ");
}
else
{
dataGridView1.Rows[index].Cells[3].Value = Desc.Replace(","," ");
}
}
#endregion description
#region Bullets
string Bullets = "";
int PointCounter = 1;
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"stockstatusProd stockText_red\"]")[0].InnerText.ToLower().Contains("special order"))
{
Bullets = "This is special Item.Estimated delivery 3-4 weeks (subject to availability). Please note that Special Order Items cannot be cancelled or returned." + Bullets;
}
}
HtmlNodeCollection _ColectionBullet = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"attributetablecontainer\"]/table[@class=\"attributetable\"]/tr");
if (_ColectionBullet != null)
{
foreach (HtmlNode _Node in _ColectionBullet)
{
HtmlNodeCollection _Collectiontd = _Node.SelectNodes(".//td");
if (_Collectiontd != null)
{
if (_Collectiontd.Count() == 2)
{
string Feature = _Collectiontd[0].InnerText.Trim() + " " + _Collectiontd[1].InnerText.Trim();
if (Bullets.Length + Feature.Length + 2 <=PointCounter* 500)
{
Bullets = Bullets + Feature + ". ";
}
else
{
PointCounter++;
Bullets = Bullets + "@@" + Feature + ". ";
}
}
}
}
}
HtmlNodeCollection _ColectionBox = null;
_ColectionBox = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"prodtabs-9\"]/ul/li");
if (_ColectionBox == null)
_ColectionBox = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"prodtabs-9\"]/li");
if (_ColectionBox != null)
{
foreach (HtmlNode _NodeBox in _ColectionBox)
{
string Feature = _NodeBox.InnerText.Trim();
if (Feature.Length > 480)
{
Feature = Feature.Substring(0, 480);
}
if (Bullets.Length + Feature.Length + 2 <= PointCounter*500)
{
Bullets = Bullets + Feature + ". ";
}
else
{
PointCounter++;
Bullets = Bullets + "@@" + Feature + ". ";
}
}
}
if (Bullets == "")
{
HtmlNodeCollection _Colectiondescli = null;
_Colectiondescli = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ProductOverviewContent\"]");
if (_Colectiondescli != null)
{
HtmlNodeCollection _Collectionul = _Colectiondescli[0].SelectNodes(".//ul");
if (_Collectionul != null)
{
HtmlNodeCollection _Collectionulli = _Collectionul[0].SelectNodes(".//li");
if (_Collectionulli != null)
{
foreach (HtmlNode _NodeBox in _Collectionulli)
{
string Feature = _NodeBox.InnerText.Trim();
if (Feature.Length > 480)
{
Feature = Feature.Substring(0, 480);
}
if (Bullets.Length + Feature.Length + 2 <= PointCounter*500)
{
Bullets = Bullets + Feature + ". ";
}
else
{
PointCounter++;
Bullets = Bullets + "@@" + Feature + ". ";
}
}
}
}
}
}
string[] BulletPoints = Bullets.Split(new string[] { "@@" }, StringSplitOptions.None);
for (int i = 0; i < BulletPoints.Length; i++)
{
if (i < 5)
{
if (BulletPoints[i].Trim().Length >= 500)
{
dataGridView1.Rows[index].Cells[i + 4].Value = (BulletPoints[i].Trim().Substring(0, 490) + "...").Replace(",", " ");
}
else
{
dataGridView1.Rows[index].Cells[i + 4].Value = BulletPoints[i].Trim().Replace(",", " ");
}
}
}
#endregion Bullets
#region manufacturer
HtmlNodeCollection _manufacturer = _Work1doc2.DocumentNode.SelectNodes("//meta[@itemprop=\"brand\"]");
if (_manufacturer == null)
{
dataGridView1.Rows[index].Cells[9].Value = BrandName2;
dataGridView1.Rows[index].Cells[10].Value = BrandName2;
}
else
{
string Brand = "";
foreach (HtmlAttribute _Att in _manufacturer[0].Attributes)
{
if (_Att.Name.ToLower() == "content")
{
Brand = _Att.Value.Trim();
}
}
if (Brand == "")
{
dataGridView1.Rows[index].Cells[9].Value = BrandName2;
dataGridView1.Rows[index].Cells[10].Value = BrandName2;
}
else
{
dataGridView1.Rows[index].Cells[9].Value = Brand;
dataGridView1.Rows[index].Cells[10].Value = Brand;
}
}
#endregion manufacturer
#region For decsription empty
try
{
if (dataGridView1.Rows[index].Cells[3].Value == null || dataGridView1.Rows[index].Cells[3].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[3].Value.ToString()))
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value.ToString().Replace(">", "").Replace("<", "");
}
}
catch
{
}
#endregion For decsription empty
#region currency
dataGridView1.Rows[index].Cells[12].Value = "CDN";
#endregion currency
#region price,stock
HtmlNodeCollection _Collectionstock = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"availability\"]");
if (_Collectionstock != null)
{
foreach (HtmlAttribute _Attribute in _Collectionstock[0].Attributes)
{
if (_Attribute.Name.ToLower() == "content")
{
if (_Attribute.Value.ToLower().Contains("instock"))
{
dataGridView1.Rows[index].Cells[13].Value = "5";
}
else
{
dataGridView1.Rows[index].Cells[13].Value = "0";
}
}
}
}
else
{
dataGridView1.Rows[index].Cells[13].Value = "0";
}
HtmlNodeCollection _NodePrice = _Work1doc2.DocumentNode.SelectNodes("//meta[@itemprop=\"price\"]");
if (_NodePrice != null)
{
foreach (HtmlAttribute _Att in _NodePrice[0].Attributes)
{
if (_Att.Name.ToLower() == "content")
{
dataGridView1.Rows[index].Cells[11].Value = _Att.Value.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
}
}
if (dataGridView1.Rows[index].Cells[11].Value == null || dataGridView1.Rows[index].Cells[11].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[11].Value.ToString()))
{
dataGridView1.Rows[index].Cells[11].Value = "0";
}
#endregion price,stock
#region sku
HtmlNodeCollection _Collectionsku = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_Collectionsku != null)
{
dataGridView1.Rows[index].Cells[1].Value = "HEN"+_Collectionsku[0].InnerText.Trim();
}
#endregion sku
#region Image
string Images = "";
HtmlNodeCollection _Collectionimg = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"primaryimgcontainer\"]/a");
if (_Collectionimg != null)
{
foreach (HtmlAttribute _Node1 in _Collectionimg[0].Attributes)
{
if (_Node1.Name.ToLower() == "href")
{
if (!Images.Contains(_Node1.Value))
{
Images = Images + _Node1.Value + "@";
}
}
}
}
HtmlNodeCollection _Collectionimg2 = _Work1doc2.DocumentNode.SelectNodes("//ul[@class=\"productimages\"]/li/a");
if (_Collectionimg2 != null)
{
foreach (HtmlNode _NodeImg in _Collectionimg2)
{
foreach (HtmlAttribute _Att in _NodeImg.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
if (!Images.Contains(_Att.Value))
{
Images = Images + _Att.Value + "@";
}
}
}
}
}
if (Images.Length > 0)
{
Images = Images.Substring(0, Images.Length - 1);
}
dataGridView1.Rows[index].Cells[14].Value = Images;
#endregion Image
#region Condition
if (Conditonwork2.ToLower().Trim() == "used")
{
dataGridView1.Rows[index].Cells[15].Value = "Like New";
}
else
{
HtmlNodeCollection _NodeCondition = _Work1doc2.DocumentNode.SelectNodes("//meta[@itemprop=\"itemCondition\"]");
if (_NodeCondition != null)
{
foreach (HtmlAttribute _Att in _NodeCondition[0].Attributes)
{
if (_Att.Name.ToLower() == "content")
{
dataGridView1.Rows[index].Cells[15].Value = _Att.Value.Trim();
}
}
}
else
{
dataGridView1.Rows[index].Cells[15].Value = "New";
}
}
#endregion Condition
}
}
else
{
_writer.WriteLine(Url2);
}
}
else
{
}
}
#endregion henrys
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename, decimal Price)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void _percent_Click(object sender, EventArgs e)
{
}
private void createcsvfile_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Go_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Pause_Click(object sender, EventArgs e)
{
}
private void totalrecord_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
/****************Code to select all check boxes*************/
/************Uncomment durng live**/
for (int i = 0; i < chkstorelist.Items.Count; i++)
{
chkstorelist.SetItemChecked(i, true);
}
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
DataGridViewColumn _Columns = new DataGridViewColumn();
_Columns.Name = "RowID";
_Columns.HeaderText = "RowID";
_Columns.DataPropertyName = "RowID";
_Columns.ValueType = Type.GetType("System.float");
_Columns.SortMode = DataGridViewColumnSortMode.Automatic;
DataGridViewCell cell = new DataGridViewLinkCell();
_Columns.CellTemplate = cell;
dataGridView1.Columns.Add(_Columns);
dataGridView1.Columns.Add("SKU", "SKU");
dataGridView1.Columns.Add("Product Name", "Product Name");
dataGridView1.Columns.Add("Product Description", "Product Description");
dataGridView1.Columns.Add("Bullet Points1", "Bullet Points1");
dataGridView1.Columns.Add("Bullet Points2", "Bullet Points2");
dataGridView1.Columns.Add("Bullet Points3", "Bullet Points3");
dataGridView1.Columns.Add("Bullet Points4", "Bullet Points4");
dataGridView1.Columns.Add("Bullet Points5", "Bullet Points5");
dataGridView1.Columns.Add("Manufacturer", "Manufacturer");
dataGridView1.Columns.Add("Brand Name", "Brand Name");
dataGridView1.Columns.Add("Price", "Price");
dataGridView1.Columns.Add("Currency", "Currency");
dataGridView1.Columns.Add("In Stock", "In Stock");
dataGridView1.Columns.Add("Image URL", "Image URL");
dataGridView1.Columns.Add("Condition", "Condition");
dataGridView1.Columns.Add("Category", "Category");
dataGridView1.Columns.Add("URL", "URL");
/****************BackGround worker *************************/
}
public void GenerateCSVFile()
{
string Filename = "data" + DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "");
DataTable exceldt = new DataTable();
exceldt.Columns.Add("Rowid", typeof(int));
exceldt.Columns.Add("SKU", typeof(string));
exceldt.Columns.Add("Product Name", typeof(string));
exceldt.Columns.Add("Product Description", typeof(string));
exceldt.Columns.Add("Bullet Points1", typeof(string));
exceldt.Columns.Add("Bullet Points2", typeof(string));
exceldt.Columns.Add("Bullet Points3", typeof(string));
exceldt.Columns.Add("Bullet Points4", typeof(string));
exceldt.Columns.Add("Bullet Points5", typeof(string));
exceldt.Columns.Add("Manufacturer", typeof(string));
exceldt.Columns.Add("Brand Name", typeof(string));
exceldt.Columns.Add("Price", typeof(string));
exceldt.Columns.Add("Currency", typeof(string));
exceldt.Columns.Add("In Stock", typeof(string));
exceldt.Columns.Add("Image URL", typeof(string));
exceldt.Columns.Add("Image URL1", typeof(string));
exceldt.Columns.Add("Image URL2", typeof(string));
exceldt.Columns.Add("Condition", typeof(string));
exceldt.Columns.Add("Category", typeof(string));
for (int m = 0; m < dataGridView1.Rows.Count - 1; m++)
{
exceldt.Rows.Add();
for (int n = 0; n < dataGridView1.Columns.Count - 1; n++)
{
if (dataGridView1.Rows[m].Cells[n].Value == null || dataGridView1.Rows[m].Cells[n].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[m].Cells[n].Value.ToString()))
continue;
if (n == 15)
{
exceldt.Rows[m][17] = dataGridView1.Rows[m].Cells[n].Value.ToString();
}
else if (n == 16)
{
exceldt.Rows[m][18] = dataGridView1.Rows[m].Cells[n].Value.ToString();
}
else if (n == 14)
{
string[] Images = dataGridView1.Rows[m].Cells[n].Value.ToString().Split('@');
try
{
exceldt.Rows[m][n] = Images[0];
}
catch
{
}
if (Images.Length > 1)
{
try
{
exceldt.Rows[m][n + 1] = Images[1];
}
catch
{
}
try
{
exceldt.Rows[m][n + 2] = Images[2];
}
catch
{
}
}
}
else
{
exceldt.Rows[m][n] = dataGridView1.Rows[m].Cells[n].Value.ToString();
}
}
}
try
{
using (CsvFileWriter writer = new CsvFileWriter(Application.StartupPath + "/" + Filename + ".txt"))
{
CsvFileWriter.CsvRow row = new CsvFileWriter.CsvRow();//HEADER FOR CSV FILE
row.Add("SKU");
row.Add("Product Name");
row.Add("Product Description");
row.Add("Bullet Points1");
row.Add("Bullet Points2");
row.Add("Bullet Points3");
row.Add("Bullet Points4");
row.Add("Bullet Points5");
row.Add("Manufacturer");
row.Add("Brand Name");
row.Add("Price");
row.Add("Currency");
row.Add("In Stock");
row.Add("Image URL");
row.Add("Image URL1");
row.Add("Image URL2");
row.Add("Condition");
row.Add("Category");
writer.WriteRow(row);//INSERT TO CSV FILE HEADER
List<string> Skus = new System.Collections.Generic.List<string>();
DataTable _TableProceSort = (from dTable in
exceldt.AsEnumerable()
where Convert.ToDecimal(dTable["Price"]) > 0
orderby Convert.ToDecimal(dTable["Price"]) descending
select dTable).CopyToDataTable();
for (int m = 0; m < _TableProceSort.Rows.Count; m++)
{
try
{
if (_TableProceSort.Rows[m]["SKU"].ToString().Trim() != "")
{
if (!Skus.Contains(_TableProceSort.Rows[m]["SKU"].ToString()) && !_TableProceSort.Rows[m]["Product Name"].ToString().ToLower().Contains("in-store only") && !_TableProceSort.Rows[m]["Product Name"].ToString().ToLower().Contains("in-store items") && !_TableProceSort.Rows[m]["Product Description"].ToString().ToLower().Contains("in-store only") && !_TableProceSort.Rows[m]["Product Description"].ToString().ToLower().Contains("in-store items"))
{
Skus.Add(_TableProceSort.Rows[m]["SKU"].ToString());
CsvFileWriter.CsvRow row1 = new CsvFileWriter.CsvRow();
for (int n = 1; n < _TableProceSort.Columns.Count; n++)
{
row1.Add(String.Format("{0}", _TableProceSort.Rows[m][n].ToString().Replace("\n", "").Replace("\r", "").Replace("\t", "")));
}
writer.WriteRow(row1);
}
else
{
}
}
else
{
}
}
catch
{
}
}
}
System.Diagnostics.Process.Start(Application.StartupPath + "/" + Filename + ".txt");//OPEN THE CSV FILE ,,CSV FILE NAMED AS DATA.CSV
}
catch (Exception) { MessageBox.Show("file is already open\nclose the file"); }
return;
}
public class CsvFileWriter : StreamWriter //Writing data to CSV
{
public CsvFileWriter(Stream stream)
: base(stream)
{
}
public CsvFileWriter(string filename)
: base(filename)
{
}
public class CsvRow : List<string> //Making each CSV rows
{
public string LineText { get; set; }
}
public void WriteRow(CsvRow row)
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in row)
{
builder.Append(value.Replace("\n", "") + "\t");
}
row.LineText = builder.ToString();
WriteLine(row.LineText);
}
}
private void btnsubmit_Click(object sender, System.EventArgs e)
{
Process();
}
private void Form1_Shown(object sender, System.EventArgs e)
{
}
}
}
<file_sep>/Project factorydirect/palyerborndate/palyerborndate/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using bestbuy;
using System.Text.RegularExpressions;
using System.Net;
using WatiN.Core;
namespace palyerborndate
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region booltypevariable
bool _IsProduct = false;
bool _IsCategory = true;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
#endregion booltypevariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
#endregion Buinesslayervariable
#region intypevariable
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
#endregion intypevariable
#region IeVariable
IE _Worker1 = null;
IE _Worker2 = null;
#endregion IeVariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "";
string Category = "";
decimal Weight = 0;
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _ProductUrl = new List<string>();
List<string> _Name = new List<string>();
List<string> CategoryUrl = new List<string>();
Dictionary<string, string> Producturl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
ExtendedWebClient _Client2 = new ExtendedWebClient();
ExtendedWebClient _Client1 = new ExtendedWebClient();
ExtendedWebClient _Client3 = new ExtendedWebClient();
ExtendedWebClient _Client4 = new ExtendedWebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
StreamWriter writer = new StreamWriter(Application.StartupPath + "/log.txt");
#endregion htmlagility
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void Form1_Load(object sender, EventArgs e)
{
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
/****************BackGround worker *************************/
}
public void tim(int t)
{
time = 0;
timer1.Start();
try
{
while (time <= t)
{
Application.DoEvents();
}
}
catch (Exception) { }
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
time++;
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public void GetCategoryInfo(HtmlAgilityPack.HtmlDocument _doc, string url)
{
HtmlNodeCollection Collection = _doc.DocumentNode.SelectNodes("//div[@class=\"nxt-product-details\"]//div[@class=\"nxt-product-name\"]//a");
if (Collection != null)
{
foreach (HtmlNode node in Collection)
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "href")
{
if (!Producturl.Keys.Contains(attr.Value.ToLower()))
{
try
{
Producturl.Add(attr.Value.ToLower(), "");
}
catch
{
}
}
}
}
}
}
else
WriteLogEvent(url, "ctl00_CC_ProductSearchResultListing_SearchProductListing tag is not found");
}
public void GetProductInfo(HtmlAgilityPack.HtmlDocument _doc, string url)
{
BusinessLayer.Product product = new BusinessLayer.Product();
try
{
#region title
if (_doc.DocumentNode.SelectNodes("//h1[@class=\"productDescLarge\"]") != null)
product.Name = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//h1[@class=\"productDescLarge\"]")[0].InnerText.Trim());
else
WriteLogEvent(url, "title not found");
#endregion title
#region price
if (_doc.DocumentNode.SelectNodes("//span[@class=\"productPriceLarge\"]") != null)
product.Price = _doc.DocumentNode.SelectNodes("//span[@class=\"productPriceLarge\"]")[0].InnerText.Replace("$", "").Trim();
else
{
product.Price = "0";
WriteLogEvent(url, "Price not found");
}
#endregion price
#region Brand
try
{
if (product.Name.Length > 0)
{
product.Brand = product.Name.Substring(0, product.Name.IndexOf(' '));
product.Manufacturer = product.Name.Substring(0, product.Name.IndexOf(' '));
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "JZ HOLDINGS";
}
else
{
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "JZ HOLDINGS";
}
}
catch
{
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "JZ HOLDINGS";
}
#endregion Brand
#region Category
if (_doc.DocumentNode.SelectNodes("//a[@id=\"ctl00_MainBodyContent_lnkMoreCatetory\"]") != null)
{
try
{
string Category = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//a[@id=\"ctl00_MainBodyContent_lnkMoreCatetory\"]")[0].InnerText);
if (Category.Contains("->"))
Category = Category.Split(new string[] { "->" }, StringSplitOptions.RemoveEmptyEntries)[0];
product.Category ="FDCA"+ Category.Trim();
}
catch
{ WriteLogEvent(url, "Category not found"); }
}
else
WriteLogEvent(url, "Category not found");
#endregion Category
product.Currency = "CAD";
#region description
string Description = "";
var allElementsWithClassFloat = _doc.DocumentNode.SelectNodes("//span[@id=\"ctl00_MainBodyContent_lblSpecification\"]");
if (allElementsWithClassFloat != null)
{
foreach (HtmlNode node in allElementsWithClassFloat)
{
Description = Description + " " + node.InnerText.Trim();
}
Description = Removeunsuaalcharcterfromstring(StripHTML(Description).Trim());
try
{
if (Description.Length > 2000)
Description = Description.Substring(0, 1997) + "...";
}
catch
{
}
product.Description = System.Net.WebUtility.HtmlDecode(Description.Replace("Â", "")).Replace("factorydirect.ca", "");
}
else
WriteLogEvent(url, "Description not found");
#endregion description
#region BulletPoints
string Feature = "";
string Bullets = "";
HtmlNodeCollection collection = _doc.DocumentNode.SelectNodes("//span[@id=\"ctl00_MainBodyContent_lblSpecification\"]");
if (collection != null)
{
int PointCounter = 1;
foreach (HtmlNode node in collection)
{
try
{
Feature = node.InnerText;
if (Feature.Length > 480)
Feature = Feature.Substring(0, 480);
if (Bullets.Length + Feature.Length + 2 <= PointCounter * 480)
Bullets = Bullets + Feature + ". ";
else
{
Bullets = Bullets + "@@" + Feature + ". ";
PointCounter++;
}
}
catch { }
}
if (!string.IsNullOrEmpty(Bullets))
Bullets = Bullets.Trim().Replace("factorydirect.ca", "");
}
else
WriteLogEvent(url, "BulletPoints not found");
if (Bullets.Length > 0)
{
Bullets = Removeunsuaalcharcterfromstring(StripHTML(Bullets).Trim());
string[] BulletPoints = Bullets.Split(new string[] { "@@" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < BulletPoints.Length; i++)
{
if (i == 0)
product.Bulletpoints1 = BulletPoints[i].ToString();
if (i == 1)
product.Bulletpoints2 = BulletPoints[i].ToString();
if (i == 2)
product.Bulletpoints3 = BulletPoints[i].ToString();
if (i == 3)
product.Bulletpoints4 = BulletPoints[i].ToString();
if (i == 4)
product.Bulletpoints5 = BulletPoints[i].ToString();
}
}
if (string.IsNullOrEmpty(product.Description))
{
product.Description = product.Name;
if (string.IsNullOrEmpty(product.Bulletpoints1))
product.Bulletpoints1 = product.Name;
}
else if (string.IsNullOrEmpty(product.Bulletpoints1))
{
if (product.Description.Length >= 500)
product.Bulletpoints1 = product.Description.Substring(0, 497);
else
product.Bulletpoints1 = product.Description;
}
#endregion BulletPoints
#region Image
string Images = "";
if (_doc.DocumentNode.SelectNodes("//a[@id=\"ctl00_MainBodyContent_ProductImageHyperLink\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//a[@id=\"ctl00_MainBodyContent_ProductImageHyperLink\"]")[0].Attributes)
{
if (attr.Name == "href")
Images = attr.Value.Trim();
}
}
else if (_doc.DocumentNode.SelectNodes("//img[@id=\"ctl00_MainBodyContent_imgProduct\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//img[@id=\"ctl00_MainBodyContent_imgProduct\"]")[0].Attributes)
{
if (attr.Name == "src")
Images = attr.Value.Trim();
}
}
else
WriteLogEvent(url, "Main Images not found");
product.Image = Images;
#endregion Image
#region sku
if (_doc.DocumentNode.SelectNodes("//span[@id=\"ctl00_MainBodyContent_lblProductCode\"]") != null)
{
product.SKU = "FDCA" + _doc.DocumentNode.SelectNodes("//span[@id=\"ctl00_MainBodyContent_lblProductCode\"]")[0].InnerText.Trim();
product.parentsku = "FDCA" + _doc.DocumentNode.SelectNodes("//span[@id=\"ctl00_MainBodyContent_lblProductCode\"]")[0].InnerText.Trim();
}
#endregion sku
product.Isparent = true;
product.Stock = "0";
if (_doc.DocumentNode.SelectNodes("//input[@id=\"ctl00_MainBodyContent_btnAdd\"]") != null)
product.Stock = "1";
product.URL = url;
if (product.Brand.ToUpper() != "SOLOGEAR")
Products.Add(product);
}
catch
{ }
}
public string GetUPC(string Response)
{
string Result = "";
foreach (var ch in Response.ToCharArray())
{
if (char.IsNumber(ch))
Result = Result + ch;
else
break;
}
Int64 n;
bool isNumeric = Int64.TryParse(Result, out n);
if (n != 0)
return Result;
else
return "";
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public void WriteLogEvent(string url, string Detail)
{
writer.WriteLine(Detail + "/t" + url);
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
int checkcounter = 0;
if (_IsProduct)
{
do
{
try
{
counterReload++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
}
else
{
do
{
try
{
counterReload++;
_Worker1.GoTo(Url1);
_Iserror = false;
_Worker1.WaitForComplete();
if (_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"nxt-product-list\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"nxt-product-list\"")) && checkcounter < 10000);
}
_Work1doc.LoadHtml(_Worker1.Html);
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
}
if (_Iserror)
WriteLogEvent(Url1, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc, Url1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading produts from category page"); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / CategoryUrl.Count));
/****************end*******************/
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc, Url1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading product Info."); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / Producturl.Count));
/****************end*******************/
}
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int checkcounter = 0;
int counterReload = 0;
if (_IsProduct)
{
do
{
try
{
counterReload++;
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
}
else
{
do
{
try
{
counterReload++;
_Worker2.GoTo(Url2);
_Iserror = false;
_Worker2.WaitForComplete();
if (_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"nxt-product-list\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"nxt-product-list\"")) && checkcounter < 10000);
}
_Work1doc2.LoadHtml(_Worker2.Html);
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
}
if (_Iserror)
WriteLogEvent(Url2, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc2, Url2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading produts from category page"); }
gridindex++;
_Work1.ReportProgress((gridindex * 100 / CategoryUrl.Count));
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc2, Url2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading product Info."); }
gridindex++;
_Work1.ReportProgress((gridindex * 100 / Producturl.Count));
}
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
private void Go_Click(object sender, EventArgs e)
{
_IsProduct = false;
_percent.Visible = false;
_Bar1.Value = 0;
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
_Worker1 = new IE();
_Worker2 = new IE();
#region Factory.ca
_ScrapeUrl = "http://www.factorydirect.ca/SearchResults.aspx";
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category Link for factorydirect.ca Website";
int counterReload = 0;
bool isError = false;
_Worker1.GoTo(_ScrapeUrl);
_Worker1.WaitForComplete();
System.Threading.Thread.Sleep(10000);
_Work1doc.LoadHtml(_Worker1.Html);
HtmlNodeCollection _CollectionCatLink = _Work1doc.DocumentNode.SelectNodes("//b[@class=\"nxt-result-total\"]");
if (_CollectionCatLink != null)
{
try
{
_TotalRecords = Convert.ToInt32(_CollectionCatLink[0].InnerText.Trim());
if ((_TotalRecords % 36) == 0)
{
_Pages = Convert.ToInt32(_TotalRecords / 36);
}
else
{
_Pages = Convert.ToInt32(_TotalRecords / 36) + 1;
}
}
catch
{ }
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (_TotalRecords > 0)
{
gridindex = 0;
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read products from search page.";
_Stop = false;
time = 0;
_IsCategory = true;
tim(3);
totalrecord.Visible = true;
for (int Page = 1; Page <= _Pages; Page++)
{
CategoryUrl.Add("http://www.factorydirect.ca/SearchResults.aspx#/?search_return=all&res_per_page=36&page=" + Page);
}
totalrecord.Text = "Total No Pages :" + CategoryUrl.Count.ToString();
foreach (string url in CategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url;
_Work.RunWorkerAsync();
}
else
{
Url2 = url;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product info.";
_IsCategory = false;
_IsProduct = true;
gridindex = 0;
totalrecord.Text = "Total No Products :" + Producturl.Count.ToString();
foreach (var url in Producturl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key;
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#region InsertScrappedProductInDatabase
if (Products.Count() > 0)
{
_Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
_Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);
_Mail.SendMail("OOPS there is no any product scrapped by app for factorydirect.ca Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#endregion InsertScrappedProductInDatabase
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website";
/****************Email****************/
_Mail.SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
/*******************End********/
}
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website";
/****************Email****************/
_Mail.SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
/*******************End********/
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data factorydirect.ca Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
# endregion Factory.CA
writer.Close();
try { _Worker1.Close(); _Worker2.Close(); }
catch
{
}
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Form1_Shown(object sender, EventArgs e)
{
base.Show();
this.Go_Click(null, null);
}
}
public class ExtendedWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = 120000;
return w;
}
}
}
<file_sep>/Project 1/palyerborndate/palyerborndate/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
namespace palyerborndate
{
public partial class Form1 : Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region booltypevariable
bool _ISWarrior = false;
bool _ISchilychiles = false;
bool _Isreadywebbrowser1 = false;
bool _Isreadywebbrowser2 = false;
bool _IsProduct = false;
bool _IsAirsoft = false;
bool _IsKnifezone = false;
bool _IsCategory = true;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
#endregion booltypevariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
#endregion Buinesslayervariable
#region intypevariable
int _Chillyindex = 0;
int _Workindex = 0;
int _WorkIndex1 = 0;
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&keyword=keywords&search_in_description=1&product_type=&kfi_blade_length_from=0&kfi_blade_length_to=15&kfi_overall_length_from=0&kfi_overall_length_to=30&kfi_serration=ANY&kfi_is_coated=ANY&kfo_blade_length_from=0&kfo_blade_length_to=8&kfo_overall_length_from=0&kfo_overall_length_to=20&kfo_serration=ANY&kfo_is_coated=ANY&kfo_assisted=ANY&kk_blade_length_from=0&kk_blade_length_to=15&fl_lumens_from=0&fl_lumens_to=18000&fl_num_cells_from=1&fl_num_cells_to=10&fl_num_modes_from=1&fl_num_modes_to=15&sw_blade_length_from=0&sw_blade_length_to=60&sw_overall_length_from=0&sw_overall_length_to=70&inc_subcat=1&pfrom=0.01&pto=10000.00&x=36&y=6&perPage=60";
string Bullets = "";
string _Description1 = "";
string _Description2 = "";
string Category = "";
decimal Weight = 0;
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
List<string> _ProductUrl = new List<string>();
List<string> _Name = new List<string>();
List<string> CategoryUrl = new List<string>();
List<string> SubCategoryUrl = new List<string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
DataTable _Tbale = new DataTable();
List<string> RestrictedBrands = new List<string>();
public Form1()
{
RestrictedBrands.Add("5.11");
RestrictedBrands.Add("Benchmade");
RestrictedBrands.Add("Boston Leather");
RestrictedBrands.Add("<NAME>");
RestrictedBrands.Add("ESEE");
RestrictedBrands.Add("Exotac");
RestrictedBrands.Add("Foursevens");
RestrictedBrands.Add("Leatherman");
RestrictedBrands.Add("Luminox");
RestrictedBrands.Add("Maxpedition");
RestrictedBrands.Add("Medford");
RestrictedBrands.Add("Olight");
RestrictedBrands.Add("Surefire");
RestrictedBrands.Add("Shun Kitchen");
RestrictedBrands.Add("Vargo");
RestrictedBrands.Add("<NAME>");
RestrictedBrands.Add("Zero Tolerance");
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void Form1_Load(object sender, EventArgs e)
{
/****************Code to select all check boxes*************/
chkstorelist.SetItemChecked(0, true);
/************For All stores***********************/
//for (int i = 0; i < chkstorelist.Items.Count; i++)
//{
// chkstorelist.SetItemChecked(i, true);
//}
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
createcsvfile.Enabled = false;
_percent.Visible = false;
createcsvfile.Enabled = false;
Pause.Enabled = false;
dataGridView1.Columns.Add("RowID", "RowID");
dataGridView1.Columns.Add("SKU", "SKU");
dataGridView1.Columns.Add("Product Name", "Product Name");
dataGridView1.Columns.Add("Product Description", "Product Description");
dataGridView1.Columns.Add("Bullet Points", "Bullet Points");
dataGridView1.Columns.Add("Manufacturer", "Manufacturer");
dataGridView1.Columns.Add("Brand Name", "Brand Name");
dataGridView1.Columns.Add("Price", "Price");
dataGridView1.Columns.Add("Currency", "Currency");
dataGridView1.Columns.Add("In Stock", "In Stock");
dataGridView1.Columns.Add("Image URL", "Image URL");
dataGridView1.Columns.Add("URL", "URL");
dataGridView1.Columns.Add("Size", "Size");
dataGridView1.Columns.Add("Color", "Color");
dataGridView1.Columns.Add("Isdefault", "Isdefault");
dataGridView1.Columns.Add("ParentSku", "ParentSku");
dataGridView1.Columns.Add("BullPoint1", "BullPoint1");
dataGridView1.Columns.Add("BullPoint2", "BullPoint2");
dataGridView1.Columns.Add("BullPoint3", "BullPoint3");
dataGridView1.Columns.Add("BullPoint4", "BullPoint4");
dataGridView1.Columns.Add("BullPoint5", "BullPoint5");
dataGridView1.Columns.Add("Category", "Category");
dataGridView1.Columns.Add("Weight", "Weight");
dataGridView1.Columns.Add("Style", "Style");
dataGridView1.Columns.Add("Shipping", "Shipping");
/****************BackGround worker *************************/
}
public void tim(int t)
{
time = 0;
timer1.Start();
try
{
while (time <= t)
{
Application.DoEvents();
}
}
catch (Exception) { }
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
time++;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public void Disableallstores()
{
_ISWarrior = false;
_Iscompleted = false;
_ISchilychiles = false;
_IsAirsoft = false;
_IsKnifezone = false;
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
try
{
if (!_IsProduct)
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
}
}
catch
{
_Iserror = true;
}
int index = 0;
#region warrior
if (_ISWarrior)
{
if (_IsCategory)
{
index = gridindex;
gridindex++;
try
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//table[@id=\"catTable\"]//tr");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
if (_Node.Attributes[0].Value.ToLower() == "productlisting-odd" || _Node.Attributes[0].Value.ToLower() == "productlisting-even")
{
BusinessLayer.Product Product = new BusinessLayer.Product();
Product.Currency = "CDN";
HtmlNodeCollection _Collection1 = _Node.SelectNodes("td");
if (_Collection1 != null)
{
/***************Sku**************/
try
{
Product.SKU = "WAW" + _Collection1[0].InnerText;
}
catch
{
}
/************End*****************/
/***************product name**************/
try
{
string test = _Collection1[3].SelectNodes("h3")[0].InnerText;
Product.Name = _Collection1[3].SelectNodes("h3")[0].InnerText;
}
catch
{
}
/************manufacturer*****************/
try
{
Product.Manufacturer = _Collection1[1].InnerText;
Product.Brand = _Collection1[1].InnerText;
}
catch
{
}
/***************Price**************/
try
{
string Price = "";
if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]")[0].InnerText;
}
else if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]")[0].InnerText;
}
else
{
try
{
Price = _Collection1[4].SelectNodes("span[@class=\"product_list_price\"]")[0].InnerText;
}
catch
{
}
}
Price = Price.Replace("$", "");
Price = Price.ToLower().Replace("price", "").Replace("cdn", "").Trim();
Product.Price = Price;
}
catch
{
}
/***************End******************/
/***************In stock**************/
try
{
if (_Collection1[4].InnerText.ToLower().Contains("out of stock"))
{
Product.Stock = "0";
}
else
{
Product.Stock = "1";
}
}
catch
{
}
/**************Image****************/
try
{
if (_Collection1[2].SelectNodes("a//img") != null)
{
Product.Image = "http://www.warriorsandwonders.com/" + _Collection1[2].SelectNodes("a//img")[0].Attributes[0].Value;
}
}
catch
{
}
/****************End*****************/
/**************Link**************/
try
{
if (_Collection1[2].SelectNodes("a") != null)
{
Product.URL = _Collection1[2].SelectNodes("a")[0].Attributes[0].Value;
}
}
catch
{
}
/*****************End*************/
}
var restricted = (from brand in RestrictedBrands
where Product.Brand.Contains(brand)
select brand).ToList();
Product.Isparent = true;
Product.parentsku = Product.SKU;
if (restricted.Count() == 0)
Products.Add(Product);
}
}
/***********Sku**************/
/**************End*************/
}
}
catch
{
}
/**********Report progress**************/
_Work.ReportProgress((gridindex * 100 / _Pages));
/****************end*******************/
}
else
{
index = gridindex;
gridindex++;
try
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productDescription\"]");
if (_Collection != null)
{
_Description1 = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productDescription\"]")[0].InnerHtml;
try
{
List<string> _Remove = new List<string>();
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productDescription\"]")[0].ChildNodes)
{
if (_Node.InnerText.ToLower().Contains("price:") || _Node.InnerText.ToLower().Contains("msrp:"))
{
_Remove.Add(_Node.InnerHtml);
}
}
foreach (string _rem in _Remove)
{
_Description1 = _Description1.Replace(_rem, "");
}
}
catch
{
}
}
}
catch
{
_Description1 = "";
}
_Description1 = StripHTML(_Description1);
if (_Description1.Length > 2000)
_Description1 = _Description1.Substring(0, 1997) + "...";
try
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@id=\"productDetailsList\"]");
if (_Collection != null)
{
Bullets = StripHTML(_Work1doc.DocumentNode.SelectNodes("//ul[@id=\"productDetailsList\"]")[0].InnerHtml);
if (Bullets.Length > 500)
Bullets = Bullets.Substring(0, 497) + "...";
}
}
catch
{
Bullets = "";
}
#region Category
HtmlNodeCollection _Collectioncategory = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"navBreadCrumb\"]/a");
if (_Collectioncategory != null)
{
foreach (HtmlNode _NodeCategory in _Collectioncategory)
{
if (_NodeCategory.InnerText.Trim().ToLower() != "home")
{
Category = "WAW" + _NodeCategory.InnerText.Trim();
break;
}
}
}
#endregion Category
#region Weight
HtmlNodeCollection _CollectionWeight = _Work1doc.DocumentNode.SelectNodes("//table[@class=\"specs\"]/td");
if (_CollectionWeight != null)
{
bool Isweight = false;
foreach (HtmlNode _Nodeweight in _CollectionWeight)
{
if (_Nodeweight.InnerText.Trim().ToLower() == "weight")
Isweight = true;
if (Isweight)
{
string WeightText = _Nodeweight.InnerText.ToLower();
if (WeightText.Contains("oz"))
{
WeightText = WeightText.Substring(0, WeightText.IndexOf("oz")).Trim();
if (Decimal.TryParse(WeightText, out Weight))
{
}
}
break;
}
}
}
#endregion Weight
_Iscompleted = true;
if (_Iserror)
{
_Description1 = "";
Bullets = "";
Category = "";
Weight = 0;
}
_Work.ReportProgress((gridindex * 100 / Products.Count));
}
}
#endregion warrior
#region chilly
else if (_ISchilychiles)
{
if (_IsCategory)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"content\"]/div/div/a");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
foreach (HtmlAttribute _Attr in _Node.Attributes)
{
if (_Attr.Name.ToLower() == "href")
{
_ProductUrl.Add("http://chillychiles.com/" + _Attr.Value);
}
}
}
}
_Chillyindex++;
_Work.ReportProgress((_Chillyindex * 100 / _Pages));
}
else
{
_Chillyindex++;
_Work.ReportProgress((_Chillyindex * 100 / _ProductUrl.Count()));
}
}
#endregion chilly
#region aircraft
else if (_IsAirsoft)
{
#region cat
if (_Issubcat)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"catStaticContentLeft\"]") != null)
{
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//div[@id=\"catStaticContentLeft\"]/a"))
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name == "href")
{
if (!SubCategoryUrl.Contains(_Att.Value))
{
if (_Att.Value.Contains("?"))
{
string suburl = _Att.Value.Substring(0, _Att.Value.IndexOf("?"));
_Work1doc3.LoadHtml(_Client3.DownloadString(suburl + "?limit=12"));
if (_Work1doc3.DocumentNode.SelectNodes("//div[@class=\"catToolbarLeft\"]") != null)
{
try
{
int TotalRecords = 0;
int TotalPages = 0;
string Paging = _Work1doc3.DocumentNode.SelectNodes("//div[@class=\"catToolbarLeft\"]")[0].InnerText;
if (Paging.Contains("of"))
{
TotalRecords = Convert.ToInt32(Paging.Substring(Paging.IndexOf("of") + 2).Replace("/t", "").Replace("/t", "").Trim());
if (TotalRecords % 12 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 12);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 12) + 1;
}
for (int i = 1; i <= TotalPages; i++)
{
SubCategoryUrl.Add(suburl + "?limit=12&p=" + i);
}
}
else
{
SubCategoryUrl.Add(suburl + "?limit=all");
}
}
catch
{
SubCategoryUrl.Add(suburl + "?limit=all");
}
}
else
{
SubCategoryUrl.Add(suburl + "?limit=all");
}
}
else
{
_Work1doc3.LoadHtml(_Client3.DownloadString(_Att.Value + "?limit=12"));
if (_Work1doc3.DocumentNode.SelectNodes("//div[@class=\"catToolbarLeft\"]") != null)
{
try
{
int TotalRecords = 0;
int TotalPages = 0;
string Paging = _Work1doc3.DocumentNode.SelectNodes("//div[@class=\"catToolbarLeft\"]")[0].InnerText;
if (Paging.Contains("of"))
{
TotalRecords = Convert.ToInt32(Paging.Substring(Paging.IndexOf("of") + 2).Replace("/t", "").Replace("/t", "").Trim());
if (TotalRecords % 12 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 12);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 12) + 1;
}
for (int i = 1; i <= TotalPages; i++)
{
SubCategoryUrl.Add(_Att.Value + "?limit=12&p=" + i);
}
}
else
{
SubCategoryUrl.Add(_Att.Value + "?limit=all");
}
}
catch
{
SubCategoryUrl.Add(_Att.Value + "?limit=all");
}
}
else
{
SubCategoryUrl.Add(_Att.Value + "?limit=all");
}
}
}
}
}
}
}
else
{
string suburl = Url1;
if (Url1.Contains("?"))
suburl = suburl.Substring(0, suburl.IndexOf("?"));
_Work1doc3.LoadHtml(_Client3.DownloadString(suburl + "?limit=12"));
if (_Work1doc3.DocumentNode.SelectNodes("//div[@class=\"catToolbarLeft\"]") != null)
{
try
{
int TotalRecords = 0;
int TotalPages = 0;
string Paging = _Work1doc3.DocumentNode.SelectNodes("//div[@class=\"catToolbarLeft\"]")[0].InnerText;
if (Paging.Contains("of"))
{
TotalRecords = Convert.ToInt32(Paging.Substring(Paging.IndexOf("of") + 2).Replace("/t", "").Replace("/t", "").Trim());
if (TotalRecords % 12 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 12);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 12) + 1;
}
for (int i = 1; i <= TotalPages; i++)
{
SubCategoryUrl.Add(suburl + "?limit=12&p=" + i);
}
}
else
{
SubCategoryUrl.Add(suburl + "?limit=all");
}
}
catch
{
SubCategoryUrl.Add(suburl + "?limit=all");
}
}
else
{
SubCategoryUrl.Add(suburl + "?limit=all");
}
}
_Chillyindex++;
_Work.ReportProgress((_Chillyindex * 100 / CategoryUrl.Count()));
}
#endregion cat
#region subcat
else if (_IsCategory)
{
if (_Work1doc.DocumentNode.SelectNodes("//a[@class=\"product-image\"]") != null)
{
string _Url = "";
bool _IsproductOurl = false;
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//a[@class=\"product-image\"]"))
{
_IsproductOurl = false;
_Url = "";
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
_Url = _Att.Value;
}
else if (_Att.Name.ToLower() == "class" && _Att.Value == "product-image")
{
_IsproductOurl = true;
}
else if (_Att.Name.ToLower() == "title")
{
if (_Name.Contains(_Att.Value))
{
_IsproductOurl = false;
}
else
{
_Name.Add(_Att.Value);
}
}
}
if (_IsproductOurl)
{
if (!_ProductUrl.Contains(_Url))
{
_ProductUrl.Add(_Url);
}
}
}
}
_Chillyindex++;
_Work.ReportProgress((_Chillyindex * 100 / SubCategoryUrl.Count()));
}
#endregion subcat
else
{
_Chillyindex++;
_Work.ReportProgress((_Chillyindex * 100 / _ProductUrl.Count()));
}
}
#endregion aircraft
#region Knife
else if (_IsKnifezone)
{
if (_IsCategory)
{
bool Confirm = true;
while (Confirm)
{
Confirm = false;
if (_Work1doc.DocumentNode.SelectNodes("//font[@size=\"+1\"]") != null)
{
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//font[@size=\"+1\"]/a"))
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
if (!_Name.Contains(_Att.Value.Replace("../", "")))
{
_Name.Add(_Att.Value.Replace("../", ""));
_ProductUrl.Add("http://www.knifezone.ca/" + _Att.Value.Replace("../", ""));
}
}
}
}
}
if (_Work1doc.DocumentNode.SelectNodes("//img") != null)
{
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//img"))
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "alt")
{
try
{
if (_Att.Value == "next")
{
HtmlNode _Node2 = _Node.ParentNode;
foreach (HtmlAttribute _Att1 in _Node2.Attributes)
{
if (_Att1.Name.ToLower() == "href")
{
string _Url = Reverse(Url1);
_Url = _Url.Substring(_Url.IndexOf("/"));
_Url = Reverse(_Url);
if (!SubCategoryUrl.Contains(_Url + _Att1.Value))
{
SubCategoryUrl.Add(_Url + _Att1.Value);
_Work1doc.LoadHtml(_Client1.DownloadString(_Url + _Att1.Value));
Confirm = true;
}
}
}
}
}
catch
{
}
}
}
}
}
}
_Chillyindex++;
_Work.ReportProgress((_Chillyindex * 100 / CategoryUrl.Count()));
}
else
{
_Chillyindex++;
_Work.ReportProgress((_Chillyindex * 100 / _ProductUrl.Count()));
}
}
#endregion knife
//#region liveoutthere
//else if (_IsLiveoutthere)
//{
// #region category
// if (_IsCategory)
// {
// try
// {
// if (_Work1doc.DocumentNode.SelectNodes("//span[@class=\"color--orange plp-h1-count\"]") != null)
// {
// int pages = 0;
// int Noofproducts = Convert.ToInt32(_Work1doc.DocumentNode.SelectNodes("//span[@class=\"color--orange plp-h1-count\"]")[0].InnerText.ToLower().Replace("products", "").Trim().Replace(",", ""));
// if (Noofproducts % 500 == 0)
// {
// pages = Convert.ToInt32(Noofproducts / 500);
// }
// else
// {
// pages = Convert.ToInt32(Noofproducts / 500) + 1;
// }
// for (int i = 1; i <= pages; i++)
// {
// SubCategoryUrl.Add(Url1 + "?n=500&p=" + i);
// }
// }
// }
// catch
// {
// }
// _Chillyindex++;
// _Work.ReportProgress((_Chillyindex * 100 / CategoryUrl.Count()));
// }
// #endregion category
// #region subcategory
// else if (_Issubcat)
// {
// try
// {
// if(_Work1doc.DocumentNode.SelectNodes("//div[@class=\"plp-tile-name\"]/a")!=null)
// {
// foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//div[@class=\"plp-tile-name\"]/a"))
// {
// foreach (HtmlAttribute _Att in _Node.Attributes)
// {
// if (_Att.Name == "href")
// {
// _ProductUrl.Add("https://www.liveoutthere.com" + _Att.Value);
// }
// }
// }
// }
// }
// catch
// {
// }
// _Chillyindex++;
// _Work.ReportProgress((_Chillyindex * 100 / SubCategoryUrl.Count()));
// }
// #endregion subcategory
//}
//#endregion liveoutthere
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
#region chilly
if (_ISchilychiles)
{
if (!_IsCategory)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url1;
/*************Title****************/
HtmlNodeCollection _Title = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"page-title\"]/h1");
if (_Title != null)
{
dataGridView1.Rows[index].Cells[2].Value = Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(GenerateSku("CHCH", Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())), Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim()), "ChillyChiles");
}
else
{
HtmlNodeCollection _Title1 = _Work1doc.DocumentNode.SelectNodes("//h1");
if (_Title1 != null)
{
dataGridView1.Rows[index].Cells[2].Value = Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(GenerateSku("CHCH", Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())), Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim()), "ChillyChiles");
}
}
/*******************end************/
/***************Description***********/
HtmlNodeCollection _description = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"product-description\"]");
if (_description != null)
{
string manufacturer = "";
List<string> _Remove = new List<string>();
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//div[@id=\"product-description\"]")[0].ChildNodes)
{
if (!_Node.InnerText.Replace("Manufacturered", "manufactured").ToLower().Contains("manufactured in") && (_Node.InnerText.ToLower().Contains("manufactured") || _Node.InnerText.ToLower().Contains("manufacturer") || _Node.InnerText.ToLower().Contains("brand")))
{
manufacturer = manufacturer + _Node.InnerText.Trim().Replace(" ", "").Replace("Â", "");
_Remove.Add(_Node.InnerHtml);
}
}
if (_Remove.Count() == 0)
{
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//div[@id=\"product-description\"]")[0].ChildNodes)
{
if (_Node.InnerText.ToLower().Contains("brand"))
{
manufacturer = _Node.InnerText.Trim().Replace(" ", ""); ;
_Remove.Add(_Node.InnerHtml);
break;
}
}
}
_Description1 = Removeunsuaalcharcterfromstring(StripHTML(_description[0].InnerHtml).Trim());
try
{
if (_Description1.Length > 2000)
{
_Description1 = _Description1.Substring(0, 1997) + "...";
}
}
catch
{
}
dataGridView1.Rows[index].Cells[3].Value = _Description1.Replace("Â", "");
/************Manufacturer**********************/
if (manufacturer.Length > 0)
{
manufacturer = manufacturer.Replace(" ", "");
manufacturer = manufacturer.Replace("Manufacturered", "Manufactured").Replace("Manufacturerd", "Manufactured");
if (manufacturer.ToLower().Contains("brand:") && (manufacturer.ToLower().Contains("manufactured") || manufacturer.ToLower().Contains("manufacturer")))
{
string brand = "";
string mantext = "";
try
{
brand = manufacturer.Substring(manufacturer.ToLower().IndexOf("brand:"));
if (brand.Length > 0)
{
if (brand.ToLower().Contains("manufactured"))
{
brand = brand.Substring(0, brand.ToLower().IndexOf("manufactured")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("For", "").Replace("for", "").Replace("manufacturer", "").Replace("Manufacturer", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = brand.Replace(":", "").Trim();
}
else if (brand.ToLower().Contains("manufacturer"))
{
brand = brand.Substring(0, brand.ToLower().IndexOf("manufacturer")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = brand.Replace(":", "").Trim();
}
else
{
brand = brand.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = brand.Replace(":", "").Trim();
}
}
/**********Mantext*******************/
if (manufacturer.ToLower().IndexOf("manufactured") >= 0)
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured"));
}
else
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufacturer"));
}
if (mantext.ToLower().Contains("brand"))
{
mantext = mantext.Substring(0, mantext.ToLower().IndexOf("brand")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
}
else
{
mantext = mantext.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
}
/**************End*****************/
if ((dataGridView1.Rows[index].Cells[5].Value == null || dataGridView1.Rows[index].Cells[5].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString())) && (dataGridView1.Rows[index].Cells[6].Value == null || dataGridView1.Rows[index].Cells[6].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[6].Value.ToString())))
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured"));
if (mantext.ToLower().Contains("brand"))
{
mantext = mantext.Substring(0, mantext.ToLower().IndexOf("brand")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
}
else
{
mantext = mantext.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
}
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = mantext.Replace(":", "").Trim();
}
else if (dataGridView1.Rows[index].Cells[5].Value == null || dataGridView1.Rows[index].Cells[5].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString()))
{
dataGridView1.Rows[index].Cells[5].Value = brand;
}
else if (dataGridView1.Rows[index].Cells[6].Value == null || dataGridView1.Rows[index].Cells[6].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[6].Value.ToString()))
{
dataGridView1.Rows[index].Cells[6].Value = mantext.Replace(":", "").Trim();
}
}
catch
{
try
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured"));
}
catch
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufacturer"));
}
if (mantext.ToLower().Contains("brand"))
{
mantext = mantext.Substring(0, mantext.ToLower().IndexOf("brand")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("For", "").Replace("for", "").Trim();
}
else
{
mantext = mantext.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
}
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = mantext.Replace(":", "").Trim();
}
}
else
{
if (manufacturer.ToLower().IndexOf("brand:") >= 0)
{
manufacturer = manufacturer.Substring(manufacturer.ToLower().IndexOf("brand:") + 6).Trim();
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
try
{
if (manufacturer.Length > 25)
{
if (manufacturer.IndexOf(".") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf("."));
}
if (manufacturer.Length > 0)
{
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
}
if (manufacturer.IndexOf(":") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured For", "").Replace("Manufactured for", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured for", "").Replace("Manufactured For", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
}
else if (manufacturer.ToLower().IndexOf("manufactured") >= 0)
{
manufacturer = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured") + 12).Trim();
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
try
{
if (manufacturer.Length > 25)
{
if (manufacturer.IndexOf(".") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf("."));
}
if (manufacturer.Length > 0)
{
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
}
if (manufacturer.IndexOf(":") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured For", "").Replace("Manufactured for", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured for", "").Replace("Manufactured For", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
}
else if (manufacturer.ToLower().IndexOf("manufacturer") >= 0)
{
manufacturer = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufacturer") + 12).Trim();
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
try
{
if (manufacturer.Length > 25)
{
if (manufacturer.IndexOf(".") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf("."));
}
if (manufacturer.Length > 0)
{
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
}
if (manufacturer.IndexOf(":") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured For", "").Replace("Manufactured for", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured for", "").Replace("Manufactured For", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
}
}
}
try
{
if (dataGridView1.Rows[index].Cells[6].Value.ToString().Length > 25)
{
dataGridView1.Rows[index].Cells[6].Value = dataGridView1.Rows[index].Cells[5].Value;
}
}
catch
{
}
/*****************End*****************/
}
/***************End****************/
/*************For decsription empty********************/
try
{
if (dataGridView1.Rows[index].Cells[3].Value == null || dataGridView1.Rows[index].Cells[3].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[3].Value.ToString()))
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value;
}
}
catch
{
}
/*********************End*****************/
/*************For manufacturer Not sure**********************/
try
{
if (dataGridView1.Rows[index].Cells[5].Value != null || dataGridView1.Rows[index].Cells[5].Value != DBNull.Value || !String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString()))
{
if (dataGridView1.Rows[index].Cells[5].Value.ToString().ToLower().Contains("not sure"))
{
dataGridView1.Rows[index].Cells[5].Value = "";
}
}
}
catch
{
}
try
{
if (dataGridView1.Rows[index].Cells[6].Value != null || dataGridView1.Rows[index].Cells[6].Value != DBNull.Value || !String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[6].Value.ToString()))
{
if (dataGridView1.Rows[index].Cells[6].Value.ToString().ToLower().Contains("not sure"))
{
dataGridView1.Rows[index].Cells[6].Value = "";
}
}
}
catch
{
}
/***************End******************************************/
/*************Currency********************/
#region currency
dataGridView1.Rows[index].Cells[8].Value = "CDN";
#endregion currency
/****************End***********************/
#region price,stock
/***********Instock***********************/
if (_Work1doc.DocumentNode.SelectNodes("//form[@action=\"/cart/add\"]") != null)
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
/************Price**************************/
string price = "";
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//script"))
{
if (_Node.InnerText.Contains("\"price\""))
{
price = _Node.InnerText.Substring(_Node.InnerText.ToLower().IndexOf("\"price\""));
price = price.Substring(0, price.IndexOf("\","));
price = price.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
break;
}
}
dataGridView1.Rows[index].Cells[7].Value = price.Replace(":", "");
/***************End**************************/
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "N";
/************Price**************************/
string price = "";
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//script"))
{
if (_Node.InnerText.Contains("\"price\""))
{
price = _Node.InnerText.Substring(_Node.InnerText.ToLower().IndexOf("\"price\""));
price = price.Substring(0, price.IndexOf("\","));
price = price.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
break;
}
}
dataGridView1.Rows[index].Cells[7].Value = price.Replace(":", "");
/***************End************************/
}
/******************end*********************/
#endregion price,stock
/***********Url******************/
/**************end****************/
/*************Image Url***************/
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"four columns alpha\"]/img") != null)
{
foreach (HtmlAttribute _Att in _Work1doc.DocumentNode.SelectNodes("//div[@class=\"four columns alpha\"]/img")[0].Attributes)
{
if (_Att.Name.ToLower() == "src")
{
dataGridView1.Rows[index].Cells[10].Value = _Att.Value;
}
}
}
/********************end***************/
}
}
#endregion chilly
#region airsoft
else if (_IsAirsoft)
{
if (!_IsCategory && !_Issubcat)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
/*****************rowid**********************/
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url1;
/******************End**********************/
#region Name
/*****************Name**********************/
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"titlebar-title green left titlebar-product-title h1\"]") != null)
{
dataGridView1.Rows[index].Cells[2].Value = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"titlebar-title green left titlebar-product-title h1\"]")[0].InnerText.Trim();
}
/******************End**********************/
#endregion Name
#region sku
/*****************Sku**********************/
if (dataGridView1.Rows[index].Cells[2].Value != null || dataGridView1.Rows[index].Cells[2].Value != DBNull.Value || !String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[2].Value.ToString()))
{
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(GenerateSku("BA", dataGridView1.Rows[index].Cells[2].Value.ToString()), dataGridView1.Rows[index].Cells[2].Value.ToString(), "Airsoft");
}
/******************End**********************/
#endregion sku
#region Description
/*****************Description**********************/
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab1\"]/div[@class=\"collateral-box bl br\"]") != null)
{
_Description1 = StripHTML(_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab1\"]/div[@class=\"collateral-box bl br\"]")[0].InnerText).Trim();
}
/*************what will you Material***********************/
try
{
if (_Description1.Length < 2000)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab3\"]/div[@class=\"attribute-specs\"]/ul") != null)
{
string _material = StripHTML(_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab3\"]/div[@class=\"attribute-specs\"]/ul")[0].InnerHtml.Replace("<ul>", "").Replace("</ul>", "").Replace("<UL>", "").Replace("<li>", "").Replace("</li>", ",").Replace("</LI>", ",").Replace("<LI>", ""));
if (_material.Length > 0)
{
if (_material.Substring(_material.Length - 1) == ",")
{
_material = _material.Substring(0, _material.Length - 1);
}
_material = "Material: " + _material;
_Description1 = _Description1 + " " + _material.Trim();
}
}
}
}
catch
{
}
/**************End**************************/
/*************what will you need***********************/
try
{
if (_Description1.Length < 2000)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab5\"]/div[@class=\"collateral-box bl br\"]/ul") != null)
{
string _Need = StripHTML(_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab5\"]/div[@class=\"collateral-box bl br\"]/ul")[0].InnerHtml.Replace("<ul>", "").Replace("</ul>", "").Replace("<UL>", "").Replace("<li>", "").Replace("</li>", ",").Replace("</LI>", ",").Replace("<LI>", ""));
if (_Need.Length > 0)
{
if (_Need.Substring(_Need.Length - 1) == ",")
{
_Need = _Need.Substring(0, _Need.Length - 1);
}
_Need = "What you will need: " + _Need;
_Description1 = _Description1 + " " + _Need.Trim();
}
}
}
}
catch
{
}
/**************End**************************/
/**********What is in this box***************/
try
{
if (_Description1.Length < 2000)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab4\"]/div[@class=\"collateral-box bl br\"]/ul") != null)
{
string _IsinBox = StripHTML(_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab4\"]/div[@class=\"collateral-box bl br\"]/ul")[0].InnerHtml.Replace("<ul>", "").Replace("</ul>", "").Replace("<UL>", "").Replace("<li>", "").Replace("</li>", ",").Replace("</LI>", ",").Replace("<LI>", ""));
if (_IsinBox.Length > 0)
{
if (_IsinBox.Substring(_IsinBox.Length - 1) == ",")
{
_IsinBox = _IsinBox.Substring(0, _IsinBox.Length - 1);
}
_IsinBox = "What's in the Box: " + _IsinBox;
_Description1 = _Description1 + " " + _IsinBox.Trim();
}
}
}
}
catch
{
}
if (_Description1.Length > 2000)
{
_Description1 = _Description1.Substring(0, 1997) + "...";
}
dataGridView1.Rows[index].Cells[3].Value = _Description1;
/**************End**************************/
/******************End**********************/
#endregion Description
#region bulletpoints
/*****************bulletpoints**********************/
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab2\"]/div[@class=\"attribute-specs\"]") != null)
{
dataGridView1.Rows[index].Cells[4].Value = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab2\"]/div[@class=\"attribute-specs\"]")[0].InnerHtml.Trim();
}
/******************End**********************/
#endregion bulletpoints
#region Manufacturer
/*****************Manufacturer**********************/
/******************End**********************/
#endregion Manufacturer
#region Brandname
/*****************Brandname**********************/
/******************End**********************/
#endregion Brandname
#region Price
/*****************Price**********************/
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"price-box\"]/span/span[@class=\"price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"price-box\"]/span/span[@class=\"price\"]")[0].InnerText.Replace("$", "").Trim();
}
else
{
if (_Work1doc.DocumentNode.SelectNodes("//span[@class=\"price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc.DocumentNode.SelectNodes("//span[@class=\"price\"]")[0].InnerText.Replace("$", "").Trim();
}
}
/******************End**********************/
#endregion Price
#region Currency
/*****************Currency**********************/
dataGridView1.Rows[index].Cells[8].Value = "CDN";
/******************End**********************/
#endregion Currency
#region stock
/*****************stock**********************/
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"stock-notification green tl tr bl br right\"]") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"stock-notification green tl tr bl br right\"]")[0].InnerText.ToLower().Trim() == "in stock")
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
}
else
{
if (_Work1doc.DocumentNode.SelectNodes("//span[@class=\"stock-notification green tl tr bl br right\"]") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//span[@class=\"stock-notification green tl tr bl br right\"]")[0].InnerText.ToLower().Trim() == "in stock")
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
}
else if (_Work1doc.DocumentNode.SelectNodes("//span[@class=\"stock-notification red tl tr bl br right\"]") != null)
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
else if (_Work1doc.DocumentNode.SelectNodes("//span[@class=\"stock-notification yellow tl tr bl br right\"]") != null)
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
}
/******************End**********************/
#endregion stock
#region Image
/*****************Image url**********************/
string _ImageUrl = "";
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"main-product-img\"]/img") != null)
{
HtmlNode _Node = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"main-product-img\"]/img")[0];
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "src")
{
_ImageUrl = _Att.Value;
}
}
/*********For multiple images*********************/
try
{
if (_Work1doc.DocumentNode.SelectNodes("//script") != null)
{
foreach (HtmlNode _Node1 in _Work1doc.DocumentNode.SelectNodes("//script"))
{
string Imagetext = "";
if (_Node1.InnerText.ToLower().Contains("media_thumb_2()"))
{
Imagetext = _Node1.InnerText.ToLower().Substring(_Node1.InnerText.ToLower().IndexOf("https://www.buyairsoft.ca")).Replace("<img src=", "").Trim();
Imagetext = Imagetext.Substring(0, Imagetext.IndexOf("\"")).Replace("\"", "");
if (Imagetext.Length > 0)
{
if (Imagetext.Substring(Imagetext.Length - 1) == @"\")
Imagetext = Imagetext.Substring(0, Imagetext.Length - 1);
}
_ImageUrl = _ImageUrl + "@" + Imagetext;
}
if (_Node1.InnerText.ToLower().Contains("media_thumb_3()"))
{
Imagetext = _Node1.InnerText.ToLower().Substring(_Node1.InnerText.ToLower().IndexOf("https://www.buyairsoft.ca")).Replace("<img src=", "").Trim();
Imagetext = Imagetext.Substring(0, Imagetext.IndexOf("\"")).Replace("\"", "");
if (Imagetext.Length > 0)
{
if (Imagetext.Substring(Imagetext.Length - 1) == @"\")
Imagetext = Imagetext.Substring(0, Imagetext.Length - 1);
}
_ImageUrl = _ImageUrl + "@" + Imagetext;
}
}
}
}
catch
{
}
/***************End********************************/
if (_ImageUrl.Length > 0)
{
if (_ImageUrl.Substring(_ImageUrl.Length - 1) == ",")
{
_ImageUrl = _ImageUrl.Substring(0, _ImageUrl.Length - 1);
}
}
dataGridView1.Rows[index].Cells[10].Value = _ImageUrl;
}
/******************End**********************/
#endregion Image
}
}
#endregion airsoft
#region knife
else if (_IsKnifezone)
{
if (!_IsCategory)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
/*****************rowid**********************/
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url1;
dataGridView1.Rows[index].Cells[8].Value = "CDN";
/******************End**********************/
/**********Sku Bullet Points manufacturer brand Name*****************/
string Title = "";
if (_Work1doc.DocumentNode.SelectNodes("//div/h1") != null)
{
HtmlNode _Node = _Work1doc.DocumentNode.SelectNodes("//div/h1")[0];
Title = _Node.InnerText.Trim();
dataGridView1.Rows[index].Cells[2].Value = _Node.InnerText.Trim();
Dictionary<string, string> Manskubullet = new Dictionary<string, string>();
string test = _Node.XPath.Replace("div[1]/h1[1]", "") + "/table/tr/td/font[@color=\"color\"]";
HtmlNodeCollection _Nodecollkey = _Work1doc.DocumentNode.SelectNodes(_Node.XPath.Replace("div[1]/h1[1]", "") + "/table/tr/td/font[@color=\"black\"]");
HtmlNodeCollection _Nodecollvalue = _Work1doc.DocumentNode.SelectNodes(_Node.XPath.Replace("div[1]/h1[1]", "") + "/table/tr/td/font[@color=\"blue\"]");
if (_Nodecollkey != null)
{
for (int i = 0; i < _Nodecollkey.Count; i++)
{
try
{
Manskubullet.Add(_Nodecollkey[i].InnerText.Trim(), _Nodecollvalue[i].InnerText.Trim());
}
catch
{
}
if (Manskubullet.Last().Key.ToLower().Contains("retail") || Manskubullet.Last().Key.ToLower().Contains("price"))
break;
}
}
string Bullets = "<ul>";
foreach (var Items in Manskubullet)
{
if (Items.Key.ToLower().Contains("manufacturer"))
{
dataGridView1.Rows[index].Cells[5].Value = Items.Value.Trim();
dataGridView1.Rows[index].Cells[6].Value = Items.Value.Trim();
}
else if (Items.Key.ToLower().Contains("name"))
{
Title = Items.Value.Trim();
dataGridView1.Rows[index].Cells[2].Value = Items.Value.Trim();
}
else if (Items.Key.ToLower().Contains("model"))
{
dataGridView1.Rows[index].Cells[1].Value = Items.Value.Trim();
}
else if (Items.Key.ToLower().Contains("retail"))
{
dataGridView1.Rows[index].Cells[7].Value = Items.Value.ToLower().Replace("retail:", "").Replace("$", "").Replace("&", "").Replace("nbsp;", "").Trim();
}
else if (!Items.Key.ToLower().Contains("price"))
{
Bullets = Bullets + "<li>" + Items.Key + Items.Value + "</li>";
}
}
Bullets = Bullets + "</ul>";
if (Bullets.Length > 10)
{
dataGridView1.Rows[index].Cells[4].Value = Bullets;
}
/*********Description Images*******************/
try
{
bool _IsImageFind = false;
string xpath = "";
foreach (HtmlNode _imgNode in _Work1doc.DocumentNode.SelectNodes("//img"))
{
foreach (HtmlAttribute _Att in _imgNode.Attributes)
{
if (_Att.Name.ToLower() == "alt" && _Att.Value.ToLower().Contains(Title.ToLower()))
{
_IsImageFind = true;
xpath = _imgNode.XPath;
}
}
//if (_IsImageFind)
// break;
}
//if (xpath.Length == 0)
xpath = "/body[1]/table[5]/tr[1]/td[2]/table[1]/tr[1]/td[2]/table[1]/tr[1]/td[2]/img[1]";
try
{
if (xpath.Length > 0)
{
HtmlNode _imgNode = _Work1doc.DocumentNode.SelectNodes(xpath)[0];
xpath = "";
foreach (HtmlAttribute _Att in _imgNode.Attributes)
{
if (_Att.Name.ToLower() == "src" || _Att.Name.ToLower() == "data-cfsrc")
{
dataGridView1.Rows[index].Cells[10].Value = _Att.Value.Trim();
xpath = _imgNode.XPath.Replace("/img[1]", "");
}
}
}
#region description
if (xpath.Length > 0)
{
try
{
_Description1 = _Work1doc.DocumentNode.SelectNodes(xpath + "/font[@color=\"black\"]")[0].InnerText.Trim();
if (_Description1.Length > 2000)
{
dataGridView1.Rows[index].Cells[3].Value = _Description1.Substring(0, 1997) + "...";
}
else
{
dataGridView1.Rows[index].Cells[3].Value = _Description1;
}
}
catch
{
}
}
#endregion decsription
}
catch
{
}
}
catch
{
}
/*****************End*******************/
/***************Price************************/
if (dataGridView1.Rows[index].Cells[1].Value == null || dataGridView1.Rows[index].Cells[1].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[1].Value.ToString()))
{
if (_Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"identifier\"]") != null)
{
dataGridView1.Rows[index].Cells[1].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"identifier\"]")[0].InnerText.Trim();
}
}
if (dataGridView1.Rows[index].Cells[5].Value == null || dataGridView1.Rows[index].Cells[5].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString()))
{
if (_Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]") != null)
{
dataGridView1.Rows[index].Cells[5].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText.Trim();
dataGridView1.Rows[index].Cells[6].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText.Trim();
}
}
if (dataGridView1.Rows[index].Cells[7].Value == null || dataGridView1.Rows[index].Cells[7].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[7].Value.ToString()))
{
if (_Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]")[0].InnerText.Trim();
}
}
/**********************End********************/
#region stock
if (_Work1doc.DocumentNode.InnerHtml.ToLower().Contains("temporarily unavailable"))
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
#endregion stock
}
else
{
if (_Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"name\"]") != null)
{
/***************Sku***************/
try
{
dataGridView1.Rows[index].Cells[1].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"identifier\"]")[0].InnerText;
}
catch
{
}
/****************End*****************/
/***************Name***************/
try
{
dataGridView1.Rows[index].Cells[2].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"name\"]")[0].InnerText;
}
catch
{
}
/****************End*****************/
/***************Description***************/
try
{
string Xpath = "/body[1]/table[2]/tr[1]/td[2]/font[1]";
_Description1 = _Work1doc.DocumentNode.SelectNodes(Xpath)[0].InnerText;
if (_Description1.Length > 2000)
{
dataGridView1.Rows[index].Cells[3].Value = _Description1.Substring(0, 1997) + "...";
}
else
{
dataGridView1.Rows[index].Cells[3].Value = _Description1;
}
}
catch
{
}
/****************End*****************/
/***************Bullepoint***************/
//try
//{
// dataGridView1.Rows[index].Cells[2].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"name\"]")[0].InnerText;
//}
//catch
//{
//}
/****************End*****************/
/***************Brand***************/
try
{
dataGridView1.Rows[index].Cells[5].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText;
dataGridView1.Rows[index].Cells[6].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText;
}
catch
{
try
{
dataGridView1.Rows[index].Cells[5].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"manufacturer\"]")[0].InnerText;
dataGridView1.Rows[index].Cells[6].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"manufacturer\"]")[0].InnerText;
}
catch
{
}
}
/****************End*****************/
/****************Price********************/
foreach (HtmlNode _priceNode in _Work1doc.DocumentNode.SelectNodes("//font"))
{
if (_priceNode.InnerText.ToLower().Contains("retail"))
{
dataGridView1.Rows[index].Cells[7].Value = _priceNode.InnerText.ToLower().Replace("retail", "").Replace(":", "").Replace("$", "").Trim();
}
}
/***************End***********************/
/****************Stock********************/
if (_Work1doc.DocumentNode.InnerHtml.ToLower().Contains("temporarily unavailable"))
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
/***************End***********************/
/***************Image*******************/
try
{
string Xpath = "/body[1]/table[2]/tr[1]/td[1]/img[1]";
foreach (HtmlAttribute _Att in _Work1doc.DocumentNode.SelectNodes(Xpath)[0].Attributes)
{
if (_Att.Name.ToLower() == "src" || _Att.Name.ToLower() == "data-cfsrc")
{
dataGridView1.Rows[index].Cells[10].Value = _Att.Value;
}
}
}
catch
{
}
/********************End**********************************/
}
}
/*******************End****************************************/
}
}
#endregion knife
//#region liveoutthere
//else if (_IsLiveoutthere)
//{
// if (_IsProduct)
// {
// webBrowser1.Navigate(Url1);
// while (!_Isreadywebbrowser1)
// {
// Application.DoEvents();
// }
// #region codecolorsize
// foreach (HtmlElement element in webBrowser1.Document.GetElementsByTagName("div"))
// {
// string temp = element.GetAttribute("class");
// if (temp.Equals("size ng-scope") == true)
// {
// element.Focus();
// element.InvokeMember("click");
// }
// }
// #endregion
// }
//}
//#endregion liveoutthere
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
try
{
if (!_IsProduct)
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
}
}
catch
{
}
int index = 0;
#region warrior
if (_ISWarrior)
{
if (_IsCategory)
{
index = gridindex;
gridindex++;
try
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//table[@id=\"catTable\"]//tr");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
if (_Node.Attributes[0].Value.ToLower() == "productlisting-odd" || _Node.Attributes[0].Value.ToLower() == "productlisting-even")
{
BusinessLayer.Product Product = new BusinessLayer.Product();
Product.Currency = "CDN";
HtmlNodeCollection _Collection1 = _Node.SelectNodes("td");
if (_Collection1 != null)
{
/***************Sku**************/
try
{
Product.SKU = "WAW" + _Collection1[0].InnerText;
}
catch
{
}
/************End*****************/
/***************product name**************/
try
{
string test = _Collection1[3].SelectNodes("h3")[0].InnerText;
Product.Name = _Collection1[3].SelectNodes("h3")[0].InnerText;
}
catch
{
}
/************manufacturer*****************/
try
{
Product.Manufacturer = _Collection1[1].InnerText;
Product.Brand = _Collection1[1].InnerText;
}
catch
{
}
/***************Price**************/
try
{
string Price = "";
if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSpecialPrice\"]")[0].InnerText;
}
else if (_Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]") != null)
{
Price = _Collection1[4].SelectNodes("span//p//span[@class=\"productSalePrice\"]")[0].InnerText;
}
else
{
try
{
Price = _Collection1[4].SelectNodes("span[@class=\"product_list_price\"]")[0].InnerText;
}
catch
{
}
}
Price = Price.Replace("$", "");
Price = Price.ToLower().Replace("price", "").Replace("cdn", "").Trim();
Product.Price = Price;
}
catch
{
}
/***************End******************/
/***************In stock**************/
try
{
if (_Collection1[4].InnerText.ToLower().Contains("out of stock"))
{
Product.Stock = "0";
}
else
{
Product.Stock = "1";
}
}
catch
{
}
/**************Image****************/
try
{
if (_Collection1[2].SelectNodes("a//img") != null)
{
Product.Image = "http://www.warriorsandwonders.com/" + _Collection1[2].SelectNodes("a//img")[0].Attributes[0].Value;
}
}
catch
{
}
/****************End*****************/
/**************Link**************/
try
{
if (_Collection1[2].SelectNodes("a") != null)
{
Product.URL = _Collection1[2].SelectNodes("a")[0].Attributes[0].Value;
}
}
catch
{
}
/*****************End*************/
}
var restricted = (from brand in RestrictedBrands
where Product.Brand.Contains(brand)
select brand).ToList();
Product.Isparent = true;
Product.parentsku = Product.SKU;
if (restricted.Count() == 0)
Products.Add(Product);
}
}
/***********Sku**************/
/**************End*************/
}
}
catch
{
}
/**********Report progress**************/
_Work1.ReportProgress((gridindex * 100 / _Pages));
/****************end*******************/
}
else
{
}
}
#endregion warrior
#region chilly
else if (_ISchilychiles)
{
if (_IsCategory)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"content\"]/div/div/a");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
foreach (HtmlAttribute _Attr in _Node.Attributes)
{
if (_Attr.Name.ToLower() == "href")
{
_ProductUrl.Add("http://chillychiles.com/" + _Attr.Value);
}
}
}
}
_Chillyindex++;
_Work1.ReportProgress((_Chillyindex * 100 / _Pages));
}
else
{
_Chillyindex++;
_Work1.ReportProgress((_Chillyindex * 100 / _ProductUrl.Count()));
}
}
#endregion chilly
#region aircraft
else if (_IsAirsoft)
{
#region cat
if (_Issubcat)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"catStaticContentLeft\"]") != null)
{
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"catStaticContentLeft\"]/a"))
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name == "href")
{
if (!SubCategoryUrl.Contains(_Att.Value))
{
if (_Att.Value.Contains("?"))
{
SubCategoryUrl.Add(_Att.Value + "&limit=all");
}
else
{
SubCategoryUrl.Add(_Att.Value + "?limit=all");
}
}
}
}
}
}
else
{
SubCategoryUrl.Add(Url1);
}
_Chillyindex++;
_Work1.ReportProgress((_Chillyindex * 100 / CategoryUrl.Count()));
}
#endregion cat
#region subcat
else if (_IsCategory)
{
if (_Work1doc2.DocumentNode.SelectNodes("//a[@class=\"product-image\"]") != null)
{
string _Url = "";
bool _IsproductOurl = false;
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"product-image\"]"))
{
_IsproductOurl = false;
_Url = "";
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
_Url = _Att.Value;
}
else if (_Att.Name.ToLower() == "class" && _Att.Value == "product-image")
{
_IsproductOurl = true;
}
else if (_Att.Name.ToLower() == "title")
{
if (_Name.Contains(_Att.Value))
{
_IsproductOurl = false;
}
else
{
_Name.Add(_Att.Value);
}
}
}
if (_IsproductOurl)
{
if (!_ProductUrl.Contains(_Url))
{
_ProductUrl.Add(_Url);
}
}
}
}
_Chillyindex++;
_Work1.ReportProgress((_Chillyindex * 100 / SubCategoryUrl.Count()));
}
#endregion subcat
#region product
else
{
_Chillyindex++;
_Work1.ReportProgress((_Chillyindex * 100 / _ProductUrl.Count()));
}
#endregion product
}
#endregion aircraft
#region Knife
else if (_IsKnifezone)
{
if (_IsCategory)
{
bool Confirm = true;
while (Confirm)
{
Confirm = false;
if (_Work1doc2.DocumentNode.SelectNodes("//font[@size=\"+1\"]") != null)
{
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//font[@size=\"+1\"]/a"))
{
//if (!_Name.Contains(_Node.InnerText.Trim()))
//{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
if (!_Name.Contains(_Att.Value.Replace("../", "")))
{
_Name.Add(_Att.Value.Replace("../", ""));
_ProductUrl.Add("http://www.knifezone.ca/" + _Att.Value.Replace("../", ""));
}
}
}
//}
}
}
if (_Work1doc2.DocumentNode.SelectNodes("//img") != null)
{
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//img"))
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "alt")
{
try
{
if (_Att.Value == "next")
{
HtmlNode _Node2 = _Node.ParentNode;
foreach (HtmlAttribute _Att1 in _Node2.Attributes)
{
if (_Att1.Name.ToLower() == "href")
{
string _Url = Reverse(Url2);
_Url = _Url.Substring(_Url.IndexOf("/"));
_Url = Reverse(_Url);
if (!SubCategoryUrl.Contains(_Url + _Att1.Value))
{
SubCategoryUrl.Add(_Url + _Att1.Value);
_Work1doc2.LoadHtml(_Client2.DownloadString(_Url + _Att1.Value));
Confirm = true;
}
}
}
}
}
catch
{
}
}
}
}
}
}
_Chillyindex++;
_Work1.ReportProgress((_Chillyindex * 100 / CategoryUrl.Count()));
}
else
{
_Chillyindex++;
_Work1.ReportProgress((_Chillyindex * 100 / _ProductUrl.Count()));
}
}
#endregion knife
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
#region chilly
if (_ISchilychiles)
{
if (!_IsCategory)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url2;
/*************Title****************/
HtmlNodeCollection _Title = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"page-title\"]/h1");
if (_Title != null)
{
dataGridView1.Rows[index].Cells[2].Value = Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(GenerateSku("CHCH", Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())), Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim()), "ChillyChiles");
}
else
{
HtmlNodeCollection _Title1 = _Work1doc2.DocumentNode.SelectNodes("//h1");
if (_Title1 != null)
{
dataGridView1.Rows[index].Cells[2].Value = Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(GenerateSku("CHCH", Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())), Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim()), "ChillyChiles");
}
}
/*******************end************/
/***************Description***********/
HtmlNodeCollection _description = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"product-description\"]");
if (_description != null)
{
string manufacturer = "";
List<string> _Remove = new List<string>();
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"product-description\"]")[0].ChildNodes)
{
if (!_Node.InnerText.Replace("Manufacturered", "manufactured").ToLower().Contains("manufactured in") && (_Node.InnerText.ToLower().Contains("manufactured") || _Node.InnerText.ToLower().Contains("manufacturer") || _Node.InnerText.ToLower().Contains("brand")))
{
manufacturer = manufacturer + _Node.InnerText.Trim().Replace(" ", "").Replace("Â", "");
_Remove.Add(_Node.InnerHtml);
}
}
if (_Remove.Count() == 0)
{
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"product-description\"]")[0].ChildNodes)
{
if (_Node.InnerText.ToLower().Contains("brand"))
{
manufacturer = _Node.InnerText.Trim().Replace(" ", "").Replace("Â", "");
_Remove.Add(_Node.InnerHtml);
break;
}
}
}
_Description2 = Removeunsuaalcharcterfromstring(StripHTML(_description[0].InnerHtml).Trim());
try
{
if (_Description2.Length > 2000)
{
_Description2 = _Description2.Substring(0, 1997) + "...";
}
}
catch
{
}
dataGridView1.Rows[index].Cells[3].Value = _Description2.Replace("Â", "");
/************Manufacturer**********************/
if (manufacturer.Length > 0)
{
manufacturer = manufacturer.Replace(" ", "");
manufacturer = manufacturer.Replace("Manufacturered", "Manufactured").Replace("Manufacturerd", "Manufactured");
if (manufacturer.ToLower().Contains("brand:") && (manufacturer.ToLower().Contains("manufactured") || manufacturer.ToLower().Contains("manufacturer")))
{
string brand = "";
string mantext = "";
try
{
brand = manufacturer.Substring(manufacturer.ToLower().IndexOf("brand:"));
if (brand.Length > 0)
{
if (brand.ToLower().Contains("manufactured"))
{
brand = brand.Substring(0, brand.ToLower().IndexOf("manufactured")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("For", "").Replace("for", "").Replace("manufacturer", "").Replace("Manufacturer", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = brand.Replace(":", "").Trim();
}
else if (brand.ToLower().Contains("manufacturer"))
{
brand = brand.Substring(0, brand.ToLower().IndexOf("manufacturer")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = brand.Replace(":", "").Trim();
}
else
{
brand = brand.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = brand.Replace(":", "").Trim();
}
}
/**********Mantext*******************/
if (manufacturer.ToLower().IndexOf("manufactured") >= 0)
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured"));
}
else
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufacturer"));
}
if (mantext.ToLower().Contains("brand"))
{
mantext = mantext.Substring(0, mantext.ToLower().IndexOf("brand")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
}
else
{
mantext = mantext.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
}
/**************End*****************/
if ((dataGridView1.Rows[index].Cells[5].Value == null || dataGridView1.Rows[index].Cells[5].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString())) && (dataGridView1.Rows[index].Cells[6].Value == null || dataGridView1.Rows[index].Cells[6].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[6].Value.ToString())))
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured"));
if (mantext.ToLower().Contains("brand"))
{
mantext = mantext.Substring(0, mantext.ToLower().IndexOf("brand")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
}
else
{
mantext = mantext.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
}
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = mantext.Replace(":", "").Trim();
}
else if (dataGridView1.Rows[index].Cells[5].Value == null || dataGridView1.Rows[index].Cells[5].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString()))
{
dataGridView1.Rows[index].Cells[5].Value = brand;
}
else if (dataGridView1.Rows[index].Cells[6].Value == null || dataGridView1.Rows[index].Cells[6].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[6].Value.ToString()))
{
dataGridView1.Rows[index].Cells[6].Value = mantext.Replace(":", "").Trim();
}
}
catch
{
try
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured"));
}
catch
{
mantext = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufacturer"));
}
if (mantext.ToLower().Contains("brand"))
{
mantext = mantext.Substring(0, mantext.ToLower().IndexOf("brand")).Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("For", "").Replace("for", "").Trim();
}
else
{
mantext = mantext.Replace("Brand", "").Replace("Manufactured", "").Replace("manufactured", "").Replace("brand", "").Replace("By", "").Replace("by", "").Replace("manufacturer", "").Replace("Manufacturer", "").Replace("For", "").Replace("for", "").Trim();
}
try
{
if (mantext.Length > 25)
{
if (mantext.IndexOf(".") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf("."));
}
if (mantext.Length > 0)
{
if (mantext.Substring(0, 1) == ":")
{
mantext = mantext.Substring(1);
}
}
if (mantext.IndexOf(":") > 0)
{
mantext = mantext.Substring(0, mantext.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = mantext.Replace(":", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = mantext.Replace(":", "").Trim();
}
}
else
{
if (manufacturer.ToLower().IndexOf("brand:") >= 0)
{
manufacturer = manufacturer.Substring(manufacturer.ToLower().IndexOf("brand:") + 6).Trim();
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
try
{
if (manufacturer.Length > 25)
{
if (manufacturer.IndexOf(".") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf("."));
}
if (manufacturer.Length > 0)
{
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
}
if (manufacturer.IndexOf(":") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured For", "").Replace("Manufactured for", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured for", "").Replace("Manufactured For", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
}
else if (manufacturer.ToLower().IndexOf("manufactured") >= 0)
{
manufacturer = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufactured") + 12).Trim();
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
try
{
if (manufacturer.Length > 25)
{
if (manufacturer.IndexOf(".") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf("."));
}
if (manufacturer.Length > 0)
{
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
}
if (manufacturer.IndexOf(":") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured For", "").Replace("Manufactured for", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured for", "").Replace("Manufactured For", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
}
else if (manufacturer.ToLower().IndexOf("manufacturer") >= 0)
{
manufacturer = manufacturer.Substring(manufacturer.ToLower().IndexOf("manufacturer") + 12).Trim();
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
try
{
if (manufacturer.Length > 25)
{
if (manufacturer.IndexOf(".") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf("."));
}
if (manufacturer.Length > 0)
{
if (manufacturer.Substring(0, 1) == ":")
{
manufacturer = manufacturer.Substring(1);
}
}
if (manufacturer.IndexOf(":") > 0)
{
manufacturer = manufacturer.Substring(0, manufacturer.IndexOf(":"));
}
}
}
catch
{
}
dataGridView1.Rows[index].Cells[5].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured For", "").Replace("Manufactured for", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
dataGridView1.Rows[index].Cells[6].Value = manufacturer.Replace("Manufactured by", "").Replace("by", "").Replace("for", "").Replace("Manufactured for", "").Replace("Manufactured For", "").Replace("Manufacturer", "").Replace("Manufactured By", "").Replace(":", "").Replace(" ", "").Trim();
}
}
}
try
{
if (dataGridView1.Rows[index].Cells[6].Value.ToString().Length > 25)
{
dataGridView1.Rows[index].Cells[6].Value = dataGridView1.Rows[index].Cells[5].Value;
}
}
catch
{
}
/*****************End*****************/
}
/***************End****************/
/*************For decsription empty********************/
try
{
if (dataGridView1.Rows[index].Cells[3].Value == null || dataGridView1.Rows[index].Cells[3].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[3].Value.ToString()))
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value;
}
}
catch
{
}
/*********************End*****************/
/*************For manufacturer Not sure**********************/
try
{
if (dataGridView1.Rows[index].Cells[5].Value != null || dataGridView1.Rows[index].Cells[5].Value != DBNull.Value || !String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString()))
{
if (dataGridView1.Rows[index].Cells[5].Value.ToString().ToLower().Contains("not sure"))
{
dataGridView1.Rows[index].Cells[5].Value = "";
}
}
}
catch
{
}
try
{
if (dataGridView1.Rows[index].Cells[6].Value != null || dataGridView1.Rows[index].Cells[6].Value != DBNull.Value || !String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[6].Value.ToString()))
{
if (dataGridView1.Rows[index].Cells[6].Value.ToString().ToLower().Contains("not sure"))
{
dataGridView1.Rows[index].Cells[6].Value = "";
}
}
}
catch
{
}
/***************End******************************************/
/*************Currency********************/
#region currency
dataGridView1.Rows[index].Cells[8].Value = "CDN";
#endregion currency
/****************End***********************/
#region price,stock
/***********Instock***********************/
if (_Work1doc2.DocumentNode.SelectNodes("//form[@action=\"/cart/add\"]") != null)
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
/************Price**************************/
string price = "";
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//script"))
{
if (_Node.InnerText.Contains("\"price\""))
{
price = _Node.InnerText.Substring(_Node.InnerText.ToLower().IndexOf("\"price\""));
price = price.Substring(0, price.IndexOf("\","));
price = price.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
break;
}
}
dataGridView1.Rows[index].Cells[7].Value = price.Replace(":", "");
/***************End**************************/
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "N";
/************Price**************************/
string price = "";
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//script"))
{
if (_Node.InnerText.Contains("\"price\""))
{
price = _Node.InnerText.Substring(_Node.InnerText.ToLower().IndexOf("\"price\""));
price = price.Substring(0, price.IndexOf("\","));
price = price.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
break;
}
}
dataGridView1.Rows[index].Cells[7].Value = price.Replace(":", "");
/***************End************************/
}
/******************end*********************/
#endregion price,stock
/***********Url******************/
/**************end****************/
/*************Image Url***************/
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"four columns alpha\"]/img") != null)
{
foreach (HtmlAttribute _Att in _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"four columns alpha\"]/img")[0].Attributes)
{
if (_Att.Name.ToLower() == "src")
{
dataGridView1.Rows[index].Cells[10].Value = _Att.Value;
}
}
}
/********************end***************/
}
}
#endregion chilly
#region airsoft
else if (_IsAirsoft)
{
if (!_IsCategory && !_Issubcat)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
/*****************rowid**********************/
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url2;
/******************End**********************/
#region Name
/*****************Name**********************/
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"titlebar-title green left titlebar-product-title h1\"]") != null)
{
dataGridView1.Rows[index].Cells[2].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"titlebar-title green left titlebar-product-title h1\"]")[0].InnerText.Trim();
}
/******************End**********************/
#endregion Name
#region sku
/*****************Sku**********************/
if (dataGridView1.Rows[index].Cells[2].Value != null || dataGridView1.Rows[index].Cells[2].Value != DBNull.Value || !String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[2].Value.ToString()))
{
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(GenerateSku("BA", dataGridView1.Rows[index].Cells[2].Value.ToString()), dataGridView1.Rows[index].Cells[2].Value.ToString(), "Airsoft");
}
/******************End**********************/
#endregion sku
#region Description
/*****************Description**********************/
if (_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab1\"]/div[@class=\"collateral-box bl br\"]") != null)
{
_Description2 = StripHTML(_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab1\"]/div[@class=\"collateral-box bl br\"]")[0].InnerText).Trim();
}
/*************what will you Material***********************/
try
{
if (_Description2.Length < 2000)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab3\"]/div[@class=\"attribute-specs\"]/ul") != null)
{
string _material = StripHTML(_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab3\"]/div[@class=\"attribute-specs\"]/ul")[0].InnerHtml.Replace("<ul>", "").Replace("</ul>", "").Replace("<UL>", "").Replace("<li>", "").Replace("</li>", ",").Replace("</LI>", ",").Replace("<LI>", ""));
if (_material.Length > 0)
{
if (_material.Substring(_material.Length - 1) == ",")
{
_material = _material.Substring(0, _material.Length - 1);
}
_material = "Material: " + _material;
_Description2 = _Description2 + " " + _material.Trim();
}
}
}
}
catch
{
}
/**************End**************************/
/*************what will you need***********************/
try
{
if (_Description2.Length < 2000)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab5\"]/div[@class=\"collateral-box bl br\"]/ul") != null)
{
string _Need = StripHTML(_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab5\"]/div[@class=\"collateral-box bl br\"]/ul")[0].InnerHtml.Replace("<ul>", "").Replace("</ul>", "").Replace("<UL>", "").Replace("<li>", "").Replace("</li>", ",").Replace("</LI>", ",").Replace("<LI>", ""));
if (_Need.Length > 0)
{
if (_Need.Substring(_Need.Length - 1) == ",")
{
_Need = _Need.Substring(0, _Need.Length - 1);
}
_Need = "What you will need: " + _Need;
_Description2 = _Description2 + " " + _Need.Trim();
}
}
}
}
catch
{
}
/**************End**************************/
/**********What is in this box***************/
try
{
if (_Description2.Length < 2000)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab4\"]/div[@class=\"collateral-box bl br\"]/ul") != null)
{
string _IsinBox = StripHTML(_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab4\"]/div[@class=\"collateral-box bl br\"]/ul")[0].InnerHtml.Replace("<ul>", "").Replace("</ul>", "").Replace("<UL>", "").Replace("<li>", "").Replace("</li>", ",").Replace("</LI>", ",").Replace("<LI>", ""));
if (_IsinBox.Length > 0)
{
if (_IsinBox.Substring(_IsinBox.Length - 1) == ",")
{
_IsinBox = _IsinBox.Substring(0, _IsinBox.Length - 1);
}
_IsinBox = "What's in the Box: " + _IsinBox;
_Description2 = _Description2 + " " + _IsinBox.Trim();
}
}
}
}
catch
{
}
if (_Description2.Length > 2000)
{
_Description2 = _Description2.Substring(0, 1997) + "...";
}
dataGridView1.Rows[index].Cells[3].Value = _Description2;
/**************End**************************/
/******************End**********************/
#endregion Description
#region bulletpoints
/*****************bulletpoints**********************/
if (_Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab2\"]/div[@class=\"attribute-specs\"]") != null)
{
dataGridView1.Rows[index].Cells[4].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab2\"]/div[@class=\"attribute-specs\"]")[0].InnerHtml.Trim();
}
/******************End**********************/
#endregion bulletpoints
#region Manufacturer
/*****************Manufacturer**********************/
/******************End**********************/
#endregion Manufacturer
#region Brandname
/*****************Brandname**********************/
/******************End**********************/
#endregion Brandname
#region Price
/*****************Price**********************/
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"price-box\"]/span/span[@class=\"price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"price-box\"]/span/span[@class=\"price\"]")[0].InnerText.Replace("$", "").Trim();
}
else
{
if (_Work1doc2.DocumentNode.SelectNodes("//span[@class=\"price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@class=\"price\"]")[0].InnerText.Replace("$", "").Trim();
}
}
/******************End**********************/
#endregion Price
#region Currency
/*****************Currency**********************/
dataGridView1.Rows[index].Cells[8].Value = "CDN";
/******************End**********************/
#endregion Currency
#region stock
/*****************stock**********************/
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"stock-notification green tl tr bl br right\"]") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"titlebar tl tr\"]/span[@class=\"stock-notification green tl tr bl br right\"]")[0].InnerText.ToLower().Trim() == "in stock")
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
}
else
{
if (_Work1doc2.DocumentNode.SelectNodes("//span[@class=\"stock-notification green tl tr bl br right\"]") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//span[@class=\"stock-notification green tl tr bl br right\"]")[0].InnerText.ToLower().Trim() == "in stock")
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
}
else if (_Work1doc2.DocumentNode.SelectNodes("//span[@class=\"stock-notification red tl tr bl br right\"]") != null)
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
else if (_Work1doc2.DocumentNode.SelectNodes("//span[@class=\"stock-notification yellow tl tr bl br right\"]") != null)
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
}
/******************End**********************/
#endregion stock
#region Image
/*****************Image url**********************/
string _ImageUrl = "";
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"main-product-img\"]/img") != null)
{
HtmlNode _Node = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"main-product-img\"]/img")[0];
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "src")
{
_ImageUrl = _Att.Value;
}
}
/*********For multiple images*********************/
try
{
if (_Work1doc2.DocumentNode.SelectNodes("//script") != null)
{
foreach (HtmlNode _Node1 in _Work1doc2.DocumentNode.SelectNodes("//script"))
{
string Imagetext = "";
if (_Node1.InnerText.ToLower().Contains("media_thumb_2()"))
{
Imagetext = _Node1.InnerText.ToLower().Substring(_Node1.InnerText.ToLower().IndexOf("https://www.buyairsoft.ca")).Replace("<img src=", "").Trim();
Imagetext = Imagetext.Substring(0, Imagetext.IndexOf("\"")).Replace("\"", "");
if (Imagetext.Length > 0)
{
if (Imagetext.Substring(Imagetext.Length - 1) == @"\")
Imagetext = Imagetext.Substring(0, Imagetext.Length - 1);
}
_ImageUrl = _ImageUrl + "@" + Imagetext;
}
if (_Node1.InnerText.ToLower().Contains("media_thumb_3()"))
{
Imagetext = _Node1.InnerText.ToLower().Substring(_Node1.InnerText.ToLower().IndexOf("https://www.buyairsoft.ca")).Replace("<img src=", "").Trim();
Imagetext = Imagetext.Substring(0, Imagetext.IndexOf("\"")).Replace("\"", "");
if (Imagetext.Length > 0)
{
if (Imagetext.Substring(Imagetext.Length - 1) == @"\")
Imagetext = Imagetext.Substring(0, Imagetext.Length - 1);
}
_ImageUrl = _ImageUrl + "@" + Imagetext;
}
}
}
}
catch
{
}
/***************End********************************/
if (_ImageUrl.Length > 0)
{
if (_ImageUrl.Substring(_ImageUrl.Length - 1) == ",")
{
_ImageUrl = _ImageUrl.Substring(0, _ImageUrl.Length - 1);
}
}
dataGridView1.Rows[index].Cells[10].Value = _ImageUrl;
}
/******************End**********************/
#endregion Image
}
}
#endregion airsoft
#region knife
else if (_IsKnifezone)
{
if (!_IsCategory)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
/*****************rowid**********************/
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url2;
dataGridView1.Rows[index].Cells[8].Value = "CDN";
/******************End**********************/
/**********Sku Bullet Points manufacturer brand Name*****************/
string Title = "";
if (_Work1doc2.DocumentNode.SelectNodes("//div/h1") != null)
{
HtmlNode _Node = _Work1doc2.DocumentNode.SelectNodes("//div/h1")[0];
Title = _Node.InnerText.Trim();
dataGridView1.Rows[index].Cells[2].Value = _Node.InnerText.Trim();
Dictionary<string, string> Manskubullet = new Dictionary<string, string>();
string test = _Node.XPath.Replace("div[1]/h1[1]", "") + "/table/tr/td/font[@color=\"color\"]";
HtmlNodeCollection _Nodecollkey = _Work1doc2.DocumentNode.SelectNodes(_Node.XPath.Replace("div[1]/h1[1]", "") + "/table/tr/td/font[@color=\"black\"]");
HtmlNodeCollection _Nodecollvalue = _Work1doc2.DocumentNode.SelectNodes(_Node.XPath.Replace("div[1]/h1[1]", "") + "/table/tr/td/font[@color=\"blue\"]");
if (_Nodecollkey != null)
{
for (int i = 0; i < _Nodecollkey.Count; i++)
{
try
{
Manskubullet.Add(_Nodecollkey[i].InnerText.Trim(), _Nodecollvalue[i].InnerText.Trim());
}
catch
{
}
if (Manskubullet.Last().Key.ToLower().Contains("retail") || Manskubullet.Last().Key.ToLower().Contains("price"))
break;
}
}
string Bullets = "<ul>";
foreach (var Items in Manskubullet)
{
if (Items.Key.ToLower().Contains("manufacturer"))
{
dataGridView1.Rows[index].Cells[5].Value = Items.Value.Trim();
dataGridView1.Rows[index].Cells[6].Value = Items.Value.Trim();
}
else if (Items.Key.ToLower().Contains("name"))
{
Title = Items.Value.Trim();
dataGridView1.Rows[index].Cells[2].Value = Items.Value.Trim();
}
else if (Items.Key.ToLower().Contains("model"))
{
dataGridView1.Rows[index].Cells[1].Value = Items.Value.Trim();
}
else if (Items.Key.ToLower().Contains("retail"))
{
dataGridView1.Rows[index].Cells[7].Value = Items.Value.ToLower().Replace("retail:", "").Replace("$", "").Replace("&", "").Replace("nbsp;", "").Trim();
}
else if (!Items.Key.ToLower().Contains("price"))
{
Bullets = Bullets + "<li>" + Items.Key + Items.Value + "</li>";
}
}
Bullets = Bullets + "</ul>";
if (Bullets.Length > 10)
{
dataGridView1.Rows[index].Cells[4].Value = Bullets;
}
/*********Description Images*******************/
try
{
bool _IsImageFind = false;
string xpath = "";
foreach (HtmlNode _imgNode in _Work1doc2.DocumentNode.SelectNodes("//img"))
{
foreach (HtmlAttribute _Att in _imgNode.Attributes)
{
if (_Att.Name.ToLower() == "alt" && _Att.Value.ToLower().Contains(Title.ToLower()))
{
_IsImageFind = true;
xpath = _imgNode.XPath;
}
}
//if (_IsImageFind)
// break;
}
//if (xpath.Length == 0)
xpath = "/body[1]/table[5]/tr[1]/td[2]/table[1]/tr[1]/td[2]/table[1]/tr[1]/td[2]/img[1]";
try
{
if (xpath.Length > 0)
{
HtmlNode _imgNode = _Work1doc2.DocumentNode.SelectNodes(xpath)[0];
xpath = "";
foreach (HtmlAttribute _Att in _imgNode.Attributes)
{
if (_Att.Name.ToLower() == "src" || _Att.Name.ToLower() == "data-cfsrc")
{
dataGridView1.Rows[index].Cells[10].Value = _Att.Value.Trim();
xpath = _imgNode.XPath.Replace("/img[1]", "");
}
}
}
#region description
if (xpath.Length > 0)
{
try
{
_Description2 = _Work1doc2.DocumentNode.SelectNodes(xpath + "/font[@color=\"black\"]")[0].InnerText.Trim();
if (_Description2.Length > 2000)
{
dataGridView1.Rows[index].Cells[3].Value = _Description2.Substring(0, 1997) + "...";
}
else
{
dataGridView1.Rows[index].Cells[3].Value = _Description2;
}
}
catch
{
}
}
#endregion decsription
}
catch
{
}
}
catch
{
}
/*****************End*******************/
/***************Price************************/
if (dataGridView1.Rows[index].Cells[1].Value == null || dataGridView1.Rows[index].Cells[1].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[1].Value.ToString()))
{
if (_Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"identifier\"]") != null)
{
dataGridView1.Rows[index].Cells[1].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"identifier\"]")[0].InnerText.Trim();
}
}
if (dataGridView1.Rows[index].Cells[5].Value == null || dataGridView1.Rows[index].Cells[5].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString()))
{
if (_Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]") != null)
{
dataGridView1.Rows[index].Cells[5].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText.Trim();
dataGridView1.Rows[index].Cells[6].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText.Trim();
}
}
if (dataGridView1.Rows[index].Cells[7].Value == null || dataGridView1.Rows[index].Cells[7].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[7].Value.ToString()))
{
if (_Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]")[0].InnerText.Trim();
}
}
/**********************End********************/
#region stock
if (_Work1doc2.DocumentNode.InnerHtml.ToLower().Contains("temporarily unavailable"))
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
#endregion stock
}
else
{
if (_Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"name\"]") != null)
{
/***************Sku***************/
try
{
dataGridView1.Rows[index].Cells[1].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"identifier\"]")[0].InnerText;
}
catch
{
}
/****************End*****************/
/***************Name***************/
try
{
dataGridView1.Rows[index].Cells[2].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"name\"]")[0].InnerText;
}
catch
{
}
/****************End*****************/
/***************Description***************/
try
{
string Xpath = "/body[1]/table[2]/tr[1]/td[2]/font[1]";
_Description2 = _Work1doc2.DocumentNode.SelectNodes(Xpath)[0].InnerText;
if (_Description2.Length > 2000)
{
dataGridView1.Rows[index].Cells[3].Value = _Description2.Substring(0, 1997) + "...";
}
else
{
dataGridView1.Rows[index].Cells[3].Value = _Description2;
}
}
catch
{
}
/****************End*****************/
/***************Bullepoint***************/
//try
//{
// dataGridView1.Rows[index].Cells[2].Value = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"name\"]")[0].InnerText;
//}
//catch
//{
//}
/****************End*****************/
/***************Brand***************/
try
{
dataGridView1.Rows[index].Cells[5].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText;
dataGridView1.Rows[index].Cells[6].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"brand\"]")[0].InnerText;
}
catch
{
try
{
dataGridView1.Rows[index].Cells[5].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"manufacturer\"]")[0].InnerText;
dataGridView1.Rows[index].Cells[6].Value = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"manufacturer\"]")[0].InnerText;
}
catch
{
}
}
/****************End*****************/
/****************Price********************/
foreach (HtmlNode _priceNode in _Work1doc2.DocumentNode.SelectNodes("//font"))
{
if (_priceNode.InnerText.ToLower().Contains("retail"))
{
dataGridView1.Rows[index].Cells[7].Value = _priceNode.InnerText.ToLower().Replace("retail", "").Replace(":", "").Replace("$", "").Trim();
}
}
/***************End***********************/
/****************Stock********************/
if (_Work1doc2.DocumentNode.InnerHtml.ToLower().Contains("temporarily unavailable"))
{
dataGridView1.Rows[index].Cells[9].Value = "N";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = "Y";
}
/***************End***********************/
/***************Image*******************/
try
{
string Xpath = "/body[1]/table[2]/tr[1]/td[1]/img[1]";
foreach (HtmlAttribute _Att in _Work1doc2.DocumentNode.SelectNodes(Xpath)[0].Attributes)
{
if (_Att.Name.ToLower() == "src" || _Att.Name.ToLower() == "data-cfsrc")
{
dataGridView1.Rows[index].Cells[10].Value = _Att.Value;
}
}
}
catch
{
}
/********************End**********************************/
}
}
/*******************End****************************************/
}
}
#endregion knife
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
public string GenerateSku(string starttext, string productname)
{
string result = "";
foreach (var c in productname)
{
int ascii = (int)c;
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == ' ')
{
result += c;
}
}
string[] name = result.Split(' ');
string firstcharcter = "";
foreach (string _name in name)
{
firstcharcter = _name.Trim();
if (firstcharcter.Length > 0)
starttext = starttext + firstcharcter.Substring(0, 1).ToUpper();
}
return starttext;
}
public void SendMail(string body, string subject, bool Isattachment, bool Exception)
{
try
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
MailAddress Fromaddress = new MailAddress("<EMAIL>", "Vishal Consultancy");
message.From = Fromaddress;
message.Subject = subject;
message.To.Add(new MailAddress("<EMAIL>"));
message.Body = body;
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient mclient = new System.Net.Mail.SmtpClient();
mclient.Host = "smtp.gmail.com";
mclient.Port = 587;
mclient.EnableSsl = true;
if (!Exception)
{
try
{
string name = Convert.ToString(System.Configuration.ConfigurationSettings.
AppSettings["Contacts"]);
string[] mails = name.Split(',');
foreach (string mail in mails)
{
if (mail.Length > 0)
{
message.CC.Add(mail);
}
}
}
catch
{
}
if (Isattachment)
{
}
}
mclient.Credentials = new System.Net.NetworkCredential("<EMAIL>", "(123456@#Aa)");
mclient.Send(message);
}
catch
{
}
}
private void Go_Click(object sender, EventArgs e)
{
_IsProduct = false;
_Name.Clear();
_Chillyindex = 0;
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_ProductUrl.Clear();
_percent.Visible = false;
Go.Enabled = false;
Pause.Enabled = true;
createcsvfile.Enabled = true;
_Bar1.Value = 0;
_Url.Clear();
_Tbale.Rows.Clear();
_Tbale.Columns.Clear();
dataGridView1.Rows.Clear();
DataColumn _Dc = new DataColumn();
_Dc.ColumnName = "Rowid";
_Dc.AutoIncrement = true;
_Dc.DataType = typeof(int);
_Dc.AutoIncrementSeed = 1;
_Dc.AutoIncrementStep = 1;
_Tbale.Columns.Add(_Dc);
_Tbale.Columns.Add("SKU", typeof(string));
_Tbale.Columns.Add("Product Name", typeof(string));
_Tbale.Columns.Add("Product Description", typeof(string));
_Tbale.Columns.Add("Bullet Points", typeof(string));
_Tbale.Columns.Add("Manufacturer", typeof(string));
_Tbale.Columns.Add("Brand Name", typeof(string));
_Tbale.Columns.Add("Price", typeof(string));
_Tbale.Columns.Add("Currency", typeof(string));
_Tbale.Columns.Add("In Stock", typeof(string));
_Tbale.Columns.Add("Image URL", typeof(string));
_Tbale.Columns.Add("URL", typeof(string));
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
#region warrior
if (chkstorelist.GetItemChecked(0))
{
_ISWarrior = true;
_ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&keyword=keywords&search_in_description=1&product_type=&kfi_blade_length_from=0&kfi_blade_length_to=15&kfi_overall_length_from=0&kfi_overall_length_to=30&kfi_serration=ANY&kfi_is_coated=ANY&kfo_blade_length_from=0&kfo_blade_length_to=8&kfo_overall_length_from=0&kfo_overall_length_to=20&kfo_serration=ANY&kfo_is_coated=ANY&kfo_assisted=ANY&kk_blade_length_from=0&kk_blade_length_to=15&fl_lumens_from=0&fl_lumens_to=18000&fl_num_cells_from=1&fl_num_cells_to=10&fl_num_modes_from=1&fl_num_modes_to=15&sw_blade_length_from=0&sw_blade_length_to=60&sw_overall_length_from=0&sw_overall_length_to=70&inc_subcat=1&pfrom=0.01&pto=10000.00&x=36&y=6&perPage=60";
// _ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&search_in_description=1&keyword=Boker+Magnum+01RY818";
// _ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&search_in_description=1&keyword=5T56026";
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read sku and manufacturer information form category page of " + chkstorelist.Items[0].ToString() + " Website";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"productsListingTopNumber\"]//strong");
if (_Collection != null)
{
_TotalRecords = Convert.ToInt32(_Work1doc.DocumentNode.SelectNodes("//div[@id=\"productsListingTopNumber\"]//strong")[2].InnerText);
if ((_TotalRecords % 60) == 0)
{
_Pages = Convert.ToInt32(_TotalRecords / 60);
}
else
{
_Pages = Convert.ToInt32(_TotalRecords / 60) + 1;
}
for (int i = 1; i <= _Pages; i++)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
tim(2);
if (!_Work.IsBusy)
{
Url1 = _ScrapeUrl + "&page=" + i;
_Work.RunWorkerAsync();
}
else
{
Url2 = _ScrapeUrl + "&page=" + i;
_Work1.RunWorkerAsync();
}
tim(2);
tim(2);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
gridindex = 0;
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_Chillyindex = 0;
_lblerror.Text = "We are going to read Decsription and Bullets information from product page of " + chkstorelist.Items[0].ToString() + " Website";
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
_IsCategory = false;
tim(3);
totalrecord.Visible = true;
Products = (Products.GroupBy(x => x.URL).Select(y => y.FirstOrDefault())).ToList();
totalrecord.Text = "Total Products :" + Products.Count.ToString();
int Counter = 0;
foreach (BusinessLayer.Product _Row in Products)
{
while (_Work.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
_Iscompleted = false;
_Description1 = "";
Bullets = "";
Category = "";
Weight = 0;
Url1 = _Row.URL;
_Work.RunWorkerAsync();
while (!_Iscompleted)
{
Application.DoEvents();
}
if (_Description1.Replace("\r", "").Replace("\n", "").Trim() == "")
_Row.Description = _Row.Name;
else
_Row.Description = _Description1.Replace("\r", "").Replace("\n", "").Trim();
if (Bullets.Replace("\r", "").Replace("\n", "").Trim() == "")
_Row.Bulletpoints1 = _Row.Name;
else
_Row.Bulletpoints1 = Bullets.Replace("\r", "").Replace("\n", "").Trim();
_Row.Category = Category;
_Row.Weight = Weight;
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_lblerror.Visible = true;
_lblerror.Text = "All Products Scrapped for " + chkstorelist.Items[0].ToString() + " Website";
#region InsertScrappedProductInDatabase
if (Products.Count() > 0)
{
gridindex = 0;
foreach (BusinessLayer.Product prd in Products)
{
int index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[1].Value = prd.SKU;
dataGridView1.Rows[index].Cells[2].Value = prd.Name;
dataGridView1.Rows[index].Cells[3].Value = prd.Description;
dataGridView1.Rows[index].Cells[4].Value = prd.Bulletpoints;
dataGridView1.Rows[index].Cells[5].Value = prd.Manufacturer;
dataGridView1.Rows[index].Cells[6].Value = prd.Brand;
dataGridView1.Rows[index].Cells[7].Value = prd.Price;
dataGridView1.Rows[index].Cells[8].Value = prd.Currency;
dataGridView1.Rows[index].Cells[9].Value = prd.Stock;
dataGridView1.Rows[index].Cells[10].Value = prd.Image;
dataGridView1.Rows[index].Cells[11].Value = prd.URL;
dataGridView1.Rows[index].Cells[12].Value = prd.Size;
dataGridView1.Rows[index].Cells[13].Value = prd.Color;
dataGridView1.Rows[index].Cells[14].Value = prd.Isparent;
dataGridView1.Rows[index].Cells[15].Value = prd.parentsku;
dataGridView1.Rows[index].Cells[16].Value = prd.Bulletpoints1;
dataGridView1.Rows[index].Cells[17].Value = prd.Bulletpoints2;
dataGridView1.Rows[index].Cells[18].Value = prd.Bulletpoints3;
dataGridView1.Rows[index].Cells[19].Value = prd.Bulletpoints4;
dataGridView1.Rows[index].Cells[20].Value = prd.Bulletpoints5;
dataGridView1.Rows[index].Cells[21].Value = prd.Category;
dataGridView1.Rows[index].Cells[22].Value = prd.Weight;
dataGridView1.Rows[index].Cells[23].Value = prd.Style;
dataGridView1.Rows[index].Cells[24].Value = prd.Shipping;
}
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
_Prd.ProductDatabaseIntegration(Products, chkstorelist.Items[0].ToString(), 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='" + chkstorelist.Items[0].ToString() + "'");
_Mail.SendMail("OOPS there is no any product scrapped by app for " + chkstorelist.Items[0].ToString() + " Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#endregion InsertScrappedProductInDatabase
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='" + chkstorelist.Items[0].ToString() + "'");
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for " + chkstorelist.Items[0].ToString() + " Website";
/****************Email****************/
_Mail.SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for " + chkstorelist.Items[0].ToString() + " Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
/*******************End********/
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='" + chkstorelist.Items[0].ToString() + "'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data " + chkstorelist.Items[0].ToString() + " Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
Disableallstores();
}
# endregion warrior
#region chilly
if (chkstorelist.GetItemChecked(1))
{
_Chillyindex = 0;
_Name.Clear();
gridindex = dataGridView1.Rows.Count;
if (gridindex == 1)
{
if (dataGridView1.Rows[0].Cells[1].Value == null || dataGridView1.Rows[0].Cells[1].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[0].Cells[1].Value.ToString()))
{
gridindex = 0;
}
}
else
{
gridindex = gridindex - 1;
}
_ProductUrl.Clear();
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
_IsCategory = true;
_ISchilychiles = true;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product Url for " + chkstorelist.Items[1].ToString() + " Website";
_ScrapeUrl = "http://chillychiles.com/collections/all";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
try
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"pagination\"]/span") != null)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"pagination\"]/span");
string test = _Collection[_Collection.Count - 1].InnerText;
_Pages = Convert.ToInt32(_Collection[_Collection.Count - 2].InnerText);
totalrecord.Visible = true;
totalrecord.Text = "Total Category :" + _Pages;
for (int i = 1; i <= _Pages; i++)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = _ScrapeUrl + "?page=" + i;
_Work.RunWorkerAsync();
}
else
{
Url2 = _ScrapeUrl + "?page=" + i;
_Work1.RunWorkerAsync();
}
break;
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
tim(2);
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product information of " + chkstorelist.Items[1].ToString() + " Website";
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
_IsCategory = false;
tim(3);
totalrecord.Visible = true;
totalrecord.Text = "Total Products :" + _ProductUrl.Count();
_Chillyindex = 0;
int counter = 0;
//_ProductUrl.Clear();
//_ProductUrl.Add("http://chillychiles.com/products/chile-habanero-whole");
// _ProductUrl.Add("http://chillychiles.com/products/ole-ray-s-sloppy-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/dallesandro-chipotle-peppers-in-adobo-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/sancto-scorpio-hot-sauce");
////_ProductUrl.Add("http://chillychiles.com//products/historic-lynchburg-tennessee-whiskey-jalapeno-cocktail-sauce");
//_ProductUrl.Add("http://chillychiles.com//products/daves-gourmet-6-pure-dried-chiles");
//_ProductUrl.Add("http://chillychiles.com//products/tabasco-sweet-and-spicy-pepper-sauce");
//_ProductUrl.Add("http://chillychiles.com//products/tabasco-chipotle-pepper-sauce-1");
// _ProductUrl.Add("http://chillychiles.com//products/georgia-peach-and-vidalia-onion-hot-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/crabanero-hot-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/the-torture-trio-3-pack");
// _ProductUrl.Add("http://chillychiles.com//products/daves-gourmet-whole-ghost-peppers");
// _ProductUrl.Add("http://chillychiles.com//products/hoboken-eddies-apple-brandy-bbq-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/historic-lynchburg-tennessee-whiskey-diabetic-friendly-mild-gourmet-deli-grillin-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/historic-lynchburg-tennessee-whiskey-diabetic-friendly-hot-spicy-bbq");
// _ProductUrl.Add("http://chillychiles.com//products/tabasco-raspberry-chipotle-hot-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/tabasco-flavoured-jelly-belly-jelly-beans");
// _ProductUrl.Add("http://chillychiles.com//products/ass-in-hell-hot-sauce");
// _ProductUrl.Add("http://chillychiles.com//products/ole-rays-red-delicious-apple-bourbon-bbq-and-cooking-sauce");
foreach (string Url in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Url;
_Work.RunWorkerAsync();
}
else
{
Url2 = Url;
_Work1.RunWorkerAsync();
}
counter++;
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
}
else
{
_lblerror.Visible = true;
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for " + chkstorelist.Items[1].ToString() + " Website";
/****************Email****************/
SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for " + chkstorelist.Items[1].ToString() + " Website" + DateTime.Now.ToString(), "Urgenr issue in Scrapper.", false, false);
/*******************End********/
}
}
catch
{
_lblerror.Visible = true;
_lblerror.Text = "Oops Some issue Occured in scrapping data " + chkstorelist.Items[1].ToString() + " Website";
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
Disableallstores();
}
# endregion chilly
#region airsoft
if (chkstorelist.GetItemChecked(2))
{
_Name.Clear();
gridindex = dataGridView1.Rows.Count;
if (gridindex == 1)
{
if (dataGridView1.Rows[0].Cells[1].Value == null || dataGridView1.Rows[0].Cells[1].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[0].Cells[1].Value.ToString()))
{
gridindex = 0;
}
}
else
{
gridindex = gridindex - 1;
}
_Chillyindex = 0;
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_ProductUrl.Clear();
_Bar1.Value = 0;
_percent.Visible = false;
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
_IsCategory = false;
_Issubcat = true;
_IsAirsoft = true;
_ScrapeUrl = "https://www.buyairsoft.ca/";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
/***************Code to read Parent category Url*********************/
if (_Work1doc.DocumentNode.SelectNodes("//div[@id=\"top-nav\"]/ul/li/a") != null)
{
#region category
foreach (HtmlNode _node in _Work1doc.DocumentNode.SelectNodes("//div[@id=\"top-nav\"]/ul/li/a"))
{
foreach (HtmlAttribute _Att in _node.Attributes)
{
if (_Att.Name.ToLower() == "href")
CategoryUrl.Add(_Att.Value);
}
}
_lblerror.Visible = true;
_lblerror.Text = "We are going to read Sub category Url for " + chkstorelist.Items[2].ToString() + " Website";
totalrecord.Visible = true;
totalrecord.Text = "Total Parent Category :" + CategoryUrl.Count();
foreach (string subcaturl in CategoryUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = subcaturl;
_Work.RunWorkerAsync();
}
else
{
Url2 = subcaturl;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (!SubCategoryUrl.Contains("https://www.buyairsoft.ca/deals/refurbished.html?limit=all"))
{
SubCategoryUrl.Add("https://www.buyairsoft.ca/deals/refurbished.html?limit=all");
}
tim(3);
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product Url for " + chkstorelist.Items[2].ToString() + " Website";
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
totalrecord.Visible = true;
totalrecord.Text = "Total Sub Categories :" + SubCategoryUrl.Count();
_Chillyindex = 0;
CategoryUrl.Clear();
_Issubcat = false;
_IsCategory = true;
#endregion category
#region sub category
foreach (string subcaturl in SubCategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = subcaturl;
_Work.RunWorkerAsync();
}
else
{
Url2 = subcaturl;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion subcategory
#region Productpage
tim(3);
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product Information for " + chkstorelist.Items[2].ToString() + " Website";
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
totalrecord.Visible = true;
totalrecord.Text = "Total :" + _ProductUrl.Count();
_Chillyindex = 0;
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_Issubcat = false;
_IsCategory = false;
foreach (string url in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url;
_Work.RunWorkerAsync();
}
else
{
Url2 = url;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion productpage
tim(2);
Disableallstores();
}
else
{
_lblerror.Visible = true;
_lblerror.Text = "Oops Some issue Occured in scrapping data " + chkstorelist.Items[2].ToString() + " Website";
/****************Email****************/
SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for " + chkstorelist.Items[2].ToString() + " Website" + DateTime.Now.ToString(), "Urgenr issue in Scrapper.", false, false);
/*******************End********/
}
/*************************End**************************************/
}
#endregion airsoft
#region Knife
if (chkstorelist.GetItemChecked(3))
{
_Name.Clear();
gridindex = dataGridView1.Rows.Count;
if (gridindex == 1)
{
if (dataGridView1.Rows[0].Cells[1].Value == null || dataGridView1.Rows[0].Cells[1].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[0].Cells[1].Value.ToString()))
{
gridindex = 0;
}
}
else
{
gridindex = gridindex - 1;
}
_Chillyindex = 0;
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_ProductUrl.Clear();
_Bar1.Value = 0;
_percent.Visible = false;
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
_IsCategory = true;
_Issubcat = false;
_IsProduct = false;
_IsKnifezone = true;
_ScrapeUrl = "http://www.knifezone.ca/";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
#region category
if (_Work1doc.DocumentNode.SelectNodes("//font") != null)
{
bool _CategoryDiv = false;
foreach (HtmlNode _Node in _Work1doc.DocumentNode.SelectNodes("//font"))
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "size")
{
if (_Att.Value == "-1")
_CategoryDiv = true;
}
}
if (_CategoryDiv)
{
if (_Node.SelectNodes("a") != null)
{
foreach (HtmlNode _Node1 in _Node.SelectNodes("a"))
{
foreach (HtmlAttribute _Att in _Node1.Attributes)
{
if (_Att.Name.ToLower() == "href")
{
string _Indexurl = _Att.Value;
try
{
if (_Indexurl.Contains("../"))
{
_Indexurl = _Indexurl.Replace("../", "");
_Indexurl = _Indexurl.Substring(0, _Indexurl.IndexOf("/"));
_Indexurl = _Indexurl + "/index.htm";
}
else
{
_Indexurl = Reverse(_Indexurl);
_Indexurl = _Indexurl.Substring(_Indexurl.IndexOf("/"));
_Indexurl = Reverse(_Indexurl) + "/index.htm";
}
}
catch
{
_Indexurl = _Att.Value;
}
CategoryUrl.Add("http://www.knifezone.ca/" + _Indexurl);
}
}
}
}
else
{
_CategoryDiv = false;
}
}
if (_CategoryDiv)
break;
}
_lblerror.Visible = true;
CategoryUrl.Remove("http://www.knifezone.ca/specials//index.htm");
CategoryUrl.Add("http://www.knifezone.ca/grohmannoutdoor/index.htm");
CategoryUrl.Add("http://www.knifezone.ca/grohmannkitchenpoly/index.htm");
CategoryUrl.Add("http://www.knifezone.ca/grohmannkitchenregular/index.htm");
CategoryUrl.Add("http://www.knifezone.ca/grohmannkitchenfulltang/index.htm");
CategoryUrl.Add("http://www.knifezone.ca/grohmannkitchenforged/index.htm");
_lblerror.Text = "We are going to read Product Url for " + chkstorelist.Items[3].ToString() + " Website";
#endregion category
totalrecord.Visible = true;
totalrecord.Text = "Total Categories :" + CategoryUrl.Count();
#region ProductURL
foreach (string caturl in CategoryUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = caturl;
_Work.RunWorkerAsync();
}
else
{
Url2 = caturl;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion Producturl
#region productinformation
tim(3);
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product Information for " + chkstorelist.Items[3].ToString() + " Website";
_Pages = 0;
_TotalRecords = 0;
_Stop = false;
time = 0;
totalrecord.Visible = true;
totalrecord.Text = "Total :" + _ProductUrl.Count();
_Chillyindex = 0;
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_Issubcat = false;
_IsCategory = false;
_Chillyindex = 0;
//_ProductUrl.Clear();
// _ProductUrl.Add("http://www.knifezone.ca/grohmannoutdoor/originalwaterbuffalo.htm");
//_ProductUrl.Add("http://www.knifezone.ca/crkt/firesparkknife.htm");
//_ProductUrl.Add("http://www.knifezone.ca/coldsteel/tiliteswitchblade.htm");
foreach (string Prdurl in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Prdurl;
_Work.RunWorkerAsync();
}
else
{
Url2 = Prdurl;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
Disableallstores();
}
else
{
SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for " + chkstorelist.Items[3].ToString() + " Website" + DateTime.Now.ToString(), "Urgenr issue in Scrapper.", false, false);
}
#endregion productinformation
}
#endregion knfie
//MessageBox.Show("Process Completed.");
Pause.Enabled = false;
Go.Enabled = true;
this.Close();
}
private void Pause_Click(object sender, EventArgs e)
{
if (Pause.Text.ToUpper() == "PAUSE")//for pause and resume process
{
_Stop = true;
Pause.Text = "RESUME";
}
else
{
_Stop = false;
Pause.Text = "Pause";
}
}
private void createcsvfile_Click(object sender, EventArgs e)
{
string Filename = "data" + DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "");
DataTable exceldt = new DataTable();
exceldt.Columns.Add("Rowid", typeof(int));
exceldt.Columns.Add("SKU", typeof(string));
exceldt.Columns.Add("Product Name", typeof(string));
exceldt.Columns.Add("Product Description", typeof(string));
exceldt.Columns.Add("Bullet Points", typeof(string));
exceldt.Columns.Add("Manufacturer", typeof(string));
exceldt.Columns.Add("Brand Name", typeof(string));
exceldt.Columns.Add("Price", typeof(string));
exceldt.Columns.Add("Currency", typeof(string));
exceldt.Columns.Add("In Stock", typeof(string));
exceldt.Columns.Add("Image URL", typeof(string));
exceldt.Columns.Add("Image URL1", typeof(string));
exceldt.Columns.Add("Image URL2", typeof(string));
for (int m = 0; m < dataGridView1.Rows.Count; m++)
{
exceldt.Rows.Add();
for (int n = 0; n < dataGridView1.Columns.Count - 1; n++)
{
if (dataGridView1.Rows[m].Cells[n].Value == null || dataGridView1.Rows[m].Cells[n].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[m].Cells[n].Value.ToString()))
continue;
if (n == 10)
{
string[] Images = dataGridView1.Rows[m].Cells[n].Value.ToString().Split('@');
try
{
exceldt.Rows[m][n] = Images[0];
}
catch
{
}
if (Images.Length > 1)
{
try
{
exceldt.Rows[m][n + 1] = Images[1];
}
catch
{
}
try
{
exceldt.Rows[m][n + 2] = Images[2];
}
catch
{
}
}
}
else
{
exceldt.Rows[m][n] = dataGridView1.Rows[m].Cells[n].Value.ToString();
}
}
}
try
{
using (CsvFileWriter writer = new CsvFileWriter(Application.StartupPath + "/" + Filename + ".txt"))
{
CsvFileWriter.CsvRow row = new CsvFileWriter.CsvRow();//HEADER FOR CSV FILE
row.Add("SKU");
row.Add("Product Name");
row.Add("Product Description");
row.Add("Bullet Points");
row.Add("Manufacturer");
row.Add("Brand Name");
row.Add("Price");
row.Add("Currency");
row.Add("In Stock");
row.Add("Image URL");
row.Add("Image URL1");
row.Add("Image URL2");
writer.WriteRow(row);//INSERT TO CSV FILE HEADER
for (int m = 0; m < exceldt.Rows.Count; m++)
{
CsvFileWriter.CsvRow row1 = new CsvFileWriter.CsvRow();
for (int n = 1; n < exceldt.Columns.Count; n++)
{
row1.Add(String.Format("{0}", exceldt.Rows[m][n].ToString().Replace("\n", "").Replace("\r", "").Replace("\t", "")));
}
writer.WriteRow(row1);
}
}
System.Diagnostics.Process.Start(Application.StartupPath + "/" + Filename + ".txt");//OPEN THE CSV FILE ,,CSV FILE NAMED AS DATA.CSV
}
catch (Exception) { MessageBox.Show("file is already open\nclose the file"); }
return;
}
public class CsvFileWriter : StreamWriter //Writing data to CSV
{
public CsvFileWriter(Stream stream)
: base(stream)
{
}
public CsvFileWriter(string filename)
: base(filename)
{
}
public class CsvRow : List<string> //Making each CSV rows
{
public string LineText { get; set; }
}
public void WriteRow(CsvRow row)
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in row)
{
builder.Append(value.Replace("\n", "") + "\t");
}
row.LineText = builder.ToString();
WriteLine(row.LineText);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void totalrecord_Click(object sender, EventArgs e)
{
}
private void _percent_Click(object sender, EventArgs e)
{
}
private void Form1_Shown(object sender, EventArgs e)
{
base.Show();
this.Go_Click(null, null);
}
}
}
<file_sep>/Project 13 openaparty/palyerborndate/palyerborndate/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using bestbuy;
using System.Text.RegularExpressions;
using System.Net;
namespace palyerborndate
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region booltypevariable
bool _ISBuy = false;
bool _IsProduct = false;
bool _IsCategory = true;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
int gridindex = 0;
int time = 0;
#endregion booltypevariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
#endregion Buinesslayervariable
#region intypevariable
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&keyword=keywords&search_in_description=1&product_type=&kfi_blade_length_from=0&kfi_blade_length_to=15&kfi_overall_length_from=0&kfi_overall_length_to=30&kfi_serration=ANY&kfi_is_coated=ANY&kfo_blade_length_from=0&kfo_blade_length_to=8&kfo_overall_length_from=0&kfo_overall_length_to=20&kfo_serration=ANY&kfo_is_coated=ANY&kfo_assisted=ANY&kk_blade_length_from=0&kk_blade_length_to=15&fl_lumens_from=0&fl_lumens_to=18000&fl_num_cells_from=1&fl_num_cells_to=10&fl_num_modes_from=1&fl_num_modes_to=15&sw_blade_length_from=0&sw_blade_length_to=60&sw_overall_length_from=0&sw_overall_length_to=70&inc_subcat=1&pfrom=0.01&pto=10000.00&x=36&y=6&perPage=60";
string Category1 = "";
string Category2 = "";
decimal Weight = 0;
#endregion listtypevariable
#region listtypevariable
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
ExtendedWebClient _Client2 = new ExtendedWebClient();
ExtendedWebClient _Client1 = new ExtendedWebClient();
ExtendedWebClient _Client3 = new ExtendedWebClient();
ExtendedWebClient _Client4 = new ExtendedWebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
StreamWriter writer = new StreamWriter(Application.StartupPath + "/log.txt");
#endregion htmlagility
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void Form1_Load(object sender, EventArgs e)
{
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
/****************BackGround worker *************************/
}
public void tim(int t)
{
time = 0;
timer1.Start();
try
{
while (time <= t)
{
Application.DoEvents();
}
}
catch (Exception) { }
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
time++;
}
public void GetCategoryInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string Category)
{
HtmlNodeCollection coll = _doc.DocumentNode.SelectNodes("//table[@class=\"productListingData\"]");
if (coll != null)
{
foreach (HtmlNode node4 in coll)
{
HtmlNodeCollection coll1 = node4.SelectNodes(".//li");
if (coll1 != null)
{
foreach (HtmlNode node in coll1)
{
HtmlNodeCollection coll2 = node.SelectNodes(".//a");
if (coll2 != null)
{
foreach (HtmlNode node1 in coll2)
{
foreach (HtmlAttribute attr in node1.Attributes)
{
if (attr.Name == "href")
{
try
{
_ProductUrl.Add(attr.Value, Category);
}
catch
{
}
}
}
break;
}
}
}
}
}
}
else
WriteLogEvent(url, "h2[@class=\"product-name\"]/a tag is not found");
}
public void GetProductInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string Category)
{
BusinessLayer.Product product = new BusinessLayer.Product();
try
{
#region title price
HtmlNodeCollection formColl = _doc.DocumentNode.SelectNodes("//div[@id=\"bodyContent\"]");
if (formColl != null)
{
if (formColl[0].SelectNodes(".//h1") != null)
{
int Counter = 0;
foreach (HtmlNode node in formColl[0].SelectNodes(".//h1"))
{
if (Counter == 0)
{
decimal Price = 0;
decimal.TryParse(node.InnerText.ToLower().Replace("$", "").Replace("ca", "").Trim(), out Price);
product.Price = Price.ToString();
if (Price == 0)
{
product.Price = "0";
WriteLogEvent(url, "Price not found");
}
}
else
product.Name = System.Net.WebUtility.HtmlDecode(node.InnerText.Trim());
Counter++;
if (product.Price == "0")
break;
}
}
else
WriteLogEvent(url, "title not found");
#endregion title price
#region Brand
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "<NAME>";
#endregion Brand
#region Category
product.Category = Category;
#endregion Category
product.Currency = "CAD";
#region description
string Description = "";
HtmlNodeCollection desCollection = _doc.DocumentNode.SelectNodes("//div[@class=\"contentText\"]");
if (desCollection != null)
{
foreach (HtmlNode node in desCollection[0].ChildNodes)
{
if (!node.InnerText.ToLower().Contains("wholesale") && !node.InnerText.ToLower().Contains("$") && !node.InnerText.ToLower().Contains("http"))
Description = Description + Removeunsuaalcharcterfromstring(StripHTML(node.InnerText).Trim() + " ");
}
Description = Removeunsuaalcharcterfromstring(StripHTML(Description).Trim()).Replace("httpwww.partysavvy.co.uk", "").Replace("httpwww.openparty.com", "");
try
{
if (Description.Length > 2000)
Description = Description.Substring(0, 1997) + "...";
}
catch
{
}
product.Description = System.Net.WebUtility.HtmlDecode(Description.Replace("Â", ""));
}
else
WriteLogEvent(url, "Description not found");
#endregion description
#region BulletPoints
if (string.IsNullOrEmpty(product.Description))
{
product.Description = product.Name;
if (string.IsNullOrEmpty(product.Bulletpoints1))
product.Bulletpoints1 = product.Name;
}
else if (string.IsNullOrEmpty(product.Bulletpoints1))
{
if (product.Description.Length >= 500)
product.Bulletpoints1 = product.Description.Substring(0, 497);
else
product.Bulletpoints1 = product.Description;
}
#endregion BulletPoints
#region Image
string Images = "";
HtmlNodeCollection imgCollection = _doc.DocumentNode.SelectNodes("//div[@id=\"piGal\"]");
if (imgCollection != null)
{
HtmlNodeCollection imgCollection1 = imgCollection[0].SelectNodes(".//a");
foreach (HtmlNode node in imgCollection1)
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "href")
Images = Images + attr.Value.Trim() + ",";
}
break;
}
}
else
WriteLogEvent(url, "Main Images not found");
if (Images.Length > 0)
Images = Images.Substring(0, Images.Length - 1);
product.Image = Images;
#endregion Image
product.Isparent = true;
#region sku
if (_doc.DocumentNode.SelectNodes("//input[@name=\"products_id\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//input[@name=\"products_id\"]")[0].Attributes)
{
if (attr.Name == "value")
{
product.SKU = "OPAR" + attr.Value.Trim();
product.parentsku = "OPAR" + attr.Value.Trim();
}
}
}
else
WriteLogEvent(url, "SKU not found");
#endregion sku
#region stock
product.Stock = "1";
#endregion stock
product.URL = url;
Products.Add(product);
}
else
WriteLogEvent(url, "Issue accured in reading product info from given product url. exp: ");
}
catch (Exception exp)
{
WriteLogEvent(url, "Issue accured in reading product info from given product url. exp: " + exp.Message);
}
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public string GetUPC(string Response)
{
string Result = "";
foreach (var ch in Response.ToCharArray())
{
if (char.IsNumber(ch))
Result = Result + ch;
else
break;
}
Int64 n;
bool isNumeric = Int64.TryParse(Result, out n);
if (n != 0)
return Result;
else
return "";
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public void WriteLogEvent(string url, string Detail)
{
writer.WriteLine(Detail + "/t" + url);
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url1, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc, Url1, Category1);
#region GetcategoryPaging
try
{
List<string> subcat = new List<string>();
HtmlNodeCollection coll = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"contentContainer\"]/table");
if (coll == null)
coll = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"contentContainer\"]/div[@class=\"contentText\"]/table");
if (coll != null)
{
HtmlNodeCollection subCat = coll[0].SelectNodes(".//a");
if (subCat != null)
{
foreach (HtmlNode node in subCat)
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "href")
{
subcat.Add(attr.Value);
}
}
}
}
}
else
WriteLogEvent(Url1, "Issue accured in getting total No of products in given category");
foreach (string subCatUrl in subcat)
{
do
{
try
{
counterReload++;
_Work1doc.LoadHtml(_Client1.DownloadString(subCatUrl));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (!_Iserror)
GetCategoryInfo(_Work1doc, subCatUrl, Category1);
}
}
catch
{
WriteLogEvent(Url1, "Issue accured in getting total No of products in given category");
}
#endregion GetcategoryPaging
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading produts from category page"); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / CategoryUrl.Count));
/****************end*******************/
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc, Url1, Category1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading product Info."); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / _ProductUrl.Count));
/****************end*******************/
}
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url2, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc2, Url2, Category2);
#region GetcategoryPaging
try
{
List<string> subcat = new List<string>();
HtmlNodeCollection coll = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"contentContainer\"]/table");
if (coll == null)
coll = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"contentContainer\"]/div[@class=\"contentText\"]/table");
if (coll != null)
{
HtmlNodeCollection subCat = coll[0].SelectNodes(".//a");
if (subCat != null)
{
foreach (HtmlNode node in subCat)
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "href")
{
subcat.Add(attr.Value);
}
}
}
}
}
else
WriteLogEvent(Url2, "Issue accured in getting total No of products in given category");
foreach (string subCatUrl in subcat)
{
counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc2.LoadHtml(_Client2.DownloadString(subCatUrl));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (!_Iserror)
GetCategoryInfo(_Work1doc2, subCatUrl, Category2);
}
}
catch
{
WriteLogEvent(Url2, "Issue accured in getting total No of products in given category");
}
#endregion GetcategoryPaging
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading produts from category page"); }
/**********Report progress**************/
gridindex++;
_Work1.ReportProgress((gridindex * 100 / CategoryUrl.Count));
/****************end*******************/
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc2, Url2, Category2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading product Info."); }
/**********Report progress**************/
gridindex++;
_Work1.ReportProgress((gridindex * 100 / _ProductUrl.Count));
/****************end*******************/
}
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
private void Go_Click(object sender, EventArgs e)
{
_IsProduct = false;
_percent.Visible = false;
_Bar1.Value = 0;
_lblerror.Visible = false;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
#region openaparty.com
_ISBuy = true;
_ScrapeUrl = "http://www.openaparty.com/applications/Category/guidedSearch.asp?CatId=12&cm_re=Homepage-_--_-CatId_12";
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category Link for openaparty.com Website";
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-all-foil-and-latex-balloons-colour-c-879_1688_999#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-balloon-weights-c-879_1688_1173#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-balloon-bouquets-c-879_1688_1160#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-foil-and-latex-french-balloons-c-879_1688_1169#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-happy-birthday-foil-balloons-c-879_1688_1182#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-happy-birthday-latex-balloons-c-879_1688_1166#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-jumbo-letter-foils-c-879_1688_1181#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-jumbo-number-foil-balloons-c-879_1688_1180#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-latex-and-foil-age-balloons-c-879_1688_1175#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-patterned-latex-balloons-c-879_1688_1172#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/all-balloons-curling-ribbon-c-879_1688_1191#bc", "OPAR200 balloons");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-crayons-c-943_1270_1357#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-pens-c-943_1270_1355#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-erasers-sharpeners-toppers-grips-c-943_1270_1586#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-pencils-pencil-crayons-c-943_1270_1356#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-stationary-sets-c-943_1270_1739#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-stencils-c-943_1270_1732#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-stickers-sticker-scenes-c-943_1270_1361#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-paper-c-943_1270_1595#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/school-supplies-stationary-products-dry-erase-products-c-943_1270_1360#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/teaching-category-classroom-pocket-charts-c-943_1666_1261#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/teaching-category-dry-erase-supplies-and-tools-c-943_1666_1260#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/teaching-category-reading-corner-supplies-c-943_1666_1596#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/teaching-subject-language-arts-and-literacy-supplies-c-943_1667_1669#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/teaching-resources-crafts-and-supplies-classroom-themes-c-943_1587#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/teaching-resources-crafts-and-supplies-classroom-crafts-c-943_1364#bc", "OPAR200 Crafts and supplies");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/200-filled-loot-boxes-c-70#bc", "OPAR200 Filled Loot Boxes");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/5000-novelty-toys-c-474#bc", "OPAR200 Filled Loot Boxes");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/200-filled-loot-boxes-100s-empty-loot-boxes-c-70_948", "OPAR200 Filled Loot Boxes");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/200-filled-loot-boxes-100s-favor-pails-and-buckets-c-70_950", "OPARBuckets and Pails");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/200-filled-loot-boxes-100s-gift-and-favor-bags-c-70_947", "OPARGift And Favor Bags");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/200-filled-loot-boxes-cool-popcorn-treat-boxes-c-70_949", "OPARPopcorn Treat Boxes");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/party-decorations-and-balloons-designer-straws-c-879_1255#bc", "OPARDesigner Straws");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/solid-colour-and-patterned-partyware-c-879_880#bc", "OPARSolid Colour and Patterned Partyware");
CategoryUrl.Add("http://openaparty.com/open-a-party-shop/index.php/party-decorations-and-balloons-cake-candles-c-879_881#bc", "OPARCandles");
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (CategoryUrl.Count() > 0)
{
gridindex = 0;
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read products from category page.";
_Stop = false;
time = 0;
_IsCategory = true;
tim(3);
totalrecord.Visible = true;
totalrecord.Text = "Total No Pages :" + CategoryUrl.Count.ToString();
foreach (var url in CategoryUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key;
Category1 = url.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
Category2 = url.Value;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product info.";
_IsCategory = false;
_IsProduct = true;
gridindex = 0;
totalrecord.Text = "Total No Products :" + _ProductUrl.Count.ToString();
foreach (var url in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key;
Category1 = url.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
Category2 = url.Value;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#region InsertScrappedProductInDatabase
if (Products.Count() > 0)
{
_Prd.ProductDatabaseIntegration(Products, "openaparty.com", 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='openaparty.com'");
_Prd.ProductDatabaseIntegration(Products, "openaparty.com", 1);
_Mail.SendMail("OOPS there is no any product scrapped by app for openaparty.com Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#endregion InsertScrappedProductInDatabase
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Prd.ProductDatabaseIntegration(Products, "openaparty.com", 1);
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='openaparty.com'");
_lblerror.Text = "Oops there is change in html code on client side. You need to contact with developer in order to check this issue for openaparty.com Website";
/****************Email****************/
_Mail.SendMail("Oops there is change in html code on client side. You need to contact with developer in order to check this issue for openaparty.com Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
/*******************End********/
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='openaparty.com'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data openaparty.com Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
# endregion openaparty.com
writer.Close();
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Form1_Shown(object sender, EventArgs e)
{
base.Show();
this.Go_Click(null, null);
}
}
public class ExtendedWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = 120000;
return w;
}
}
}
<file_sep>/Project9-scubagearcanada/Crawler_WithouSizes_Part3/Crawler_WithouSizes_Part3/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using Crawler_WithouSizes_Part7;
using System.Xml;
using Newtonsoft.Json;
using WatiN.Core;
namespace Crawler_WithouSizes_Part3
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
StreamWriter _writer = new StreamWriter(Application.StartupPath + "/test.csv");
#region ClassTypeVariable
List<Crawler_WithouSizes_Part7.BusinessLayer.Product> Worker1Products = new List<Crawler_WithouSizes_Part7.BusinessLayer.Product>();
List<Crawler_WithouSizes_Part7.BusinessLayer.Product> Worker2Products = new List<Crawler_WithouSizes_Part7.BusinessLayer.Product>();
List<string> Url = new List<string>();
#endregion ClassTypeVariable
#region booltypevariable
bool _ISscubagearcanada = true;
bool _IsProduct = false;
bool _IsCategory = true;
bool _IsCategorypaging = false;
bool _Stop = false;
bool Erorr_scubagearcanada1 = true;
bool Erorr_scubagearcanada2 = true;
#endregion booltypevariable
#region datatable
DataTable _TableWork1 = new DataTable();
DataTable _TableWork2 = new DataTable();
#endregion datatable
#region IeVariable
IE _Worker1 = null;
IE _Worker2 = null;
#endregion IeVariable
#region intypevariable
int gridindex = 0;
int _Saleeventindex = 0;
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string BrandName1 = "";
string BrandName2 = "";
string _ScrapeUrl = "";
string Bullets = "";
string _Description1 = "";
string _Description2 = "";
#endregion listtypevariable
#region listtypevariable
List<string> ProductName = new List<string>();
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
Dictionary<string, string> _ProductUrl = new Dictionary<string, string>();
List<string> Skus = new List<string>();
List<string> _Name = new List<string>();
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> SubCategoryUrl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
DataTable _Tbale = new DataTable();
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
#region Datacolumn
DataColumn _ColPrice = new DataColumn();
_ColPrice.ColumnName = "Price";
_ColPrice.DataType = Type.GetType("System.String");
_TableWork1.Columns.Add(_ColPrice);
DataColumn _ColSku = new DataColumn();
_ColSku.ColumnName = "sku";
_ColSku.DataType = Type.GetType("System.String");
_TableWork1.Columns.Add(_ColSku);
DataColumn _ColColor = new DataColumn();
_ColColor.ColumnName = "Color";
_ColColor.DataType = Type.GetType("System.String");
_TableWork1.Columns.Add(_ColColor);
DataColumn _Colsize = new DataColumn();
_Colsize.ColumnName = "size";
_Colsize.DataType = Type.GetType("System.String");
_TableWork1.Columns.Add(_Colsize);
DataColumn _ColStock = new DataColumn();
_ColStock.ColumnName = "Stock";
_ColStock.DataType = Type.GetType("System.String");
_TableWork1.Columns.Add(_ColStock);
_TableWork2 = _TableWork1.Clone();
#endregion Datacolumn
}
public void DisplayRecordProcessdetails(string Message, string TotalrecordMessage)
{
_lblerror.Visible = true;
_lblerror.Text = Message;
totalrecord.Visible = true;
totalrecord.Text = TotalrecordMessage;
}
public void Process()
{
_IsProduct = false;
_Name.Clear();
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_ProductUrl.Clear();
_percent.Visible = false;
_Bar1.Value = 0;
_Url.Clear();
_Tbale.Rows.Clear();
_Tbale.Columns.Clear();
dataGridView1.Rows.Clear();
DataColumn _Dc = new DataColumn();
_Dc.ColumnName = "Rowid";
_Dc.AutoIncrement = true;
_Dc.DataType = typeof(int);
_Dc.AutoIncrementSeed = 1;
_Dc.AutoIncrementStep = 1;
_Tbale.Columns.Add(_Dc);
_Tbale.Columns.Add("SKU", typeof(string));
_Tbale.Columns.Add("Product Name", typeof(string));
_Tbale.Columns.Add("Product Description", typeof(string));
_Tbale.Columns.Add("Bullet Points", typeof(string));
_Tbale.Columns.Add("Manufacturer", typeof(string));
_Tbale.Columns.Add("Brand Name", typeof(string));
_Tbale.Columns.Add("Price", typeof(string));
_Tbale.Columns.Add("Currency", typeof(string));
_Tbale.Columns.Add("In Stock", typeof(string));
_Tbale.Columns.Add("Image URL", typeof(string));
_Tbale.Columns.Add("URL", typeof(string));
_lblerror.Visible = false;
gridindex = 0;
_IsCategory = true;
_Stop = false;
#region scubagearcanada
_ISscubagearcanada = true;
_ScrapeUrl = "http://www.scubagearcanada.ca/";
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category url for " + chkstorelist.Items[0].ToString() + " Website";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _Collection = null;
_Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"sf-horizontal category-list treeview\"]/li");
if (_Collection == null)
_Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"sf-menu sf-horizontal\"]/li");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
try
{
HtmlAttributeCollection _AttributeCollection = _Node.SelectNodes(".//a")[0].Attributes;
foreach (HtmlAttribute _Attribute in _AttributeCollection)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_Node.SelectNodes(".//a")[0].InnerText.ToLower().StartsWith("all") && _Attribute.Value.Trim().Length > 0 && _Attribute.Value != "#")
{
try
{
CategoryUrl.Add(_Attribute.Value, _Node.SelectNodes(".//a")[0].InnerText.Trim());
}
catch
{
}
}
}
}
}
catch
{
}
Recusion(_Node);
}
}
// CategoryUrl.Clear();
if (CategoryUrl.Count() > 0)
{
#region Category
//DisplayRecordProcessdetails("We are going to read paging from category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
//_IsCategorypaging = true;
//foreach (var Caturl in CategoryUrl)
//{
// while (_Work.IsBusy || _Work1.IsBusy)
// {
// Application.DoEvents();
// }
// while (_Stop)
// {
// Application.DoEvents();
// }
// if (!_Work.IsBusy)
// {
// Url1 = Caturl.Key;
// BrandName1 = Caturl.Value;
// _Work.RunWorkerAsync();
// }
// else
// {
// Url2 = Caturl.Key;
// BrandName2 = Caturl.Value;
// _Work1.RunWorkerAsync();
// }
//}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion Category
#region ProductUrl
System.Threading.Thread.Sleep(1000);
_Bar1.Value = 0;
_Saleeventindex = 0;
_IsCategorypaging = false;
_IsCategory = true;
SubCategoryUrl = CategoryUrl;
DisplayRecordProcessdetails("We are going to read Product url for " + chkstorelist.Items[0].ToString() + " Website", "Total category url :" + SubCategoryUrl.Count());
foreach (var CatUrl in SubCategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
BrandName1 = CatUrl.Value;
Url1 = CatUrl.Key;
_Work.RunWorkerAsync();
}
else
{
BrandName2 = CatUrl.Value;
Url2 = CatUrl.Key;
_Work1.RunWorkerAsync();
}
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion ProductUrl
#region ProductInformation
_Bar1.Value = 0;
System.Threading.Thread.Sleep(1000);
_Saleeventindex = 0;
_IsCategory = false;
_IsProduct = true;
DisplayRecordProcessdetails("We are going to read Product Information for " + chkstorelist.Items[0].ToString() + " Website", "Total Products :" + _ProductUrl.Count());
#region iebrowser intialization
_Worker1 = new IE();
_Worker2 = new IE();
//_Worker1.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Hide);
//_Worker2.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Hide);
////_ProductUrl.Add("http://scubagearcanada.ca/gomask-for-gopro-original/#.VkteD9zyHIU", "");
////_ProductUrl.Add("http://scubagearcanada.ca/akona-armoretex-kevlar-5mm-glove/#.Vkt5atzyHIU", "");
////_ProductUrl.Add("http://scubagearcanada.ca/ultra-quick-dry-towel/#.Vkt7UdzyHIU", "");
//_ProductUrl.Add("http://scubagearcanada.ca/ultra-quick-dry-towel/#.Vky4dNzyHIV", "");
//_ProductUrl.Add("http://scubagearcanada.ca/akona-armoretex-kevlar-5mm-glove/#.Vkt5atzyHIU", "");
#endregion iebrowser intialization
foreach (var PrdUrl in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
BrandName1 = PrdUrl.Value;
Url1 = PrdUrl.Key;
_Work.RunWorkerAsync();
}
else
{
BrandName2 = PrdUrl.Value;
Url2 = PrdUrl.Key;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_Worker1.Close();
_Worker2.Close();
#region InsertdataIngrid
foreach (Crawler_WithouSizes_Part7.BusinessLayer.Product prd in Worker1Products)
{
if (prd.Name.Trim().Length > 0)
{
int index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[1].Value = prd.SKU;
dataGridView1.Rows[index].Cells[2].Value = prd.Name;
dataGridView1.Rows[index].Cells[3].Value = prd.Description;
dataGridView1.Rows[index].Cells[4].Value = prd.Bulletpoints;
dataGridView1.Rows[index].Cells[5].Value = prd.Manufacturer;
dataGridView1.Rows[index].Cells[6].Value = prd.Brand;
dataGridView1.Rows[index].Cells[7].Value = prd.Price;
dataGridView1.Rows[index].Cells[8].Value = prd.Currency;
dataGridView1.Rows[index].Cells[9].Value = prd.Stock;
dataGridView1.Rows[index].Cells[10].Value = prd.Image;
dataGridView1.Rows[index].Cells[11].Value = prd.URL;
dataGridView1.Rows[index].Cells[12].Value = prd.Size;
dataGridView1.Rows[index].Cells[13].Value = prd.Color;
dataGridView1.Rows[index].Cells[14].Value = prd.Isparent;
dataGridView1.Rows[index].Cells[15].Value = prd.parentsku;
dataGridView1.Rows[index].Cells[16].Value = prd.Bulletpoints1;
dataGridView1.Rows[index].Cells[17].Value = prd.Bulletpoints2;
dataGridView1.Rows[index].Cells[18].Value = prd.Bulletpoints3;
dataGridView1.Rows[index].Cells[19].Value = prd.Bulletpoints4;
dataGridView1.Rows[index].Cells[20].Value = prd.Bulletpoints5;
dataGridView1.Rows[index].Cells[21].Value = prd.Category;
dataGridView1.Rows[index].Cells[22].Value = prd.Weight;
}
}
foreach (Crawler_WithouSizes_Part7.BusinessLayer.Product prd in Worker2Products)
{
if (prd.Name.Trim().Length > 0)
{
int index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[1].Value = prd.SKU;
dataGridView1.Rows[index].Cells[2].Value = prd.Name;
dataGridView1.Rows[index].Cells[3].Value = prd.Description;
dataGridView1.Rows[index].Cells[4].Value = prd.Bulletpoints;
dataGridView1.Rows[index].Cells[5].Value = prd.Manufacturer;
dataGridView1.Rows[index].Cells[6].Value = prd.Brand;
dataGridView1.Rows[index].Cells[7].Value = prd.Price;
dataGridView1.Rows[index].Cells[8].Value = prd.Currency;
dataGridView1.Rows[index].Cells[9].Value = prd.Stock;
dataGridView1.Rows[index].Cells[10].Value = prd.Image;
dataGridView1.Rows[index].Cells[11].Value = prd.URL;
dataGridView1.Rows[index].Cells[12].Value = prd.Size;
dataGridView1.Rows[index].Cells[13].Value = prd.Color;
dataGridView1.Rows[index].Cells[14].Value = prd.Isparent;
dataGridView1.Rows[index].Cells[15].Value = prd.parentsku;
dataGridView1.Rows[index].Cells[16].Value = prd.Bulletpoints1;
dataGridView1.Rows[index].Cells[17].Value = prd.Bulletpoints2;
dataGridView1.Rows[index].Cells[18].Value = prd.Bulletpoints3;
dataGridView1.Rows[index].Cells[19].Value = prd.Bulletpoints4;
dataGridView1.Rows[index].Cells[20].Value = prd.Bulletpoints5;
dataGridView1.Rows[index].Cells[21].Value = prd.Category;
dataGridView1.Rows[index].Cells[22].Value = prd.Weight;
}
}
#endregion InsertdataIngrid
#endregion ProductInformation
System.Threading.Thread.Sleep(1000);
_lblerror.Visible = true;
_lblerror.Text = "Now we going to generate Csv File";
GenerateCSVFile();
MessageBox.Show("Process Completed.");
}
catch
{
}
#endregion scubagearcanada
_writer.Close();
}
public void Recusion(HtmlNode _Node)
{
HtmlNodeCollection _InnerCollection = null;
_InnerCollection = _Node.SelectNodes(".//ul/li");
if (_InnerCollection != null)
{
foreach (HtmlNode _Nodeinner in _InnerCollection)
{
try
{
foreach (HtmlAttribute _Attributeinner in _Nodeinner.SelectNodes(".//a")[0].Attributes)
{
if (!_Nodeinner.SelectNodes(".//a")[0].InnerText.ToLower().StartsWith("all") && _Attributeinner.Value.Trim().Length > 0 && _Attributeinner.Value != "#")
{
if (_Attributeinner.Name.ToLower() == "href")
{
try
{
CategoryUrl.Add(_Attributeinner.Value, _Nodeinner.SelectNodes(".//a")[0].InnerText.Trim());
}
catch
{
}
}
}
}
}
catch
{
}
Recusion(_Nodeinner);
}
}
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int CountError = 0;
if (!_IsProduct)
{
do
{
try
{
CountError++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
}
catch
{
_Iserror = true;
}
} while (_Iserror && CountError < 5);
}
else
{
Erorr_scubagearcanada1 = true;
int CounterError = 0;
do
{
try
{
_Worker1.GoToNoWait(Url1);
Erorr_scubagearcanada1 = false;
}
catch
{
CounterError++;
}
} while (Erorr_scubagearcanada1 && CounterError < 20);
}
#region scubagearcanada
if (_ISscubagearcanada)
{
if (_IsCategorypaging)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"col-sm-6 text-right\"]");
if (_Collection != null)
{
try
{
string PagingText = _Collection[0].InnerText.ToLower();
PagingText = PagingText.Substring(0, PagingText.IndexOf("pages"));
PagingText = PagingText.Substring(PagingText.IndexOf("(")).Trim();
int _TotalPages = Convert.ToInt32(Regex.Replace(PagingText.Replace("\r", "").Replace("\n", "").ToLower().Replace("page", "").Replace("of", "").Trim(), "[^0-9+]", string.Empty));
for (int Page = 1; Page <= _TotalPages; Page++)
{
try
{
SubCategoryUrl.Add(Url1 + "?page=" + Page, BrandName1);
}
catch
{
}
}
}
catch
{
try
{
SubCategoryUrl.Add(Url1, BrandName1);
}
catch
{
}
}
}
else
{
SubCategoryUrl.Add(Url1, BrandName1);
}
}
else
{
}
_Saleeventindex++;
_Work.ReportProgress((_Saleeventindex * 100 / CategoryUrl.Count()));
}
else if (_IsCategory)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ProductDetails\"]/a");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
if (!ProductName.Contains(_Node.InnerText.Trim()))
{
ProductName.Add(_Node.InnerText.Trim());
HtmlAttributeCollection _AttColl = _Node.Attributes;
foreach (HtmlAttribute _Att in _AttColl)
{
if (_Att.Name.ToLower() == "href")
{
try
{
if (!_ProductUrl.Keys.Contains(_Att.Value.ToLower()))
_ProductUrl.Add(_Att.Value.ToLower(), BrandName1);
}
catch
{
}
}
}
}
}
}
else
{
}
_Saleeventindex++;
_Work.ReportProgress((_Saleeventindex * 100 / SubCategoryUrl.Count()));
}
else
{
}
}
else
{
_Saleeventindex++;
_Work.ReportProgress((_Saleeventindex * 100 / _ProductUrl.Count()));
}
}
#endregion scubagearcanada
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int CountError = 0;
if (!_IsProduct)
{
do
{
try
{
CountError++;
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
}
catch
{
_Iserror = true;
}
} while (_Iserror && CountError < 5);
}
else
{
Erorr_scubagearcanada2 = true;
int CounterError = 0;
do
{
try
{
_Worker2.GoToNoWait(Url2);
Erorr_scubagearcanada2 = false;
}
catch
{
CounterError++;
}
} while (Erorr_scubagearcanada2 && CounterError < 20);
}
#region scubagearcanada
if (_ISscubagearcanada)
{
if (_IsCategorypaging)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"col-sm-6 text-right\"]");
if (_Collection != null)
{
try
{
string PagingText = _Collection[0].InnerText.ToLower();
PagingText = PagingText.Substring(0, PagingText.IndexOf("pages"));
PagingText = PagingText.Substring(PagingText.IndexOf("(")).Trim();
int _TotalPages = Convert.ToInt32(Regex.Replace(PagingText.Replace("\r", "").Replace("\n", "").ToLower().Replace("page", "").Replace("of", "").Trim(), "[^0-9+]", string.Empty));
for (int Page = 1; Page <= _TotalPages; Page++)
{
try
{
SubCategoryUrl.Add(Url2 + "?page=" + Page, BrandName2);
}
catch
{
}
}
}
catch
{
try
{
SubCategoryUrl.Add(Url2, BrandName2);
}
catch
{
}
}
}
else
{
SubCategoryUrl.Add(Url2, BrandName2);
}
}
else
{
}
_Saleeventindex++;
_Work1.ReportProgress((_Saleeventindex * 100 / CategoryUrl.Count()));
}
else if (_IsCategory)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ProductDetails\"]/a");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
if (!ProductName.Contains(_Node.InnerText.Trim()))
{
ProductName.Add(_Node.InnerText.Trim());
HtmlAttributeCollection _AttColl = _Node.Attributes;
foreach (HtmlAttribute _Att in _AttColl)
{
if (_Att.Name.ToLower() == "href")
{
try
{
if (!_ProductUrl.Keys.Contains(_Att.Value.ToLower()))
_ProductUrl.Add(_Att.Value.ToLower(), BrandName2);
}
catch
{
}
}
}
}
}
}
else
{
}
_Saleeventindex++;
_Work1.ReportProgress((_Saleeventindex * 100 / SubCategoryUrl.Count()));
}
else
{
}
}
else
{
_Saleeventindex++;
_Work1.ReportProgress((_Saleeventindex * 100 / _ProductUrl.Count()));
}
}
#endregion scubagearcanada
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
#region scubagearcanada
if (_ISscubagearcanada)
{
if (_IsProduct)
{
if (!Erorr_scubagearcanada1)
{
_Worker1.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
if (_Worker1.Html == null)
{
do
{
System.Threading.Thread.Sleep(10);
Application.DoEvents();
checkcounter++;
} while (_Worker1.Html == null && checkcounter < 10);
}
#endregion CheckPageLoaded
if (_Worker1.Html != null)
{
_Work1doc.LoadHtml(_Worker1.Html);
try
{
try
{
#region Title
string Title = "";
HtmlNodeCollection _Title = null;
_Title = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ProductDetailsGrid desktop PriceBorderBottom\"]/div[@class=\"DetailRow\"]/h1");
if (_Title == null)
_Title = _Work1doc.DocumentNode.SelectNodes("//meta=[@property=\"og:title\"]");
if (_Title != null)
{
Title = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "").Replace("â„¢", "™");
}
#endregion Title
#region Description
_Description1 = "";
HtmlNodeCollection _description = _Work1doc.DocumentNode.SelectNodes("//div[@itemprop=\"description\"]");
if (_description != null)
{
_Description1 = _description[0].InnerHtml.Replace("Quick Overview", "").Trim();
_Description1 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_Description1).Trim());
}
try
{
if (_Description1.Length > 2000)
_Description1 = _Description1.Substring(0, 1997) + "...";
}
catch
{
}
string Desc = System.Net.WebUtility.HtmlDecode(_Description1.Replace("Â", "").Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("online only", "").Replace("Online Only", "")).Replace(",", " ");
if (Desc.Trim() != "")
{
if (Desc.Substring(0, 1) == "\"")
_Description1 = Desc.Substring(1);
else
_Description1 = Desc;
}
#endregion Description
#region BulletPoints
string BulletPoints = "";
List<string> LstBulletPoints = new List<string>();
HtmlNodeCollection _Bullets1 = null;
_Bullets1 = _Work1doc.DocumentNode.SelectNodes("//div[@itemprop=\"description\"]");
if (_Bullets1 != null)
{
foreach (HtmlNode _BullNode in _Bullets1)
{
BulletPoints = BulletPoints + System.Net.WebUtility.HtmlDecode(CommanFunction.StripHTML(_BullNode.InnerText).Trim()) + ".";
}
}
if (BulletPoints.Trim() != "")
{
if (BulletPoints.Length >= 500)
LstBulletPoints.Add(BulletPoints.Substring(0, 497).Replace("â„¢", "™"));
else
LstBulletPoints.Add(BulletPoints.Replace("â„¢", "™"));
}
#endregion BulletPoints
#region Brand
string Brand = "";
HtmlNodeCollection _Brand = null;
_Brand = _Work1doc.DocumentNode.SelectNodes("//h4[@class=\"BrandName\"]/a");
if (_Brand == null)
_Brand = _Work1doc.DocumentNode.SelectNodes("//h4[@class=\"BrandName\"]/a/span");
if (_Brand != null)
{
Brand = _Brand[0].InnerText.Trim();
}
if (Brand.Trim() == "")
Brand = "SCUBA";
#endregion Brand
#region Images
string Images = "";
HtmlNodeCollection _Image = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ProductThumbImage\"]/a");
if (_Image != null)
{
foreach (HtmlAttribute _Att in _Image[0].Attributes)
{
if (_Att.Name == "href")
Images = _Att.Value.Trim() + "@";
}
}
Dictionary<string, string> _ThumbImages = new Dictionary<string, string>();
string ImageUrl = "";
string AltText = "";
HtmlNodeCollection _ThumImage1 = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ProductTinyImageList\"]");
if (_ThumImage1 != null)
{
HtmlNodeCollection _ThumImage = _ThumImage1[0].SelectNodes(".//a");
foreach (HtmlNode ThumNode in _ThumImage)
{
AltText = "";
ImageUrl = "";
foreach (HtmlAttribute _Att in ThumNode.Attributes)
{
if (_Att.Name.ToLower() == "rel")
{
string LargeImage = _Att.Value;
try
{
LargeImage = LargeImage.Substring(LargeImage.IndexOf("\"largeimage\": \"")).Replace("\"largeimage\": \"", "");
LargeImage = LargeImage.Substring(0, LargeImage.IndexOf("\""));
}
catch
{
LargeImage = LargeImage.Substring(LargeImage.IndexOf("\"smallimage\": \"")).Replace("\"smallimage\": \"", "");
LargeImage = LargeImage.Substring(0, LargeImage.IndexOf("\""));
}
finally
{
}
if (!Images.Contains(LargeImage))
{
ImageUrl = LargeImage;
HtmlNodeCollection _CollectionImgalt = ThumNode.SelectNodes(".//img");
if (_CollectionImgalt != null)
{
foreach (HtmlAttribute _Attimg in _CollectionImgalt[0].Attributes)
{
if (_Attimg.Name.ToLower() == "alt")
AltText = _Attimg.Value.ToLower().Trim();
}
}
Images = Images + LargeImage.Trim() + "@";
_ThumbImages.Add(ImageUrl, AltText);
}
}
}
}
}
if (Images.Length > 0)
Images = Images.Substring(0, Images.Length - 1);
#endregion Images
int VariantsCounter = 0;
string ParentSku = "";
VariantsCounter++;
string Price = "";
string Stock = "";
string Sku = "";
#region Price
HtmlNodeCollection _Price = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]");
if (_Price != null)
{
Price = _Price[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
#endregion price
#region stock
Stock = "5";
HtmlNodeCollection _Stock1 = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"content\"]");
if (_Stock1 != null)
{
HtmlNodeCollection _Stock = _Stock1[0].SelectNodes(".//ul[@class=\"list-unstyled\"]");
if (_Stock != null)
{
if (_Stock[0].InnerHtml.ToLower().Contains("out of stock") || _Stock[0].InnerHtml.ToLower().Contains("out stock"))
Stock = "0";
}
}
#endregion stock
#region sku
HtmlNodeCollection _sku = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_sku != null)
{
Sku = _sku[0].InnerText.ToLower().Replace("product code:", "").Trim();
ParentSku = Sku;
}
if (ParentSku == "")
{
ParentSku = CommanFunction.GeneratecolorSku("", Title);
Sku = ParentSku;
}
ParentSku = ParentSku + "prnt";
#endregion sku
if (Skus.Contains(Sku))
return;
else
Skus.Add(Sku);
HtmlNodeCollection _Coll = null;
_Coll = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"productAddToCartRight\"]");
if (_Coll != null)
_Coll = _Coll[0].SelectNodes(".//select");
string ID = "";
if (_Coll != null)
{
if (_Coll.Count == 1)
{
if (_Coll[0].Id == "qty_")
ID = "qty_";
}
}
if (_Coll == null || (ID.Length > 0))
{
Crawler_WithouSizes_Part7.BusinessLayer.Product Prd = new Crawler_WithouSizes_Part7.BusinessLayer.Product();
Prd.Brand = Brand;
Prd.Category = BrandName1;
Prd.Manufacturer = Brand;
Prd.Currency = "CAD";
if (_Description1.Trim() != "")
Prd.Description = _Description1;
else
Prd.Description = Title;
Prd.URL = Url1;
int BulletPointCounter = 0;
foreach (var Points in LstBulletPoints)
{
BulletPointCounter++;
switch (BulletPointCounter)
{
case 1:
Prd.Bulletpoints1 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 2:
Prd.Bulletpoints2 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 3:
Prd.Bulletpoints3 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 4:
Prd.Bulletpoints4 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 5:
Prd.Bulletpoints5 = Points.Replace("..", "").Replace("â€", "\"");
break;
}
}
Prd.Isparent = true;
if (Sku.Length + 3 > 30)
Prd.SKU = "SGC" + Sku.Substring(0, 27);
else
Prd.SKU = "SGC" + Sku;
Prd.Stock = Stock;
Prd.Price = Price;
if (ParentSku.Length + 3 > 30)
Prd.parentsku = "SGC" + ParentSku.Substring(0, 27);
else
Prd.parentsku = "SGC" + ParentSku;
Prd.Weight = "0";
Prd.Name = Title;
Prd.Image = Images;
Worker1Products.Add(Prd);
}
else
{
bool Kit = false;
Dictionary<string, string> Options = new Dictionary<string, string>();
foreach (HtmlNode _Node in _Coll)
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "id")
{
if (_Att.Value.ToLower() != "qty_")
{
HtmlNodeCollection _LblColllection = _Work1doc.DocumentNode.SelectNodes("//label[@for=\"" + _Att.Value + "\"]");
if (_LblColllection != null)
{
if (_LblColllection[0].InnerText.Trim().ToLower().Contains("size"))
Options.Add(_Att.Value, "size");
else if (_LblColllection[0].InnerText.Trim().ToLower().Contains("color") || _LblColllection[0].InnerText.Trim().ToLower().Contains("colour"))
Options.Add(_Att.Value, "color");
else
{
Kit = true;
Options.Add(_Att.Value, _LblColllection[0].InnerText.Trim().ToLower().Replace(":", "").Replace("*", ""));
}
}
else
{
Kit = true;
Options.Add(_Att.Value, "");
}
}
}
}
}
if (Options.Count > 0 && !Kit)
{
int Variantcounter = 0;
SelectList _List = _Worker1.SelectList(Find.ById(Options.Keys.ElementAt(0)));
int Counter = 0;
bool DuplicacayExist = true;
int CheckCounter = 0;
string CheckSkuDuplicacy = "";
foreach (Option option in _List.Options)
{
if (!option.Text.Trim().ToLower().Contains("please "))
{
DuplicacayExist = true;
CheckCounter = 0;
_TableWork1.Rows.Clear();
_Worker1.SelectList(Find.ById(Options.Keys.ElementAt(0))).Option(option.Text).Select();
_Worker1.SelectList(Find.ById(Options.Keys.ElementAt(0))).Option(option.Text).Click();
_Worker1.WaitForComplete();
System.Threading.Thread.Sleep(2000);
if (Options.Count == 1)
{
_Work1doc.LoadHtml(_Worker1.Html);
while (DuplicacayExist && CheckCounter < 10)
{
HtmlNodeCollection _skuatt1 = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt1 != null)
{
if ((CheckSkuDuplicacy == _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim()) || _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim() == "")
{
Application.DoEvents();
_Work1doc.LoadHtml(_Worker1.Html);
}
else
{
DuplicacayExist = false;
CheckSkuDuplicacy = _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
CheckCounter++;
}
}
if (DuplicacayExist)
return;
}
if (Options.Count > 1)
{
SelectList _List1 = _Worker1.SelectList(Find.ById(Options.Keys.ElementAt(1)));
int Counter1 = 0;
foreach (var option1 in _List1.Options)
{
if (!option1.Text.ToLower().Contains("please "))
{
_Worker1.SelectList(Find.ById(Options.Keys.ElementAt(1))).Option(option1.Text).Select();
_Worker1.SelectList(Find.ById(Options.Keys.ElementAt(1))).Option(option1.Text).Click();
System.Threading.Thread.Sleep(2000);
_Work1doc.LoadHtml(_Worker1.Html);
while (DuplicacayExist && CheckCounter < 10)
{
HtmlNodeCollection _skuatt1 = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt1 != null)
{
if ((CheckSkuDuplicacy == _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim()) || _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim() == "")
{
Application.DoEvents();
_Work1doc.LoadHtml(_Worker1.Html);
}
else
{
DuplicacayExist = false;
CheckSkuDuplicacy = _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
CheckCounter++;
}
}
if (DuplicacayExist)
return;
option1.SelectNoWait();
DataRow _Row = _TableWork1.NewRow();
HtmlNodeCollection _PriceAtt = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]");
if (_PriceAtt != null)
{
_Row[0] = _PriceAtt[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
HtmlNodeCollection _skuatt = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt != null)
{
_Row[1] = _skuatt[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
if (Options.Values.ElementAt(0) == "color")
{
_Row[2] = option.Text.Trim();
_Row[3] = option1.Text.Trim();
}
else
{
_Row[3] = option.Text.Trim();
_Row[2] = option1.Text.Trim();
}
_Row[4] = "5";
_TableWork1.Rows.Add(_Row);
}
Counter1++;
}
}
else
{
DataRow _Row = _TableWork1.NewRow();
HtmlNodeCollection _PriceAtt = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]");
if (_PriceAtt != null)
{
_Row[0] = _PriceAtt[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
HtmlNodeCollection _skuatt = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt != null)
{
_Row[1] = _skuatt[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
if (Options.Values.ElementAt(0) == "color")
_Row[2] = option.Text.Trim();
else
_Row[3] = option.Text.Trim();
_Row[4] = "5";
_TableWork1.Rows.Add(_Row);
}
Counter++;
foreach (DataRow Dr in _TableWork1.Rows)
{
if (Dr[1].ToString() + "prnt" != ParentSku)
{
Crawler_WithouSizes_Part7.BusinessLayer.Product PrdCheck = null;
try
{
PrdCheck = Worker1Products.Find(M => M.SKU == "SGC" + Dr[1].ToString());
}
catch
{
}
if (PrdCheck == null)
{
Variantcounter++;
Crawler_WithouSizes_Part7.BusinessLayer.Product Prd = new Crawler_WithouSizes_Part7.BusinessLayer.Product();
Prd.Brand = Brand;
Prd.Category = BrandName1;
Prd.Manufacturer = Brand;
Prd.Currency = "CAD";
if (_Description1.Trim() != "")
Prd.Description = _Description1;
else
Prd.Description = Title;
Prd.URL = Url1;
int BulletPointCounter = 0;
foreach (var Points in LstBulletPoints)
{
BulletPointCounter++;
switch (BulletPointCounter)
{
case 1:
Prd.Bulletpoints1 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 2:
Prd.Bulletpoints2 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 3:
Prd.Bulletpoints3 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 4:
Prd.Bulletpoints4 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 5:
Prd.Bulletpoints5 = Points.Replace("..", "").Replace("â€", "\"");
break;
}
}
Prd.Name = Title;
if (Variantcounter == 1)
Prd.Isparent = true;
Prd.Size = Dr[3].ToString();
Prd.Color = Dr[2].ToString();
Prd.SKU = "SGC" + Dr[1].ToString();
Prd.Stock = Dr[4].ToString();
Prd.Price = Dr[0].ToString();
if (ParentSku.Length + 3 > 30)
Prd.parentsku = "SGC" + ParentSku.Substring(0, 27);
else
Prd.parentsku = "SGC" + ParentSku;
Prd.Weight = "0";
try
{
var _Images = (from Img in _ThumbImages
where Dr[2].ToString().ToLower().Contains(Img.Value.Trim().ToLower())
select Img.Key).ToArray();
if (_Images == null || _Images.Count() == 0)
{
var _Imagessize = (from Img in _ThumbImages
where Dr[3].ToString().ToLower().Contains(Img.Value.Trim().ToLower())
select Img.Key).ToArray();
if (_Imagessize == null || _Imagessize.Count() == 0)
Prd.Image = Images;
else
{
string ColorImages = _Imagessize[0].ToString() + "@" + Images.Replace(_Imagessize[0].ToString(), "");
Prd.Image = ColorImages.Replace("@@", "@");
}
}
else
{
string ColorImages = _Images[0].ToString() + "@" + Images.Replace(_Images[0].ToString(), "");
Prd.Image = ColorImages.Replace("@@", "@");
}
}
catch
{
Prd.Image = Images;
}
Worker1Products.Add(Prd);
}
else
{
_writer.WriteLine(Url1 + "Duplicacy issue in sku.");
}
}
}
}
}
}
else
{
_writer.WriteLine(Url1 + "Url with More Options.");
}
}
}
catch
{
_writer.WriteLine(Url1 + "error occured in code to process this link");
}
}
catch
{
_writer.WriteLine(Url1 + "error occured in code to process this link");
}
}
else
{
_writer.WriteLine(Url1 + "Url data is not loaded.");
}
}
else
{
_writer.WriteLine(Url1 + "Url data is not loaded.");
}
}
else
{
}
}
else
{
}
#endregion scubagearcanada
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
#region scubagearcanada
if (_ISscubagearcanada)
{
if (_IsProduct)
{
if (!Erorr_scubagearcanada2)
{
_Worker2.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
if (_Worker2.Html == null)
{
do
{
System.Threading.Thread.Sleep(10);
Application.DoEvents();
checkcounter++;
} while (_Worker2.Html == null && checkcounter < 10);
}
#endregion CheckPageLoaded
if (_Worker2.Html != null)
{
_Work1doc2.LoadHtml(_Worker2.Html);
try
{
try
{
#region Title
string Title = "";
HtmlNodeCollection _Title = null;
_Title = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ProductDetailsGrid desktop PriceBorderBottom\"]/div[@class=\"DetailRow\"]/h1");
if (_Title == null)
_Title = _Work1doc2.DocumentNode.SelectNodes("//meta=[@property=\"og:title\"]");
if (_Title != null)
{
Title = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "").Replace("â„¢", "™");
}
#endregion Title
#region Description
_Description2 = "";
HtmlNodeCollection _description = _Work1doc2.DocumentNode.SelectNodes("//div[@itemprop=\"description\"]");
if (_description != null)
{
_Description2 = _description[0].InnerHtml.Replace("Quick Overview", "").Trim();
_Description2 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_Description2).Trim());
}
try
{
if (_Description2.Length > 2000)
_Description2 = _Description2.Substring(0, 1997) + "...";
}
catch
{
}
string Desc = System.Net.WebUtility.HtmlDecode(_Description2.Replace("Â", "").Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("online only", "").Replace("Online Only", "")).Replace(",", " ");
if (Desc.Trim() != "")
{
if (Desc.Substring(0, 1) == "\"")
_Description2 = Desc.Substring(1);
else
_Description2 = Desc;
}
#endregion Description
#region BulletPoints
string BulletPoints = "";
List<string> LstBulletPoints = new List<string>();
HtmlNodeCollection _Bullets1 = null;
_Bullets1 = _Work1doc2.DocumentNode.SelectNodes("//div[@itemprop=\"description\"]");
if (_Bullets1 != null)
{
foreach (HtmlNode _BullNode in _Bullets1)
{
BulletPoints = BulletPoints + System.Net.WebUtility.HtmlDecode(CommanFunction.StripHTML(_BullNode.InnerText).Trim()) + ".";
}
}
if (BulletPoints.Trim() != "")
{
if (BulletPoints.Length >= 500)
LstBulletPoints.Add(BulletPoints.Substring(0, 497).Replace("â„¢", "™"));
else
LstBulletPoints.Add(BulletPoints.Replace("â„¢", "™"));
}
#endregion BulletPoints
#region Brand
string Brand = "";
HtmlNodeCollection _Brand = null;
_Brand = _Work1doc2.DocumentNode.SelectNodes("//h4[@class=\"BrandName\"]/a");
if (_Brand == null)
_Brand = _Work1doc2.DocumentNode.SelectNodes("//h4[@class=\"BrandName\"]/a/span");
if (_Brand != null)
{
Brand = _Brand[0].InnerText.Trim();
}
if (Brand.Trim() == "")
Brand = "SCUBA";
#endregion Brand
#region Images
string Images = "";
HtmlNodeCollection _Image = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ProductThumbImage\"]/a");
if (_Image != null)
{
foreach (HtmlAttribute _Att in _Image[0].Attributes)
{
if (_Att.Name == "href")
Images = _Att.Value.Trim() + "@";
}
}
Dictionary<string, string> _ThumbImages = new Dictionary<string, string>();
string ImageUrl = "";
string AltText = "";
HtmlNodeCollection _ThumImage1 = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ProductTinyImageList\"]");
if (_ThumImage1 != null)
{
HtmlNodeCollection _ThumImage = _ThumImage1[0].SelectNodes(".//a");
foreach (HtmlNode ThumNode in _ThumImage)
{
AltText = "";
ImageUrl = "";
foreach (HtmlAttribute _Att in ThumNode.Attributes)
{
if (_Att.Name.ToLower() == "rel")
{
string LargeImage = _Att.Value;
try
{
LargeImage = LargeImage.Substring(LargeImage.IndexOf("\"largeimage\": \"")).Replace("\"largeimage\": \"", "");
LargeImage = LargeImage.Substring(0, LargeImage.IndexOf("\""));
}
catch
{
LargeImage = LargeImage.Substring(LargeImage.IndexOf("\"smallimage\": \"")).Replace("\"smallimage\": \"", "");
LargeImage = LargeImage.Substring(0, LargeImage.IndexOf("\""));
}
finally
{
}
if (!Images.Contains(LargeImage))
{
ImageUrl = LargeImage;
HtmlNodeCollection _CollectionImgalt = ThumNode.SelectNodes(".//img");
if (_CollectionImgalt != null)
{
foreach (HtmlAttribute _Attimg in _CollectionImgalt[0].Attributes)
{
if (_Attimg.Name.ToLower() == "alt")
AltText = _Attimg.Value.ToLower().Trim();
}
}
Images = Images + LargeImage.Trim() + "@";
_ThumbImages.Add(ImageUrl, AltText);
}
}
}
}
}
if (Images.Length > 0)
Images = Images.Substring(0, Images.Length - 1);
#endregion Images
int VariantsCounter = 0;
string ParentSku = "";
VariantsCounter++;
string Price = "";
string Stock = "";
string Sku = "";
#region Price
HtmlNodeCollection _Price = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]");
if (_Price != null)
{
Price = _Price[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
#endregion price
#region stock
Stock = "5";
HtmlNodeCollection _Stock1 = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"content\"]");
if (_Stock1 != null)
{
HtmlNodeCollection _Stock = _Stock1[0].SelectNodes(".//ul[@class=\"list-unstyled\"]");
if (_Stock != null)
{
if (_Stock[0].InnerHtml.ToLower().Contains("out of stock") || _Stock[0].InnerHtml.ToLower().Contains("out stock"))
Stock = "0";
}
}
#endregion stock
#region sku
HtmlNodeCollection _sku = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_sku != null)
{
Sku = _sku[0].InnerText.ToLower().Replace("product code:", "").Trim();
ParentSku = Sku;
}
if (ParentSku == "")
{
ParentSku = CommanFunction.GeneratecolorSku("", Title);
Sku = ParentSku;
}
ParentSku = ParentSku + "prnt";
#endregion sku
if (Skus.Contains(Sku))
return;
else
Skus.Add(Sku);
HtmlNodeCollection _Coll = null;
_Coll = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"productAddToCartRight\"]");
if (_Coll != null)
_Coll = _Coll[0].SelectNodes(".//select");
string ID = "";
if (_Coll != null)
{
if (_Coll.Count == 1)
{
if (_Coll[0].Id == "qty_")
ID = "qty_";
}
}
if (_Coll == null || (ID.Length > 0))
{
Crawler_WithouSizes_Part7.BusinessLayer.Product Prd = new Crawler_WithouSizes_Part7.BusinessLayer.Product();
Prd.Brand = Brand;
Prd.Category = BrandName1;
Prd.Manufacturer = Brand;
Prd.Currency = "CAD";
if (_Description2.Trim() != "")
Prd.Description = _Description2;
else
Prd.Description = Title;
Prd.URL = Url2;
int BulletPointCounter = 0;
foreach (var Points in LstBulletPoints)
{
BulletPointCounter++;
switch (BulletPointCounter)
{
case 1:
Prd.Bulletpoints1 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 2:
Prd.Bulletpoints2 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 3:
Prd.Bulletpoints3 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 4:
Prd.Bulletpoints4 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 5:
Prd.Bulletpoints5 = Points.Replace("..", "").Replace("â€", "\"");
break;
}
}
Prd.Isparent = true;
if (Sku.Length + 3 > 30)
Prd.SKU = "SGC" + Sku.Substring(0, 27);
else
Prd.SKU = "SGC" + Sku;
Prd.Stock = Stock;
Prd.Price = Price;
if (ParentSku.Length + 3 > 30)
Prd.parentsku = "SGC" + ParentSku.Substring(0, 27);
else
Prd.parentsku = "SGC" + ParentSku;
Prd.Weight = "0";
Prd.Name = Title;
Prd.Image = Images;
Worker2Products.Add(Prd);
}
else
{
bool Kit = false;
Dictionary<string, string> Options = new Dictionary<string, string>();
foreach (HtmlNode _Node in _Coll)
{
foreach (HtmlAttribute _Att in _Node.Attributes)
{
if (_Att.Name.ToLower() == "id")
{
if (_Att.Value.ToLower() != "qty_")
{
HtmlNodeCollection _LblColllection = _Work1doc2.DocumentNode.SelectNodes("//label[@for=\"" + _Att.Value + "\"]");
if (_LblColllection != null)
{
if (_LblColllection[0].InnerText.Trim().ToLower().Contains("size"))
Options.Add(_Att.Value, "size");
else if (_LblColllection[0].InnerText.Trim().ToLower().Contains("color") || _LblColllection[0].InnerText.Trim().ToLower().Contains("colour"))
Options.Add(_Att.Value, "color");
else
{
Kit = true;
Options.Add(_Att.Value, _LblColllection[0].InnerText.Trim().ToLower().Replace(":", "").Replace("*", ""));
}
}
else
{
Kit = true;
Options.Add(_Att.Value, "");
}
}
}
}
}
if (Options.Count > 0 && !Kit)
{
string CheckSkuDuplicacy = "";
bool DuplicacayExist = true;
int CheckCounter = 0;
int Variantcounter = 0;
SelectList _List = _Worker2.SelectList(Find.ById(Options.Keys.ElementAt(0)));
int Counter = 0;
foreach (Option option in _List.Options)
{
if (!option.Text.Trim().ToLower().Contains("please "))
{
DuplicacayExist = true;
CheckCounter = 0;
_TableWork2.Rows.Clear();
_Worker2.SelectList(Find.ById(Options.Keys.ElementAt(0))).Option(option.Text).Select();
_Worker2.SelectList(Find.ById(Options.Keys.ElementAt(0))).Option(option.Text).Click();
_Worker2.WaitForComplete();
System.Threading.Thread.Sleep(2000);
if (Options.Count == 1)
{
_Work1doc2.LoadHtml(_Worker2.Html);
while (DuplicacayExist && CheckCounter < 10)
{
HtmlNodeCollection _skuatt1 = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt1 != null)
{
if ((CheckSkuDuplicacy == _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim()) || _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim() == "")
{
Application.DoEvents();
_Work1doc2.LoadHtml(_Worker2.Html);
}
else
{
DuplicacayExist = false;
CheckSkuDuplicacy = _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
CheckCounter++;
}
}
if (DuplicacayExist)
return;
}
#region CheckPageLoading
#endregion
if (Options.Count > 1)
{
SelectList _List1 = _Worker2.SelectList(Find.ById(Options.Keys.ElementAt(1)));
int Counter1 = 0;
foreach (var option1 in _List1.Options)
{
if (!option1.Text.ToLower().Contains("please "))
{
_Worker2.SelectList(Find.ById(Options.Keys.ElementAt(1))).Option(option1.Text).Select();
_Worker2.SelectList(Find.ById(Options.Keys.ElementAt(1))).Option(option1.Text).Click();
System.Threading.Thread.Sleep(2000);
_Work1doc2.LoadHtml(_Worker2.Html);
while (DuplicacayExist && CheckCounter < 10)
{
HtmlNodeCollection _skuatt1 = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt1 != null)
{
if ((CheckSkuDuplicacy == _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim()) || _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim() == "")
{
Application.DoEvents();
_Work1doc2.LoadHtml(_Worker2.Html);
}
else
{
DuplicacayExist = false;
CheckSkuDuplicacy = _skuatt1[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
CheckCounter++;
}
}
if (DuplicacayExist)
return;
option1.SelectNoWait();
DataRow _Row = _TableWork2.NewRow();
HtmlNodeCollection _PriceAtt = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]");
if (_PriceAtt != null)
{
_Row[0] = _PriceAtt[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
HtmlNodeCollection _skuatt = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt != null)
{
_Row[1] = _skuatt[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
if (Options.Values.ElementAt(0) == "color")
{
_Row[2] = option.Text.Trim();
_Row[3] = option1.Text.Trim();
}
else
{
_Row[3] = option.Text.Trim();
_Row[2] = option1.Text.Trim();
}
_Row[4] = "5";
_TableWork2.Rows.Add(_Row);
}
Counter1++;
}
}
else
{
DataRow _Row = _TableWork2.NewRow();
HtmlNodeCollection _PriceAtt = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"price\"]");
if (_PriceAtt != null)
{
_Row[0] = _PriceAtt[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
HtmlNodeCollection _skuatt = _Work1doc2.DocumentNode.SelectNodes("//span[@itemprop=\"sku\"]");
if (_skuatt != null)
{
_Row[1] = _skuatt[0].InnerText.ToLower().Replace("product code:", "").Trim();
}
if (Options.Values.ElementAt(0) == "color")
_Row[2] = option.Text.Trim();
else
_Row[3] = option.Text.Trim();
_Row[4] = "5";
_TableWork2.Rows.Add(_Row);
}
Counter++;
foreach (DataRow Dr in _TableWork2.Rows)
{
if (Dr[1].ToString() + "prnt" != ParentSku)
{
Crawler_WithouSizes_Part7.BusinessLayer.Product PrdCheck = null;
try
{
PrdCheck = Worker2Products.Find(M => M.SKU == "SGC" + Dr[1].ToString());
}
catch
{
}
if (PrdCheck == null)
{
Variantcounter++;
Crawler_WithouSizes_Part7.BusinessLayer.Product Prd = new Crawler_WithouSizes_Part7.BusinessLayer.Product();
Prd.Brand = Brand;
Prd.Category = BrandName1;
Prd.Manufacturer = Brand;
Prd.Currency = "CAD";
if (_Description2.Trim() != "")
Prd.Description = _Description2;
else
Prd.Description = Title;
Prd.URL = Url2;
int BulletPointCounter = 0;
foreach (var Points in LstBulletPoints)
{
BulletPointCounter++;
switch (BulletPointCounter)
{
case 1:
Prd.Bulletpoints1 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 2:
Prd.Bulletpoints2 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 3:
Prd.Bulletpoints3 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 4:
Prd.Bulletpoints4 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 5:
Prd.Bulletpoints5 = Points.Replace("..", "").Replace("â€", "\"");
break;
}
}
Prd.Name = Title;
if (Variantcounter == 1)
Prd.Isparent = true;
Prd.Size = Dr[3].ToString();
Prd.Color = Dr[2].ToString();
Prd.SKU = "SGC" + Dr[1].ToString();
Prd.Stock = Dr[4].ToString();
Prd.Price = Dr[0].ToString();
if (ParentSku.Length + 3 > 30)
Prd.parentsku = "SGC" + ParentSku.Substring(0, 27);
else
Prd.parentsku = "SGC" + ParentSku;
Prd.Weight = "0";
try
{
var _Images = (from Img in _ThumbImages
where Dr[2].ToString().ToLower().Contains(Img.Value.Trim().ToLower())
select Img.Key).ToArray();
if (_Images == null || _Images.Count() == 0)
{
var _Imagessize = (from Img in _ThumbImages
where Dr[3].ToString().ToLower().Contains(Img.Value.Trim().ToLower())
select Img.Key).ToArray();
if (_Imagessize == null || _Imagessize.Count() == 0)
Prd.Image = Images;
else
{
string ColorImages = _Imagessize[0].ToString() + "@" + Images.Replace(_Imagessize[0].ToString(), "");
Prd.Image = ColorImages.Replace("@@", "@");
}
}
else
{
string ColorImages = _Images[0].ToString() + "@" + Images.Replace(_Images[0].ToString(), "");
Prd.Image = ColorImages.Replace("@@", "@");
}
}
catch
{
Prd.Image = Images;
}
Worker2Products.Add(Prd);
}
else
{
_writer.WriteLine(Url2 + "Duplicacy issue in sku.");
}
}
}
}
}
}
else
{
_writer.WriteLine(Url2 + "Url with More Options.");
}
}
}
catch
{
_writer.WriteLine(Url2 + "error occured in code to process this link");
}
}
catch
{
_writer.WriteLine(Url2 + "error occured in code to process this link");
}
}
else
{
_writer.WriteLine(Url2 + "Url data is not loaded.");
}
}
else
{
_writer.WriteLine(Url2 + "Url data is not loaded.");
}
}
else
{
}
}
else
{
}
#endregion scubagearcanada
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename, decimal Price)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void _percent_Click(object sender, EventArgs e)
{
}
private void createcsvfile_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Go_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Pause_Click(object sender, EventArgs e)
{
}
private void totalrecord_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
/****************Code to select all check boxes*************/
/************Uncomment durng live**/
for (int i = 0; i < chkstorelist.Items.Count; i++)
{
chkstorelist.SetItemChecked(i, true);
}
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
dataGridView1.Columns.Add("RowID", "RowID");
dataGridView1.Columns.Add("SKU", "SKU");
dataGridView1.Columns.Add("Product Name", "Product Name");
dataGridView1.Columns.Add("Product Description", "Product Description");
dataGridView1.Columns.Add("Bullet Points", "Bullet Points");
dataGridView1.Columns.Add("Manufacturer", "Manufacturer");
dataGridView1.Columns.Add("Brand Name", "Brand Name");
dataGridView1.Columns.Add("Price", "Price");
dataGridView1.Columns.Add("Currency", "Currency");
dataGridView1.Columns.Add("In Stock", "In Stock");
dataGridView1.Columns.Add("Image URL", "Image URL");
dataGridView1.Columns.Add("URL", "URL");
dataGridView1.Columns.Add("Size", "Size");
dataGridView1.Columns.Add("Color", "Color");
dataGridView1.Columns.Add("Isdefault", "Isdefault");
dataGridView1.Columns.Add("ParentSku", "ParentSku");
dataGridView1.Columns.Add("BullPoint1", "BullPoint1");
dataGridView1.Columns.Add("BullPoint2", "BullPoint2");
dataGridView1.Columns.Add("BullPoint3", "BullPoint3");
dataGridView1.Columns.Add("BullPoint4", "BullPoint4");
dataGridView1.Columns.Add("BullPoint5", "BullPoint5");
dataGridView1.Columns.Add("Category", "Category");
dataGridView1.Columns.Add("Weight", "Weight");
/****************BackGround worker *************************/
}
public void GenerateCSVFile()
{
try
{
string Filename = "data" + DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "");
DataTable exceldt = new DataTable();
exceldt.Columns.Add("Rowid", typeof(int));
exceldt.Columns.Add("SKU", typeof(string));
exceldt.Columns.Add("Product Name", typeof(string));
exceldt.Columns.Add("Product Description", typeof(string));
exceldt.Columns.Add("Bullet Points", typeof(string));
exceldt.Columns.Add("Manufacturer", typeof(string));
exceldt.Columns.Add("Brand Name", typeof(string));
exceldt.Columns.Add("Price", typeof(decimal));
exceldt.Columns.Add("Currency", typeof(string));
exceldt.Columns.Add("In Stock", typeof(string));
exceldt.Columns.Add("Image URL", typeof(string));
exceldt.Columns.Add("URL", typeof(string));
exceldt.Columns.Add("Size", typeof(string));
exceldt.Columns.Add("Color", typeof(string));
exceldt.Columns.Add("Isdefault", typeof(bool));
exceldt.Columns.Add("ParentSku", typeof(string));
exceldt.Columns.Add("Bulletpoints1", typeof(string));
exceldt.Columns.Add("Bulletpoints2", typeof(string));
exceldt.Columns.Add("Bulletpoints3", typeof(string));
exceldt.Columns.Add("Bulletpoints4", typeof(string));
exceldt.Columns.Add("Bulletpoints5", typeof(string));
exceldt.Columns.Add("Category", typeof(string));
exceldt.Columns.Add("Weight", typeof(string));
for (int m = 0; m < dataGridView1.Rows.Count; m++)
{
exceldt.Rows.Add();
try
{
for (int n = 0; n < dataGridView1.Columns.Count; n++)
{
if (dataGridView1.Rows[m].Cells[n].Value == null || dataGridView1.Rows[m].Cells[n].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[m].Cells[n].Value.ToString()))
continue;
exceldt.Rows[m][n] = dataGridView1.Rows[m].Cells[n].Value.ToString();
}
}
catch
{
}
}
#region sqlcode
DataSet _Ds = new DataSet();
DataTable _Product = new DataTable();
using (SqlCommand Cmd = new SqlCommand())
{
try
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandTimeout = 0;
Cmd.Connection = Connection;
Cmd.CommandText = "MarkHub_ScrapeProductMerging";
Cmd.Parameters.AddWithValue("@StoreName", "scubagearcanada.ca");
Cmd.Parameters.AddWithValue("@Products", exceldt);
SqlDataAdapter _ADP = new SqlDataAdapter(Cmd);
_ADP.Fill(_Ds);
}
catch
{
}
}
_Product = _Ds.Tables[0];
#endregion sqlcode
if (_Product.Rows.Count > 0)
{
try
{
using (CsvFileWriter writer = new CsvFileWriter(Application.StartupPath + "/" + Filename + ".txt"))
{
CsvFileWriter.CsvRow row = new CsvFileWriter.CsvRow();//HEADER FOR CSV FILE
foreach (DataColumn _Dc in _Product.Columns)
{
row.Add(_Dc.ColumnName);
}
row.Add("Image URL2");
row.Add("Image URL3");
row.Add("Image URL4");
row.Add("Image URL5");
writer.WriteRow(row);//INSERT TO CSV FILE HEADER
for (int m = 0; m < _Product.Rows.Count; m++)
{
CsvFileWriter.CsvRow row1 = new CsvFileWriter.CsvRow();
for (int n = 0; n < _Product.Columns.Count; n++)
{
if (n == _Product.Columns.Count - 1)
{
if (_Product.Rows[m][n] != null)
{
string[] ImageArray = _Product.Rows[m][n].ToString().Split('@');
for (int count = 0; count < ImageArray.Length; count++)
{
if (count < 5)
row1.Add(String.Format("{0}", ImageArray[count].ToString()));
}
}
else
row1.Add(String.Format("{0}", ""));
}
else
{
if (_Product.Rows[m][n] != null)
row1.Add(String.Format("{0}", _Product.Rows[m][n].ToString().Replace("\n", "").Replace("\r", "").Replace("\t", "")));
else
row1.Add(String.Format("{0}", ""));
}
}
writer.WriteRow(row1);
}
}
System.Diagnostics.Process.Start(Application.StartupPath + "/" + Filename + ".txt");//OPEN THE CSV FILE ,,CSV FILE NAMED AS DATA.CSV
}
catch (Exception) { MessageBox.Show("file is already open\nclose the file"); }
return;
}
else
{
_lblerror.Visible = true;
_lblerror.Text = "OOPS there is some iossue occured. Please contact developer as soon as possible";
}
}
catch
{
_lblerror.Visible = true;
_lblerror.Text = "OOPS there is some iossue occured. Please contact developer as soon as possible";
}
}
public class CsvFileWriter : StreamWriter //Writing data to CSV
{
public CsvFileWriter(Stream stream)
: base(stream)
{
}
public CsvFileWriter(string filename)
: base(filename)
{
}
public class CsvRow : List<string> //Making each CSV rows
{
public string LineText { get; set; }
}
public void WriteRow(CsvRow row)
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in row)
{
builder.Append(value.Replace("\n", "") + "\t");
}
row.LineText = builder.ToString();
WriteLine(row.LineText);
}
}
private void btnsubmit_Click(object sender, System.EventArgs e)
{
Process();
}
private void Form1_Shown(object sender, System.EventArgs e)
{
}
private void chkstorelist_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>/Project 1/palyerborndate/BusinessLayer/DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
namespace BusinessLayer
{
public class DB
{
public SqlConnection Connection()
{
SqlConnection Connection = new SqlConnection();
Connection.ConnectionString = ConfigurationManager.AppSettings["connectionstring"].ToString();
return Connection;
}
public SqlDataReader GetDR(string Command)
{
SqlDataReader _Reader = null;
try
{
var _Con = Connection();
SqlCommand _CMD = new SqlCommand(Command);
if (_Con.State == ConnectionState.Closed)
_Con.Open();
_CMD.Connection = _Con;
_CMD.CommandType = CommandType.Text;
_Reader = _CMD.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{ }
return _Reader;
}
public void ExecuteCommand(string Command)
{
try
{
using (var _Con = Connection())
{
using (SqlCommand _CMD = new SqlCommand(Command))
{
if (_Con.State == ConnectionState.Closed)
_Con.Open();
_CMD.Connection = _Con;
_CMD.CommandType = CommandType.Text;
_CMD.ExecuteNonQuery();
}
}
}
catch
{ }
}
public DataSet GetDataset(string CommandName, CommandType _CmdType, string Parameters)
{
DataSet _DsRecords = new DataSet();
using (var _Con = Connection())
{
using (SqlCommand _CMD = new SqlCommand(CommandName))
{
if (_Con.State == ConnectionState.Closed)
_Con.Open();
_CMD.Connection = _Con;
_CMD.CommandType = _CmdType;
if (Parameters.Trim().Length > 0)
{
string[] Param = Parameters.Split(':');
foreach (string _Prm in Param)
{
_CMD.Parameters.AddWithValue(_Prm.Split(',')[0], _Prm.Split(',')[1].Replace("#$^&", ",").Replace("#$^&&", ""));
}
}
SqlDataAdapter _Adp = new SqlDataAdapter(_CMD);
_Adp.Fill(_DsRecords);
_Adp.Dispose();
}
}
return _DsRecords;
}
public bool ProductInsert(string StoreName, DataTable exceldt)
{
using (var con = Connection())
{
using (SqlCommand Cmd = new SqlCommand())
{
try
{
if (con.State == ConnectionState.Closed)
con.Open();
Cmd.Connection = con;
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandTimeout = 0;
Cmd.CommandText = "MarkHub_ProductsInsert";
Cmd.Parameters.AddWithValue("@StoreName", StoreName);
Cmd.Parameters.AddWithValue("@Products", exceldt);
Cmd.ExecuteNonQuery();
}
catch
{
return false;
}
}
}
return true;
}
public DataSet GetDatasetByPassDatatable(string ProcName, DataTable exceldt, string DatTableVariable, CommandType _Type, string Parameters)
{
DataSet _DS = new DataSet();
using (var con = Connection())
{
using (SqlCommand Cmd = new SqlCommand())
{
try
{
if (con.State == ConnectionState.Closed)
con.Open();
Cmd.Connection = con;
Cmd.CommandType = _Type;
Cmd.CommandTimeout = 0;
Cmd.CommandText = ProcName;
if (Parameters.Trim().Length > 0)
{
string[] Param = Parameters.Split(':');
foreach (string _Prm in Param)
{
Cmd.Parameters.AddWithValue(_Prm.Split(',')[0], _Prm.Split(',')[1]);
}
}
Cmd.Parameters.AddWithValue(DatTableVariable, exceldt);
SqlDataAdapter _Adp = new SqlDataAdapter(Cmd);
_Adp.Fill(_DS);
}
catch
{
return _DS;
}
}
}
return _DS;
}
public bool PassDatatable(string ProcName, DataTable exceldt, string DatTableVariable, CommandType _Type, string Parameters)
{
DataSet _DS = new DataSet();
using (var con = Connection())
{
using (SqlCommand Cmd = new SqlCommand())
{
try
{
if (con.State == ConnectionState.Closed)
con.Open();
Cmd.Connection = con;
Cmd.CommandType = _Type;
Cmd.CommandTimeout = 0;
Cmd.CommandText = ProcName;
if (Parameters.Trim().Length > 0)
{
string[] Param = Parameters.Split(':');
foreach (string _Prm in Param)
{
Cmd.Parameters.AddWithValue(_Prm.Split(',')[0], _Prm.Split(',')[1]);
}
}
Cmd.Parameters.AddWithValue(DatTableVariable, exceldt);
SqlDataAdapter _Adp = new SqlDataAdapter(Cmd);
_Adp.Fill(_DS);
}
catch
{
return false;
}
}
}
return true;
}
}
}
<file_sep>/Project 17 canadacomputers/Crawler_WithouSizes_Part2/Form1.cs
using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using Crawler_Without_Sizes_Part2;
using WatiN.Core;
using System.Text.RegularExpressions;
namespace Crawler_WithouSizes_Part2
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.APPConfig Config = new BusinessLayer.APPConfig();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
#endregion Buinesslayervariable
StreamWriter _writer = new StreamWriter(Application.StartupPath + "/test.csv");
#region booltypevariable
bool _IScanadacomputers = true;
bool _IsProduct = false;
bool _IsCategorypaging = false;
bool _IsSubcat = false;
bool _Stop = false;
bool Erorr_401_1 = true;
bool Erorr_401_2 = true;
#endregion booltypevariable
#region intypevariable
int FindCounter = 0;
int _Workindex = 0;
int _WorkIndex1 = 0;
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
int _401index = 0;
#endregion intypevariable
#region stringtypevariable
string BrandName1 = "";
string BrandName2 = "";
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "";
string _Description1 = "";
string _Description2 = "";
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
Dictionary<string, string> Url = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrlthread1 = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrlthread2 = new Dictionary<string, string>();
List<string> _Name = new List<string>();
Dictionary<string, string> subCategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
#region IeVariable
IE _Worker1 = null;
IE _Worker2 = null;
#endregion IeVariable
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public void DisplayRecordProcessdetails(string Message, string TotalrecordMessage)
{
_lblerror.Visible = true;
_lblerror.Text = Message;
totalrecord.Visible = true;
totalrecord.Text = TotalrecordMessage;
}
public void Process()
{
_IsProduct = false;
_Name.Clear();
CategoryUrl.Clear();
_ProductUrlthread1.Clear();
_ProductUrlthread1.Clear();
Url.Clear();
_percent.Visible = false;
_Bar1.Value = 0;
_Url.Clear();
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_Stop = false;
time = 0;
#region canadacomputers.com
_IScanadacomputers = true;
_ScrapeUrl = "http://www.canadacomputers.com/asus/notebooks.php";
try
{
//_Worker1 = new IE();
//_Worker2 = new IE();
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category url of " + chkstorelist.Items[0].ToString() + " Website";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"hd-nav-prod-dropdn\"]");
if (_Collection != null)
{
HtmlNodeCollection _Collection11 = _Collection[0].SelectNodes(".//a");
if (_Collection11 != null)
{
foreach (HtmlNode node in _Collection11)
{
foreach (HtmlAttribute att in node.Attributes)
{
if (att.Name == "href")
try
{
if (att.Value.Trim() != string.Empty && att.Value.Trim() != "#")
CategoryUrl.Add((att.Value.ToLower().Contains("canadacomputers.com") ? "" : "http://www.canadacomputers.com") + att.Value.Replace("..", ""), "CANCOM" + node.InnerText.Trim());
}
catch
{ }
}
}
}
}
DisplayRecordProcessdetails("We are going to read product url from category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
if (File.Exists(Application.StartupPath + "/Files/Url.txt"))
{
FileInfo _Info = new FileInfo(Application.StartupPath + "/Files/Url.txt");
int Days = 14;
try
{
Days = Convert.ToInt32(Config.GetAppConfigValue("canadacomputers.com", "FrequencyOfCategoryScrapping"));
}
catch
{
}
if (_Info.CreationTime < DateTime.Now.AddDays(-Days))
_IsCategorypaging = true;
else
_IsCategorypaging = false;
}
else
_IsCategorypaging = true;
if (_IsCategorypaging)
{
int i = 0;
foreach (var Caturl in CategoryUrl)
{
try
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Caturl.Key;
BrandName1 = Caturl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = Caturl.Key;
BrandName2 = Caturl.Value;
_Work1.RunWorkerAsync();
}
}
catch { }
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
DisplayRecordProcessdetails("We are going to read product url from sub-category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
_401index = 0;
_IsSubcat = true;
foreach (var Caturl in subCategoryUrl)
{
try
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Caturl.Key;
BrandName1 = Caturl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = Caturl.Key;
BrandName2 = Caturl.Value;
_Work1.RunWorkerAsync();
}
}
catch (Exception exp)
{
}
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
System.Threading.Thread.Sleep(1000);
_Bar1.Value = 0;
_401index = 0;
#region Code to get and write urls from File
if (File.Exists(Application.StartupPath + "/Files/Url.txt"))
{
if (!_IsCategorypaging)
{
using (StreamReader Reader = new StreamReader(Application.StartupPath + "/Files/Url.txt"))
{
string line = "";
while ((line = Reader.ReadLine()) != null)
{
try
{
Url.Add(line.Split(new[] { "@#$#" }, StringSplitOptions.None)[0], line.Split(new[] { "@#$#" }, StringSplitOptions.None)[1]);
}
catch
{
}
}
}
}
}
foreach (var url in _ProductUrlthread1)
{
try
{
if (!Url.Keys.Contains(url.Key.ToLower()))
Url.Add(url.Key.ToLower(), url.Value);
}
catch
{
}
}
foreach (var url in _ProductUrlthread2)
{
try
{
if (!Url.Keys.Contains(url.Key.ToLower()))
Url.Add(url.Key.ToLower(), url.Value);
}
catch
{
}
}
// Code to write in file
if (_IsCategorypaging)
{
using (StreamWriter writer = new StreamWriter(Application.StartupPath + "/Files/Url.txt"))
{
foreach (var PrdUrl in Url)
{
writer.WriteLine(PrdUrl.Key + "@#$#" + PrdUrl.Value);
}
}
}
#endregion Code to get and write urls from File
_IsCategorypaging = false;
DisplayRecordProcessdetails("We are going to read Product information for " + chkstorelist.Items[0].ToString() + " Website", "Total products :" + Url.Count());
_IsProduct = true;
foreach (var PrdUrl in Url)
{
try
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = PrdUrl.Key;
BrandName1 = PrdUrl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = PrdUrl.Key;
BrandName2 = PrdUrl.Value;
_Work1.RunWorkerAsync();
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (Products.Count() > 0)
{
System.Threading.Thread.Sleep(1000);
_lblerror.Visible = true;
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
_Prd.ProductDatabaseIntegration(Products, "canadacomputers.com", 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='canadacomputers.com'");
_Mail.SendMail("OOPS there is no any product scrapped by app for canadacomputers.com Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='canadacomputers.com'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data canadacomputers.com Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#region closeIEinstance
try
{
_Worker1.Close();
_Worker2.Close();
}
catch
{
}
#endregion closeIEinstance
#endregion
_writer.Close();
this.Close();
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
Erorr_401_1 = true;
if (_IScanadacomputers)
{
try
{
int CounterError = 0;
do
{
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
Erorr_401_1 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_1 && CounterError < 20);
}
catch { }
}
int index = 0;
#region canadacomputers.com
if (_IsCategorypaging)
{
#region canadacomputers.com
if (!Erorr_401_1)
{
try
{
#region getChildCat
if (!_IsSubcat)
{
HtmlNodeCollection _SubCat = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"sub_cat1\"]");
if (_SubCat != null)
{
foreach (HtmlNode node in _SubCat)
{
foreach (HtmlNode subnode in node.SelectNodes(".//a"))
{
foreach (HtmlAttribute attr in subnode.Attributes)
{
if (attr.Name == "href")
{
try
{
subCategoryUrl.Add("http://www.canadacomputers.com" + attr.Value.Replace("..", ""), "CANCOM" + node.InnerText.Trim());
}
catch
{ }
}
}
}
}
}
}
#endregion getChildCat
HtmlNodeCollection coll = _Work1doc.DocumentNode.SelectNodes("//td[@class=\"productListing-data\"]/form");
if (coll != null)
{
int Stock = 0;
foreach (HtmlNode node in coll)
{
Stock = 0;
HtmlNodeCollection collStock = node.SelectNodes("..//div[@class=\"availability_text\"]");
if (collStock != null)
{
if (collStock[0].InnerText.ToLower().Contains("available online") && !collStock[0].InnerText.ToLower().Contains("not available online"))
Stock = 1;
}
if (Stock == 1)
{
HtmlNodeCollection collPrdUrl = node.SelectNodes("..//div[@class=\"item_description\"]/a");
if (collPrdUrl != null)
{
foreach (HtmlAttribute attr in collPrdUrl[0].Attributes)
{
if (attr.Name == "href")
{
try
{
if (!CheckUrlExist("http://www.canadacomputers.com" + attr.Value.Replace("..", "")))
_ProductUrlthread1.Add("http://www.canadacomputers.com" + attr.Value.Replace("..", ""), BrandName1);
}
catch
{
}
}
}
}
else
{
_writer.WriteLine(Url1 + " " + "workerexp1 " + "Product Url is not found");
}
}
}
try
{
int TotalRecords = 0;
int TotalPages = 0;
int CurrentPage = 1;
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//td[@class=\"pageHeading\"]/b");
if (_Collection != null)
{
int.TryParse(_Collection[0].InnerText.Trim(), out TotalRecords);
if (TotalRecords != 0)
{
if (TotalRecords % 20 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 20);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 20) + 1;
}
}
else
_writer.WriteLine(Url1 + " " + "workerexp1 " + "Total records Tags Not found");
}
for (int i = 2; i <= TotalPages; i++)
{
Erorr_401_1 = true;
try
{
int CounterError = 0;
do
{
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1.Contains("?") ? Url1 + "&page=" + i : Url1 + "?page=" + i));
Erorr_401_1 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_1 && CounterError < 20);
if (!Erorr_401_1)
{
HtmlNodeCollection coll1 = _Work1doc.DocumentNode.SelectNodes("//td[@class=\"productListing-data\"]/form");
if (coll != null)
{
foreach (HtmlNode node in coll1)
{
Stock = 0;
HtmlNodeCollection collStock = node.SelectNodes("..//div[@class=\"availability_text\"]");
if (collStock != null)
{
if (collStock[0].InnerText.ToLower().Contains("available online") && !collStock[0].InnerText.ToLower().Contains("not available online"))
Stock = 1;
}
if (Stock == 1)
{
HtmlNodeCollection collPrdUrl = node.SelectNodes("..//div[@class=\"item_description\"]/a");
if (collPrdUrl != null)
{
foreach (HtmlAttribute attr in collPrdUrl[0].Attributes)
{
if (attr.Name == "href")
{
try
{
if (!CheckUrlExist("http://www.canadacomputers.com" + attr.Value.Replace("..", "")))
_ProductUrlthread1.Add("http://www.canadacomputers.com" + attr.Value.Replace("..", ""), BrandName1);
}
catch
{
}
}
}
}
else
{
_writer.WriteLine(Url1 + " " + "workerexp1 " + "Product Url is not found");
}
}
}
}
}
}
catch { }
}
}
catch
{
_writer.WriteLine(Url1 + " " + "workerexp1 " + "Total records Tags Not found");
}
}
_401index++;
_Work.ReportProgress((_401index * 100 / (_IsSubcat == false ? CategoryUrl.Count() : subCategoryUrl.Count())));
#endregion canadacomputers.com
}
catch
{
}
}
}
else if (_IsProduct)
{
if (!Erorr_401_1)
{
try
{
GetProductInfo(_Work1doc, Url1, BrandName1);
}
catch (Exception exp)
{
_writer.WriteLine(Url1 + " " + " product page exception workerexp4 " + exp.Message);
}
}
_401index++;
_Work.ReportProgress((_401index * 100 / Url.Count()));
}
#endregion canadacomputers.com
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
Erorr_401_2 = true;
if (_IScanadacomputers)
{
try
{
int CounterError = 0;
do
{
try
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
Erorr_401_2 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_2 && CounterError < 20);
}
catch { }
}
int index = 0;
#region canadacomputers.com
if (_IsCategorypaging)
{
#region canadacomputers.com
if (!Erorr_401_2)
{
try
{
#region getChildCat
if (!_IsSubcat)
{
HtmlNodeCollection _SubCat = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"sub_cat1\"]");
if (_SubCat != null)
{
foreach (HtmlNode node in _SubCat)
{
foreach (HtmlNode subnode in node.SelectNodes(".//a"))
{
foreach (HtmlAttribute attr in subnode.Attributes)
{
if (attr.Name == "href")
{
try
{
subCategoryUrl.Add("http://www.canadacomputers.com" + attr.Value.Replace("..", ""), "CANCOM" + node.InnerText.Trim());
}
catch
{ }
}
}
}
}
}
}
#endregion getChildCat
HtmlNodeCollection coll = _Work1doc2.DocumentNode.SelectNodes("//td[@class=\"productListing-data\"]/form");
if (coll != null)
{
int Stock = 0;
foreach (HtmlNode node in coll)
{
Stock = 0;
HtmlNodeCollection collStock = node.SelectNodes("..//div[@class=\"availability_text\"]");
if (collStock != null)
{
if (collStock[0].InnerText.ToLower().Contains("available online") && !collStock[0].InnerText.ToLower().Contains("not available online"))
Stock = 1;
}
if (Stock == 1)
{
HtmlNodeCollection collPrdUrl = node.SelectNodes("..//div[@class=\"item_description\"]/a");
if (collPrdUrl != null)
{
foreach (HtmlAttribute attr in collPrdUrl[0].Attributes)
{
if (attr.Name == "href")
{
try
{
if (!CheckUrlExist("http://www.canadacomputers.com" + attr.Value.Replace("..", "")))
_ProductUrlthread1.Add("http://www.canadacomputers.com" + attr.Value.Replace("..", ""), BrandName2);
}
catch
{
}
}
}
}
else
{
_writer.WriteLine(Url2 + " " + "workerexp1 " + "Product Url is not found");
}
}
}
try
{
int TotalRecords = 0;
int TotalPages = 0;
int CurrentPage = 1;
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//td[@class=\"pageHeading\"]/b");
if (_Collection != null)
{
int.TryParse(_Collection[0].InnerText.Trim(), out TotalRecords);
if (TotalRecords != 0)
{
if (TotalRecords % 20 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 20);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 20) + 1;
}
}
else
_writer.WriteLine(Url2 + " " + "workerexp1 " + "Total records Tags Not found");
}
for (int i = 2; i <= TotalPages; i++)
{
Erorr_401_2 = true;
try
{
int CounterError = 0;
do
{
try
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2.Contains("?") ? Url2 + "&page=" + i : Url2 + "?page=" + i));
Erorr_401_2 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_2 && CounterError < 20);
if (!Erorr_401_2)
{
HtmlNodeCollection coll1 = _Work1doc2.DocumentNode.SelectNodes("//td[@class=\"productListing-data\"]/form");
if (coll != null)
{
foreach (HtmlNode node in coll1)
{
Stock = 0;
HtmlNodeCollection collStock = node.SelectNodes("..//div[@class=\"availability_text\"]");
if (collStock != null)
{
if (collStock[0].InnerText.ToLower().Contains("available online") && !collStock[0].InnerText.ToLower().Contains("not available online"))
Stock = 1;
}
if (Stock == 1)
{
HtmlNodeCollection collPrdUrl = node.SelectNodes("..//div[@class=\"item_description\"]/a");
if (collPrdUrl != null)
{
foreach (HtmlAttribute attr in collPrdUrl[0].Attributes)
{
if (attr.Name == "href")
{
try
{
if (!CheckUrlExist("http://www.canadacomputers.com" + attr.Value.Replace("..", "")))
_ProductUrlthread1.Add("http://www.canadacomputers.com" + attr.Value.Replace("..", ""), BrandName2);
}
catch
{
}
}
}
}
else
{
_writer.WriteLine(Url2 + " " + "workerexp1 " + "Product Url is not found");
}
}
}
}
}
}
catch { }
}
}
catch
{
_writer.WriteLine(Url2 + " " + "workerexp1 " + "Total records Tags Not found");
}
}
_401index++;
_Work1.ReportProgress((_401index * 100 / (_IsSubcat == false ? CategoryUrl.Count() : subCategoryUrl.Count())));
#endregion canadacomputers.com
}
catch
{
}
}
}
else if (_IsProduct)
{
if (!Erorr_401_2)
{
try
{
GetProductInfo(_Work1doc2, Url2, BrandName2);
}
catch (Exception exp)
{
_writer.WriteLine(Url2 + " " + " product page exception workerexp4 " + exp.Message);
}
}
_401index++;
_Work1.ReportProgress((_401index * 100 / Url.Count()));
}
#endregion canadacomputers.com
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public void GetProductInfo(HtmlAgilityPack.HtmlDocument _doc, string url, string Category)
{
BusinessLayer.Product product = new BusinessLayer.Product();
try
{
string Bullets = "";
#region title
HtmlNodeCollection formColl = _doc.DocumentNode.SelectNodes("//div[@class=\"item_title\"]/h1");
if (formColl != null)
product.Name = System.Net.WebUtility.HtmlDecode(formColl[0].InnerText).Trim();
else if (_doc.DocumentNode.SelectNodes("//title") != null)
product.Name = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//title")[0].InnerText).Trim();
else
_writer.WriteLine(url + " " + "title not found");
#endregion title
#region Price
string priceString = "";
double Price = 0;
if (_doc.DocumentNode.SelectNodes("//span[@id=\"SalePrice\"]") != null)
{
priceString = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//span[@id=\"SalePrice\"]")[0].InnerText).Replace("$", "").Trim();
double.TryParse(priceString, out Price);
if (Price != 0)
product.Price = Price.ToString(); //System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//span[@class=\"regular-price\"]/span[@class=\"price\"]")[0].InnerText).re;
else
_writer.WriteLine(url + " " + "Price not found");
}
else
_writer.WriteLine(url + " " + "Price not found");
#endregion Price
#region Brand
try
{
if (_doc.DocumentNode.SelectNodes("//span[@class=\"icon\"]/img") != null)
{
if (_doc.DocumentNode.SelectNodes("//span[@class=\"icon\"]/img")[0].Attributes["src"].Value.ToLower().Contains("logos"))
{
product.Brand = _doc.DocumentNode.SelectNodes("//span[@class=\"icon\"]/img")[0].Attributes["src"].Value.Replace("logos", "").Replace("/", "").Replace(".gif", "").Replace(".png", "").Replace(".jpg", "").Trim();
product.Manufacturer = _doc.DocumentNode.SelectNodes("//span[@class=\"icon\"]/img")[0].Attributes["src"].Value.Replace("logos", "").Replace("/", "").Replace(".gif", "").Replace(".png", "").Replace(".jpg", "").Trim();
}
}
}
catch
{
}
if (string.IsNullOrEmpty(product.Brand))
{
product.Brand = "JZ HOLDINGS";
product.Manufacturer = "JZ HOLDINGS";
}
#endregion Brand
#region Category
product.Category = string.IsNullOrEmpty(Category) ? "CANCOMJZ HOLDINGS" : Category;
#endregion Category
product.Currency = "CAD";
int descIndex = 0;
int specIndex = 0;
int stockIndex = 0;
#region description
string Description = "";
#region Get Description,stock abnd SpecificationIndex
HtmlNodeCollection index = _doc.DocumentNode.SelectNodes("//ul[@class=\"TabbedPanelsTabGroup\"]/li");
if (index != null)
{
int counter = 0;
foreach (HtmlNode node in index)
{
if (node.InnerText.Trim().ToLower().Trim() == "stock level")
stockIndex = counter;
else if (node.InnerText.Trim().ToLower().Trim() == "overview")
descIndex = counter;
else if (node.InnerText.Trim().ToLower().Trim() == "specifications")
specIndex = counter;
counter++;
}
}
#endregion Get Description,stock abnd SpecificationIndex
HtmlNodeCollection desCollection = _doc.DocumentNode.SelectNodes("//div[@class=\"TabbedPanelsContentGroup\"]/div");
if (descIndex != 0)
{
if (desCollection != null)
{
try
{
foreach (HtmlNode node in desCollection[descIndex].ChildNodes)
{
if (node.Name != "script")
{
Description = Description + node.InnerHtml;
}
}
Description = Removeunsuaalcharcterfromstring(StripHTML(Description).Trim());
try
{
if (Description.Length > 2000)
Description = Description.Substring(0, 1997) + "...";
}
catch
{
}
product.Description = System.Net.WebUtility.HtmlDecode(Description.Replace("Â", ""));
}
catch
{
_writer.WriteLine(url + " " + "Description not found");
}
}
else
_writer.WriteLine(url + " " + "Description not found");
}
else
_writer.WriteLine(url + " " + "Description not found");
#endregion description
#region BulletPoints
string Feature = "";
if (specIndex != 0)
{
if (desCollection != null)
{
string Header = "";
string Value = "";
int PointCounter = 1;
try
{
if (desCollection[specIndex].SelectNodes(".//td[@class=\"specification\"]") != null)
{
foreach (HtmlNode node in desCollection[specIndex].SelectNodes(".//td[@class=\"specification\"]"))
{
try
{
Header = System.Net.WebUtility.HtmlDecode(node.InnerText.Trim());
Value = System.Net.WebUtility.HtmlDecode(node.NextSibling.InnerText.Trim());
if (Value != "" && Header.Length < 100 && !Header.ToLower().Contains("warranty") && !Header.ToLower().Contains("return"))
{
Feature = " " + Header + " " + Value;
if (Feature.Length > 480)
Feature = Feature.Substring(0, 480);
if (Bullets.Length + Feature.Length + 2 <= PointCounter * 480)
Bullets = Bullets + Feature + ". ";
else
{
Bullets = Bullets + "@@" + Feature + ". ";
PointCounter++;
}
if (Header.ToLower() == "brand")
{
product.Brand = Value;
product.Manufacturer = Value;
}
}
}
catch { }
}
}
else
{
Bullets = Removeunsuaalcharcterfromstring(StripHTML(desCollection[specIndex].InnerText).Trim());
if (Bullets.Length > 1000)
Bullets = Bullets.Substring(0, 990) + "...";
}
}
catch { }
if (!string.IsNullOrEmpty(Bullets))
Bullets = Bullets.Trim();
}
else
_writer.WriteLine(url + " " + "Bullet Points not found");
}
else
_writer.WriteLine(url + " " + "Bullet Points not found");
if (Bullets.Length > 0)
{
Bullets = Removeunsuaalcharcterfromstring(StripHTML(Bullets).Trim());
string[] BulletPoints = Bullets.Split(new string[] { "@@" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < BulletPoints.Length; i++)
{
if (i == 0)
product.Bulletpoints1 = BulletPoints[i].ToString();
if (i == 1)
product.Bulletpoints2 = BulletPoints[i].ToString();
if (i == 2)
product.Bulletpoints3 = BulletPoints[i].ToString();
if (i == 3)
product.Bulletpoints4 = BulletPoints[i].ToString();
if (i == 4)
product.Bulletpoints5 = BulletPoints[i].ToString();
if (i > 4)
break;
}
}
if (string.IsNullOrEmpty(product.Description))
{
product.Description = product.Name;
if (string.IsNullOrEmpty(product.Bulletpoints1))
product.Bulletpoints1 = product.Name;
}
else if (string.IsNullOrEmpty(product.Bulletpoints1))
{
if (product.Description.Length >= 500)
product.Bulletpoints1 = product.Description.Substring(0, 497);
else
product.Bulletpoints1 = product.Description;
}
#endregion BulletPoints
#region Image
string Images = "";
HtmlNodeCollection imgCollection = _doc.DocumentNode.SelectNodes("//div[@class=\"prod_thumb\"]");
if (imgCollection != null)
{
if (imgCollection[0].SelectNodes(".//img") != null)
{
foreach (HtmlNode node in imgCollection[0].SelectNodes(".//img"))
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "src")
{
try
{
if (!node.Attributes["title"].Value.Trim().ToLower().Contains("image not available"))
Images = Images + attr.Value.Trim().Replace("40x40", "450x450") + ",";
}
catch
{
Images = Images + attr.Value.Trim().Replace("40x40", "450x450") + ",";
}
break;
}
}
}
}
}
else
_writer.WriteLine(url + " " + "Main Images not found");
if (string.IsNullOrEmpty(Images))
{
HtmlNodeCollection imgCollection1 = _doc.DocumentNode.SelectNodes("//div[@class=\"preview_img\"]/img");
if (imgCollection != null)
{
try
{
if (!imgCollection1[0].Attributes["title"].Value.Trim().ToLower().Contains("image not available"))
Images = imgCollection1[0].Attributes["src"].Value.Trim();
}
catch
{ Images = imgCollection1[0].Attributes["src"].Value.Trim(); }
}
}
if (Images.Length > 0)
{
if (Images.Contains(","))
Images = Images.Substring(0, Images.Length - 1);
}
product.Image = Images;
#endregion Image
product.Isparent = true;
#region sku
string sku = "";
if (_doc.DocumentNode.SelectNodes("//span[@class=\"itdetail\"]/strong") != null)
{
try
{
foreach (HtmlNode Node in _doc.DocumentNode.SelectNodes("//span[@class=\"itdetail\"]/strong"))
{
if (Node.InnerText.ToLower().Contains("part number:"))
product.ManPartNO = Removeunsuaalcharcterfromstring(StripHTML(Node.NextSibling.InnerText)).Replace("|", "").Trim();
else if (Node.InnerText.ToLower().Contains("item code:"))
{
// product.SKU =
// product.parentsku = string.IsNullOrEmpty(Removeunsuaalcharcterfromstring(StripHTML(Node.NextSibling.InnerText))) ? "" : "CANCOM" + Removeunsuaalcharcterfromstring(StripHTML(Node.NextSibling.InnerText)).Replace("|", "").Trim();
}
}
}
catch
{ }
}
else
_writer.WriteLine(url + " " + "Model not found");
if (_doc.DocumentNode.SelectNodes("//input[@name=\"item_id\"]") != null)
{
product.SKU = string.IsNullOrEmpty(Removeunsuaalcharcterfromstring(StripHTML(_doc.DocumentNode.SelectNodes("//input[@name=\"item_id\"]")[0].Attributes["value"].Value))) ? "" : "CANCOM" + Removeunsuaalcharcterfromstring(StripHTML(_doc.DocumentNode.SelectNodes("//input[@name=\"item_id\"]")[0].Attributes["value"].Value)).Replace("|", "").Trim();
product.parentsku = string.IsNullOrEmpty(Removeunsuaalcharcterfromstring(StripHTML(_doc.DocumentNode.SelectNodes("//input[@name=\"item_id\"]")[0].Attributes["value"].Value))) ? "" : "CANCOM" + Removeunsuaalcharcterfromstring(StripHTML(_doc.DocumentNode.SelectNodes("//input[@name=\"item_id\"]")[0].Attributes["value"].Value)).Replace("|", "").Trim();
}
else
_writer.WriteLine(url + " " + "Sku not found");
#endregion sku
#region stock
product.Stock = "0";
int Stock = 0;
if (desCollection != null)
{
string Header = "";
string Value = "";
int PointCounter = 1;
try
{
HtmlNodeCollection stockNodes = desCollection[stockIndex].SelectNodes(".//td");
if (stockNodes != null)
{
for (int i = 0; i < stockNodes.Nodes().Count(); i++)
{
if (stockNodes[i].InnerText.ToLower().Trim() == "online store")
{
int.TryParse(stockNodes[i + 1].InnerText.Trim(), out Stock);
break;
}
}
}
}
catch
{ Stock = 2; }
}
product.Stock = Stock > 1 ? "1" : "0";
#endregion stock
product.URL = url;
if (!string.IsNullOrEmpty(product.Image))
if (!product.Image.ToLower().Contains("ina.jpg"))
Products.Add(product);
}
catch (Exception exp)
{
_writer.WriteLine(url + " " + "Issue accured in reading product info from given product url. exp: " + exp.Message);
}
}
public bool CheckImageExist(string url)
{
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
try
{
response = (HttpWebResponse)request.GetResponse();
return true;
}
catch (WebException ex)
{
return false;
}
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename, decimal Price, string url)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.Parameters.AddWithValue("@URL", url);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed. Record Processed " + _401index;
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed. Record Processed " + _401index;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Go_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
}
private void btnsubmit_Click(object sender, System.EventArgs e)
{
Process();
}
public bool CheckUrlExist(string Url)
{
bool result = true;
try
{
string[] parts = Url.Split('&');
foreach (string part in parts)
{
if (part.ToLower().Contains("item_id"))
{
if ((from dic in _ProductUrlthread1
where dic.Key.IndexOf(part) >= 0
select dic).Count() == 0)
result = false;
}
}
}
catch
{
}
return result;
}
private void Form1_Shown(object sender, System.EventArgs e)
{
base.Show();
this.btnsubmit_Click(null, null);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
}
}
<file_sep>/Project 18 Toys Store/palyerborndate/palyerborndate/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using bestbuy;
using System.Text.RegularExpressions;
using System.Net;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
namespace palyerborndate
{
public partial class Form1 : Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region booltypevariable
bool _ISBuy = false;
bool _IsProduct = false;
bool _IsCategory = true;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
#endregion booltypevariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
#endregion Buinesslayervariable
#region intypevariable
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "http://www.warriorsandwonders.com/index.php?main_page=advanced_search_result&keyword=keywords&search_in_description=1&product_type=&kfi_blade_length_from=0&kfi_blade_length_to=15&kfi_overall_length_from=0&kfi_overall_length_to=30&kfi_serration=ANY&kfi_is_coated=ANY&kfo_blade_length_from=0&kfo_blade_length_to=8&kfo_overall_length_from=0&kfo_overall_length_to=20&kfo_serration=ANY&kfo_is_coated=ANY&kfo_assisted=ANY&kk_blade_length_from=0&kk_blade_length_to=15&fl_lumens_from=0&fl_lumens_to=18000&fl_num_cells_from=1&fl_num_cells_to=10&fl_num_modes_from=1&fl_num_modes_to=15&sw_blade_length_from=0&sw_blade_length_to=60&sw_overall_length_from=0&sw_overall_length_to=70&inc_subcat=1&pfrom=0.01&pto=10000.00&x=36&y=6&perPage=60";
string Category = "";
decimal Weight = 0;
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _ProductUrl = new List<string>();
List<string> _Name = new List<string>();
List<string> CategoryUrl = new List<string>();
Dictionary<string, string> Producturl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
ExtendedWebClient _Client2 = new ExtendedWebClient();
ExtendedWebClient _Client1 = new ExtendedWebClient();
ExtendedWebClient _Client3 = new ExtendedWebClient();
ExtendedWebClient _Client4 = new ExtendedWebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
StreamWriter writer = new StreamWriter(Application.StartupPath + "/log.txt");
#endregion htmlagility
#region supplier
List<Supplier> Suppliers = new List<Supplier>();
Supplier workingSupplier = new Supplier();
#endregion supplier
public Form1()
{
InitializeComponent();
Suppliers.Add(new Supplier { Url = "http://www.toysrus.com/shop/index.jsp?categoryId=2255956",Domain="http://www.toysrus.com/" StoreID = 1, Prefix = "TYRSCM", SupplierName = "toysrus.com" });
Suppliers.Add(new Supplier { Url = "http://www.toysrus.ca/home/index.jsp?categoryId=2567269",Domain="http://www.toysrus.ca/", StoreID = 2, Prefix = "TYRSCA", SupplierName = "toysrus.ca" });
Suppliers.Add(new Supplier { Url = "https://www.ebgames.ca/",Domain="https://www.ebgames.ca/", StoreID = 3, Prefix = "EBGMCA", SupplierName = "ebgames.ca" });
Suppliers.Add(new Supplier { Url = "http://www.gamestop.com/",Domain="http://www.gamestop.com/", StoreID = 4, Prefix = "GMSTPCM", SupplierName = "gamestop.com" });
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void Form1_Load(object sender, EventArgs e)
{
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
/****************BackGround worker *************************/
}
public void tim(int t)
{
time = 0;
timer1.Start();
try
{
while (time <= t)
{
Application.DoEvents();
}
}
catch (Exception) { }
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
time++;
}
private string StripHTML(string source)
{
try
{
string result;
// Remove HTML Development formatting
// Replace line breaks with space
// because browsers inserts space
result = source.Replace("\r", " ");
// Replace line breaks with space
// because browsers inserts space
result = result.Replace("\n", " ");
// Remove step-formatting
result = result.Replace("\t", string.Empty);
// Remove repeating spaces because browsers ignore them
result = System.Text.RegularExpressions.Regex.Replace(result,
@"( )+", " ");
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove the header (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*head([^>])*>", "<head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*head( )*>)", "</head>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<head>).*(</head>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all scripts (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*script([^>])*>", "<script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*script( )*>)", "</script>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//result = System.Text.RegularExpressions.Regex.Replace(result,
// @"(<script>)([^(<script>\.</script>)])*(</script>)",
// string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<script>).*(</script>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// remove all styles (prepare first by clearing attributes)
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*style([^>])*>", "<style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"(<( )*(/)( )*style( )*>)", "</style>",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(<style>).*(</style>)", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert tabs in spaces of <td> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*td([^>])*>", "\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line breaks in places of <BR> and <LI> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*br( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*li( )*>", "\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// insert line paragraphs (double line breaks) in place
// if <P>, <DIV> and <TR> tags
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*div([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*tr([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<( )*p([^>])*>", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove remaining tags like <a>, links, images,
// comments etc - anything that's enclosed inside < >
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<[^>]*>", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// replace special characters:
result = System.Text.RegularExpressions.Regex.Replace(result,
@" ", " ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"•", " * ",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"‹", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"›", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"™", "(tm)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"⁄", "/",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"<", "<",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@">", ">",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"©", "(c)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
@"®", "(r)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove all others. More can be added, see
// http://hotwired.lycos.com/webmonkey/reference/special_characters/
result = System.Text.RegularExpressions.Regex.Replace(result,
@"&(.{2,6});", string.Empty,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// for testing
//System.Text.RegularExpressions.Regex.Replace(result,
// this.txtRegex.Text,string.Empty,
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// make line breaking consistent
result = result.Replace("\n", "\r");
// Remove extra line breaks and tabs:
// replace over 2 breaks with 2 and over 4 tabs with 4.
// Prepare first to remove any whitespaces in between
// the escaped characters and remove redundant tabs in between line breaks
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\t)", "\t\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\t)( )+(\r)", "\t\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)( )+(\t)", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove redundant tabs
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+(\r)", "\r\r",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove multiple tabs following a line break with just one tab
result = System.Text.RegularExpressions.Regex.Replace(result,
"(\r)(\t)+", "\r\t",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Initial replacement target string for line breaks
string breaks = "\r\r\r";
// Initial replacement target string for tabs
string tabs = "\t\t\t\t\t";
for (int index = 0; index < result.Length; index++)
{
result = result.Replace(breaks, "\r\r");
result = result.Replace(tabs, "\t\t\t\t");
breaks = breaks + "\r";
tabs = tabs + "\t";
}
// That's it.
return result;
}
catch
{
return source;
}
}
public void GetCategoryInfo(HtmlAgilityPack.HtmlDocument _doc, string url)
{
List<BusinessLayer.InventorySync> PrdData = new List<BusinessLayer.InventorySync>();
string skus = "";
HtmlNodeCollection productCollection = _doc.DocumentNode.SelectNodes("//div[@id=\"ctl00_CC_ProductSearchResultListing_SearchProductListing\"]/ul//li");
if (productCollection != null)
{
foreach (HtmlNode prd in productCollection)
{
HtmlNodeCollection _CollectionCatLink = prd.SelectNodes(".//div[@class=\"prod-image\"]/a");
if (_CollectionCatLink != null)
{
foreach (HtmlNode node in _CollectionCatLink)
{
foreach (HtmlAttribute attr in node.Attributes)
{
if (attr.Name == "href")
if (!Producturl.Keys.Contains("http://www.bestToyStores/" + attr.Value))
{
HtmlNodeCollection _CollectionStock = prd.SelectNodes(".//ul[@class=\"prod-availability list-layout-prod-availability\"]");
if (_CollectionStock != null)
{
string sku = "";
foreach (HtmlAttribute attrStock in _CollectionStock[0].Attributes)
{
if (attrStock.Name == "data-sku")
sku = attrStock.Value.Trim();
}
if (sku != "")
{
try
{
Producturl.Add("http://www.bestToyStores/" + attr.Value, sku);
skus = skus + sku + "|";
#region Price
try
{
HtmlNodeCollection _price = prd.SelectNodes(".//div[@class=\"prodprice\"]/span[@class=\"amount\"]");
if (_price == null)
_price = prd.SelectNodes(".//div[@class=\"prodprice price-onsale\"]/span[@class=\"amount\"]");
if (_price != null)
{
BusinessLayer.InventorySync data = new BusinessLayer.InventorySync();
data.SKU = sku;
data.Price = _price[0].InnerText.Replace("$", "").Trim();
data.Stock = "1";
PrdData.Add(data);
}
}
catch { }
#endregion Price
}
catch { }
}
else
WriteLogEvent(url, "sku not found");
}
else
WriteLogEvent(url, "Availibility tag is not found");
}
}
}
}
else
WriteLogEvent(url, "prod-image tag is not found");
}
if (skus.Length > 0)
GetOnlineStock(skus, PrdData);
}
else
WriteLogEvent(url, "ctl00_CC_ProductSearchResultListing_SearchProductListing tag is not found");
}
public void GetProductInfo(HtmlAgilityPack.HtmlDocument _doc, string url)
{
BusinessLayer.Product product = new BusinessLayer.Product();
try
{
#region title
if (_doc.DocumentNode.SelectNodes("//meta[@property=\"og:title\"]") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//meta[@property=\"og:title\"]")[0].Attributes)
{
if (attr.Name == "content")
product.Name = System.Net.WebUtility.HtmlDecode(attr.Value);
}
}
else if (_doc.DocumentNode.SelectNodes("//h1[@itemprop=\"name\"]") != null)
product.Name = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//h1[@itemprop=\"name\"]")[0].InnerText.Trim());
else
WriteLogEvent(url, "title not found");
#endregion title
#region price
if (_doc.DocumentNode.SelectNodes("//div[@itemprop=\"price\"]") != null)
product.Price = _doc.DocumentNode.SelectNodes("//div[@itemprop=\"price\"]")[0].InnerText.Replace("$", "").Trim();
else
{
product.Price = "0";
WriteLogEvent(url, "Price not found");
}
#endregion price
#region Brand
if (_doc.DocumentNode.SelectNodes("//span[@class=\"brand-logo\"]//img") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//span[@class=\"brand-logo\"]//img")[0].Attributes)
{
if (attr.Name == "alt")
{
product.Brand = System.Net.WebUtility.HtmlDecode(attr.Value.Trim());
product.Manufacturer = System.Net.WebUtility.HtmlDecode(attr.Value.Trim());
}
}
if (product.Brand == "")
{
if (_doc.DocumentNode.SelectNodes("//div[@class=\"brand-logo\"]//a") != null)
{
product.Brand = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//div[@class=\"brand-logo\"]//a")[0].InnerText.Trim());
product.Manufacturer = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//div[@class=\"brand-logo\"]//a")[0].InnerText.Trim());
}
else
WriteLogEvent(url, "Brand not found");
}
}
else if (_doc.DocumentNode.SelectNodes("//div[@class=\"brand-logo\"]//a") != null)
{
product.Brand = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//div[@class=\"brand-logo\"]//a")[0].InnerText.Trim());
product.Manufacturer = System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//div[@class=\"brand-logo\"]//a")[0].InnerText.Trim());
}
else
WriteLogEvent(url, "Brand not found");
#endregion Brand
#region Category
if (_doc.DocumentNode.SelectNodes("//span[@property=\"itemListElement\"]//a") != null)
{
try
{
product.Category = System.Net.WebUtility.HtmlDecode("BBYCA" + _doc.DocumentNode.SelectNodes("//span[@property=\"itemListElement\"]//a")[1].InnerText.Trim());
}
catch
{ WriteLogEvent(url, "Category not found"); }
}
else
WriteLogEvent(url, "Category not found");
#endregion Category
product.Currency = "CAD";
#region description
string Description = "";
if (_doc.DocumentNode.SelectNodes("//div[@class=\"tab-overview-item\"]") != null)
{
foreach (HtmlNode node in _doc.DocumentNode.SelectNodes("//div[@class=\"tab-overview-item\"]"))
{
Description = Description + " " + node.InnerText.Trim();
}
Description = Removeunsuaalcharcterfromstring(StripHTML(Description).Trim());
try
{
if (Description.Length > 2000)
Description = Description.Substring(0, 1997) + "...";
}
catch
{
}
product.Description = System.Net.WebUtility.HtmlDecode(Description.Replace("Â", ""));
}
else
WriteLogEvent(url, "Description not found");
#endregion description
#region BulletPoints
string Feature = "";
string Bullets = "";
HtmlNodeCollection collection = _doc.DocumentNode.SelectNodes("//ul[@class=\"std-tablist\"]//li");
if (collection == null)
collection = _doc.DocumentNode.SelectNodes("//ul[@class=\"std-tablist nobpadding\"]//li");
if (collection != null)
{
string Header = "";
string Value = "";
int PointCounter = 1;
foreach (HtmlNode node in collection)
{
try
{
Header = System.Net.WebUtility.HtmlDecode(node.SelectNodes(".//span")[0].InnerText.Trim());
Value = System.Net.WebUtility.HtmlDecode(node.SelectNodes(".//div")[0].InnerText.Trim());
if (Value != "")
{
if (Header.ToLower() == "color" || Header.ToLower() == "colour")
product.Color = Value;
else if (Header.ToLower() == "size")
product.Size = Value;
else if (Header.ToLower() == "appropriate ages")
{
if (Value.ToLower().Contains("year"))
product.AgeUnitMeasure = "Year";
else
product.AgeUnitMeasure = "Month";
string childAge = System.Net.WebUtility.HtmlDecode(Value);
childAge = Regex.Replace(childAge, @"[^\d]", String.Empty);
int Age = 0;
int.TryParse(childAge, out Age);
product.MinimumAgeRecommend = Age == 0 || Age > 50 ? 1 : Age;
}
Feature = " " + Header + " " + Value;
if (Feature.Length > 480)
Feature = Feature.Substring(0, 480);
if (Bullets.Length + Feature.Length + 2 <= PointCounter * 480)
Bullets = Bullets + Feature + ". ";
else
{
Bullets = Bullets + "@@" + Feature + ". ";
PointCounter++;
}
}
}
catch { }
}
if (!string.IsNullOrEmpty(Bullets))
Bullets = Bullets.Trim();
}
else
WriteLogEvent(url, "BulletPoints not found");
#region ItemsInBox
if (_doc.DocumentNode.SelectNodes("//div[@class=\"tab-content-right dynamic-content-column\"]//li") != null)
Bullets = Bullets + "@@" + System.Net.WebUtility.HtmlDecode(_doc.DocumentNode.SelectNodes("//div[@class=\"tab-content-right dynamic-content-column\"]//li")[0].InnerText) + ". ";
if (Bullets.Length > 0)
{
Bullets = Removeunsuaalcharcterfromstring(StripHTML(Bullets).Trim());
string[] BulletPoints = Bullets.Split(new string[] { "@@" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < BulletPoints.Length; i++)
{
if (i == 0)
product.Bulletpoints1 = BulletPoints[i].ToString();
if (i == 1)
product.Bulletpoints2 = BulletPoints[i].ToString();
if (i == 2)
product.Bulletpoints3 = BulletPoints[i].ToString();
if (i == 3)
product.Bulletpoints4 = BulletPoints[i].ToString();
if (i == 4)
product.Bulletpoints5 = BulletPoints[i].ToString();
}
}
if (string.IsNullOrEmpty(product.Description))
{
product.Description = product.Name;
if (string.IsNullOrEmpty(product.Bulletpoints1))
product.Bulletpoints1 = product.Name;
}
else if (string.IsNullOrEmpty(product.Bulletpoints1))
{
if (product.Description.Length >= 500)
product.Bulletpoints1 = product.Description.Substring(0, 497);
else
product.Bulletpoints1 = product.Description;
}
#endregion ItemsInBox
#endregion BulletPoints
#region Image
string Images = "";
if (_doc.DocumentNode.SelectNodes("//div[@id=\"pdp-gallery\"]//img") != null)
{
foreach (HtmlAttribute attr in _doc.DocumentNode.SelectNodes("//div[@id=\"pdp-gallery\"]//img")[0].Attributes)
{
if (attr.Name == "src")
Images = attr.Value.Trim();
}
}
else
WriteLogEvent(url, "Main Images not found");
foreach (HtmlNode node in _doc.DocumentNode.SelectNodes("//script"))
{
if (node.InnerText.Contains("pdpProduct"))
{
try
{
string script = "{\"" + node.InnerText.Substring(node.InnerText.IndexOf("pdpProduct")).Replace("//]]>", "");
script = script.Substring(0, script.IndexOf("if(config)")).Trim();
script = script.Substring(0, script.Length - 1);
RootObject deserializedProduct = JsonConvert.DeserializeObject<RootObject>(script.Trim());
Images = "";
product.SKU = "BBYCA" + deserializedProduct.pdpProduct.sku;
product.parentsku = "BBYCA" + deserializedProduct.pdpProduct.sku;
int ImageCounter = 0;
foreach (AdditionalMedia image in deserializedProduct.pdpProduct.additionalMedia)
{
if (image.mimeType.ToLower() == "image")
{
ImageCounter++;
Images = Images + image.url + ",";
}
if (ImageCounter >= 9)
break;
}
if (Images.Length > 0 && Images.Contains(","))
Images = Images.Substring(0, Images.Length - 1);
}
catch
{
WriteLogEvent(url, "Json conversion failed for PDPproduct script");
}
break;
}
}
product.Image = Images;
#endregion Image
product.Isparent = true;
#region sku
if (product.SKU == "")
{
if (_doc.DocumentNode.SelectNodes("//span[@itemprop=\"productid\"]") != null)
{
product.SKU = "BBYCA" + _doc.DocumentNode.SelectNodes("//span[@itemprop=\"productid\"]")[0].InnerText;
product.parentsku = "BBYCA" + _doc.DocumentNode.SelectNodes("//span[@itemprop=\"productid\"]")[0].InnerText;
}
else
WriteLogEvent(url, "SKU not found");
}
#endregion sku
product.Stock = "1";
product.URL = url;
#region UPC
if (_doc.DocumentNode.SelectNodes("//div[@class=\"tab-overview-item\"]") != null)
{
foreach (HtmlNode node in _doc.DocumentNode.SelectNodes("//div[@class=\"tab-overview-item\"]"))
{
string Innertext = System.Web.HttpUtility.HtmlDecode(node.InnerText.ToLower()).ToLower();
if (Innertext.Contains("upc:"))
{
string UPC = GetUPC(Innertext.Substring(Innertext.IndexOf("upc:")).Replace("upc:", "").Trim());
if (UPC.Length > 0)
product.UPC = UPC;
break;
}
}
}
#endregion UPC
if (product.Brand.ToUpper() != "SOLOGEAR")
Products.Add(product);
}
catch
{ }
}
public string GetUPC(string Response)
{
string Result = "";
foreach (var ch in Response.ToCharArray())
{
if (char.IsNumber(ch))
Result = Result + ch;
else
break;
}
Int64 n;
bool isNumeric = Int64.TryParse(Result, out n);
if (n != 0)
return Result;
else
return "";
}
public bool GetOnlineStock(string skus, List<BusinessLayer.InventorySync> PrdData)
{
bool Result = false;
try
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("http://api.bestToyStores/availability/products?accept-language=en-CA&skus=" + skus + "&accept=application%2Fvnd.bestbuy.simpleproduct.v1%2Bjson");
HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string responseText = reader.ReadToEnd();
try
{
RootObject deserializedProduct = JsonConvert.DeserializeObject<RootObject>(responseText);
if (deserializedProduct != null)
{
foreach (Availability Avail in deserializedProduct.availabilities)
{
if (Avail.shipping.status == "InStock" || Avail.shipping.status == "InStockOnlineOnly")
{
if (Avail.scheduledDelivery)
{
try
{
try
{
foreach (BusinessLayer.InventorySync sync in PrdData)
{
if (sync.SKU == Avail.sku)
{
sync.Stock = "0";
break;
}
}
}
catch
{
}
Producturl.Remove(Producturl.First(m => m.Value == Avail.sku).Key);
}
catch (Exception EXP)
{
WriteLogEvent(Avail.sku, "Error accured in removing sku from dictionary for out of stock product." + EXP.Message);
}
}
}
else
{
try
{
try
{
foreach (BusinessLayer.InventorySync sync in PrdData)
{
if (sync.SKU == Avail.sku)
{
sync.Stock = "0";
break;
}
}
}
catch
{
}
Producturl.Remove(Producturl.First(m => m.Value == Avail.sku).Key);
}
catch (Exception EXP)
{
WriteLogEvent(Avail.sku, "Error accured in removing sku from dictionary for out of stock product." + EXP.Message);
}
}
}
}
}
catch
{
foreach (string sku in skus.Split('|'))
{
try
{
Producturl.Remove(Producturl.First(m => m.Value == sku).Key);
}
catch (Exception EXP)
{
WriteLogEvent(sku, "Error accured in removing sku from dictionary for out of stock product." + EXP.Message);
}
}
try
{
foreach (BusinessLayer.InventorySync sync in PrdData)
{
sync.Stock = "0";
}
}
catch
{
}
WriteLogEvent(skus, "Error accured in conversion of json to c# for stock");
}
}
catch
{ }
#region DbSyncSkuData
try
{
if (PrdData.Count() > 0)
{
BusinessLayer.SyncerProductData syncData = new BusinessLayer.SyncerProductData();
syncData.SyncInventory(PrdData, "BBYCA", 1);
}
}
catch
{ }
#endregion DbSyncSkuData
return Result;
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public void WriteLogEvent(string url, string Detail)
{
writer.WriteLine(Detail + "/t" + url);
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url1, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc, Url1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading produts from category page"); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / CategoryUrl.Count));
/****************end*******************/
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc, Url1);
}
catch
{ WriteLogEvent(Url1, "Issue accured in reading product Info."); }
/**********Report progress**************/
gridindex++;
_Work.ReportProgress((gridindex * 100 / Producturl.Count));
/****************end*******************/
}
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int counterReload = 0;
do
{
try
{
counterReload++;
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
Application.DoEvents();
}
catch
{
_Iserror = true;
}
} while (counterReload < 25 && _Iserror);
if (_Iserror)
WriteLogEvent(Url2, "issue accured in loading Given URL is not found");
if (_IsCategory && !_Iserror)
{
try
{
GetCategoryInfo(_Work1doc2, Url2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading produts from category page"); }
gridindex++;
_Work1.ReportProgress((gridindex * 100 / CategoryUrl.Count));
}
else if (_IsProduct && !_Iserror)
{
try
{
GetProductInfo(_Work1doc2, Url2);
}
catch
{ WriteLogEvent(Url2, "Issue accured in reading product Info."); }
gridindex++;
_Work1.ReportProgress((gridindex * 100 / Producturl.Count));
}
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
}
public string Removeunsuaalcharcterfromstring(string name)
{
return name.Replace("–", "-").Replace("ñ", "ñ").Replace("’", "'").Replace("’", "'").Replace("ñ", "ñ").Replace("–", "-").Replace(" ", "").Replace("Â", "").Trim();
}
private void Go_Click(object sender, EventArgs e)
{
_IsProduct = false;
_percent.Visible = false;
_Bar1.Value = 0;
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
#region ToyStores
try
{
foreach (Supplier supp in Suppliers)
{
workingSupplier = supp;
_IsCategory = false;
_IsProduct = false;
CategoryUrl.Clear();
Producturl.Clear();
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category Link for " + supp.SupplierName + " Website";
int counterReload = 0;
bool isError = false;
do
{
try
{
counterReload++;
_Work1doc.LoadHtml(_Client1.DownloadString(supp.Url));
isError = false;
Application.DoEvents();
tim(2);
}
catch
{
isError = true;
}
} while (isError && counterReload < 25);
try
{
if (supp.StoreID == 1)
{
HtmlNodeCollection _CollectionCatLink = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"ctl00_CC_ProductSearchResultListing_topPaging\"]//div//div//span[@class=\"display-total\"]");
_TotalRecords = Convert.ToInt32(_CollectionCatLink[0].InnerText.Trim());
if ((_TotalRecords % 32) == 0)
{
_Pages = Convert.ToInt32(_TotalRecords / 32);
}
else
{
_Pages = Convert.ToInt32(_TotalRecords / 32) + 1;
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
gridindex = 0;
_Bar1.Value = 0;
_percent.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read products from search page.";
_Stop = false;
time = 0;
_IsCategory = true;
tim(3);
totalrecord.Visible = true;
for (int Page = 1; Page <= _Pages; Page++)
{
CategoryUrl.Add("http://www.bestToyStores/Search/SearchResults.aspx?path=ca77b9b4beca91fe414314b86bb581f8en20&page=" + Page);
}
totalrecord.Text = "Total No Pages :" + CategoryUrl.Count.ToString();
}
#region categoryPageUrl
foreach (string url in CategoryUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url;
_Work.RunWorkerAsync();
}
else
{
Url2 = url;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion categoryPageUrl
_lblerror.Visible = true;
_lblerror.Text = "We are going to read product info.";
_IsCategory = false;
_IsProduct = true;
gridindex = 0;
totalrecord.Text = "Total No Products :" + Producturl.Count.ToString();
foreach (var url in Producturl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = url.Key; //"http://www.bestToyStores//en-CA/product/-/b0007063.aspx?path=57d9708c19625082a2c2820fd20a3b2cen02";// "http://www.bestToyStores/en-CA/product/traxxas-traxxas-x-maxx-brushless-electric-rc-monster-truck-blue-77076-4/10400679.aspx?path=e334459dbb1955f57c8d232171133dbben02";
_Work.RunWorkerAsync();
}
else
{
Url2 = url.Key;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#region InsertScrappedProductInDatabase
}
catch(Exception exp) {
_Mail.SendMail("Oops Some issue Occured in scrapping data"+supp.Url+" Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='BestToyStores'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data BestToyStores Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
# endregion ToyStores
writer.Close();
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
}
public class ExtendedWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest w = base.GetWebRequest(uri);
w.Timeout = 120000;
return w;
}
}
public class Supplier
{
public string Url { get; set; }
public string Domain { get; set; }
public string Prefix { get; set; }
public int StoreID { get; set; }
public string SupplierName { get; set; }
public decimal Currency { get; set; }
}
}
<file_sep>/Project2/Crawler_WithouSizes_Part2/Crawler_WithouSizes_Part2/Form1.cs
using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using Crawler_Without_Sizes_Part2;
using WatiN.Core;
namespace Crawler_WithouSizes_Part2
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region Buinesslayervariable
List<BusinessLayer.Product> Products = new List<BusinessLayer.Product>();
BusinessLayer.APPConfig Config = new BusinessLayer.APPConfig();
BusinessLayer.Mail _Mail = new BusinessLayer.Mail();
#endregion Buinesslayervariable
StreamWriter _writer = new StreamWriter(Application.StartupPath + "/test.csv");
#region booltypevariable
bool _Isfind = false;
bool _IS401games = true;
bool _Isreadywebbrowser1 = false;
bool _Isreadywebbrowser2 = false;
bool _IsProduct = false;
bool _IsCategory = true;
bool _IsCategorypaging = false;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
bool Erorr_401_1 = true;
bool Erorr_401_2 = true;
#endregion booltypevariable
#region intypevariable
int FindCounter = 0;
int _Workindex = 0;
int _WorkIndex1 = 0;
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
int _401index = 0;
#endregion intypevariable
#region stringtypevariable
string BrandName1 = "";
string BrandName2 = "";
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "";
string Bullets = "";
string _Description1 = "";
string _Description2 = "";
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
Dictionary<string, string> Url = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrlthread1 = new Dictionary<string, string>();
Dictionary<string, string> _ProductUrlthread2 = new Dictionary<string, string>();
List<string> _Name = new List<string>();
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
#region IeVariable
IE _Worker1 = null;
IE _Worker2 = null;
#endregion IeVariable
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public void DisplayRecordProcessdetails(string Message, string TotalrecordMessage)
{
_lblerror.Visible = true;
_lblerror.Text = Message;
totalrecord.Visible = true;
totalrecord.Text = TotalrecordMessage;
}
public void Process()
{
_IsProduct = false;
_Name.Clear();
CategoryUrl.Clear();
_ProductUrlthread1.Clear();
_ProductUrlthread1.Clear();
Url.Clear();
_percent.Visible = false;
_Bar1.Value = 0;
_Url.Clear();
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
#region 401Games
_IS401games = true;
_ScrapeUrl = "http://store.401games.ca/";
try
{
_Worker1 = new IE();
_Worker2 = new IE();
// _Worker1.Visible = false;
// _Worker2.Visible = false;
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category url of " + chkstorelist.Items[0].ToString() + " Website";
_Worker1.GoTo(_ScrapeUrl);
_Worker1.WaitForComplete();
System.Threading.Thread.Sleep(10000);
_Work1doc.LoadHtml(_Worker1.Html);
//HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"col left\"]");
//CategoryUrl = CommanFunction.GetCategoryUrl(_Collection, "ul", "//li/a", "http://store.401games.ca", "#st=&begin=1&nhit=40");
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"sub-menu\"]");
if (_Collection != null)
{
HtmlNodeCollection menu = _Collection[0].SelectNodes("..//ul[@class=\"submenu\"]//li//a");
foreach (HtmlNode node in menu)
{
foreach (HtmlAttribute att in node.Attributes)
{
if (att.Name == "href")
CategoryUrl.Add(att.Value, node.InnerText.Trim());
}
}
}
CategoryUrl.Remove("http://store.401games.ca/product/sitemap/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/shipping/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/returns/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/terms/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/terms/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/contact_us/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/contact_us/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/product/sitemap/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.cahttp://payd.moneris.com/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/privacy/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/catalog/93370C/pre-orders#st=&begin=1&nhit=40");
DisplayRecordProcessdetails("We are going to read product url from category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
if (File.Exists(Application.StartupPath + "/Files/Url.txt"))
{
FileInfo _Info = new FileInfo(Application.StartupPath + "/Files/Url.txt");
int Days = 14;
try
{
Days = Convert.ToInt32(Config.GetAppConfigValue("store.401games", "FrequencyOfCategoryScrapping"));
}
catch
{
}
if (_Info.CreationTime < DateTime.Now.AddDays(-Days))
_IsCategorypaging = true;
else
_IsCategorypaging = false;
}
else
_IsCategorypaging = true;
if (_IsCategorypaging)
{
foreach (var Caturl in CategoryUrl)
{
try
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Caturl.Key;
BrandName1 = Caturl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = Caturl.Key;
BrandName2 = Caturl.Value;
_Work1.RunWorkerAsync();
}
}
catch { }
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
System.Threading.Thread.Sleep(1000);
_Bar1.Value = 0;
_401index = 0;
#region Code to get and write urls from File
if (File.Exists(Application.StartupPath + "/Files/Url.txt"))
{
using (StreamReader Reader = new StreamReader(Application.StartupPath + "/Files/Url.txt"))
{
string line = "";
while ((line = Reader.ReadLine()) != null)
{
try
{
Url.Add(line.Split(new[] { "@#$#" }, StringSplitOptions.None)[0], line.Split(new[] { "@#$#" }, StringSplitOptions.None)[1]);
}
catch
{
}
}
}
}
foreach (var url in _ProductUrlthread1)
{
try
{
if (!Url.Keys.Contains(url.Key.ToLower()))
Url.Add(url.Key.ToLower(), url.Value);
}
catch
{
}
}
foreach (var url in _ProductUrlthread2)
{
try
{
if (!Url.Keys.Contains(url.Key.ToLower()))
Url.Add(url.Key.ToLower(), url.Value);
}
catch
{
}
}
// Code to write in file
if (_IsCategorypaging)
{
using (StreamWriter writer = new StreamWriter(Application.StartupPath + "/Files/Url.txt"))
{
foreach (var PrdUrl in Url)
{
writer.WriteLine(PrdUrl.Key + "@#$#" + PrdUrl.Value);
}
}
}
#endregion Code to get and write urls from File
_IsCategorypaging = false;
DisplayRecordProcessdetails("We are going to read Product information for " + chkstorelist.Items[0].ToString() + " Website", "Total products :" + Url.Count());
_IsProduct = true;
foreach (var PrdUrl in Url)
{
try
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = "http://store.401games.ca" + PrdUrl.Key;
BrandName1 = PrdUrl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = "http://store.401games.ca" + PrdUrl.Key;
BrandName2 = PrdUrl.Value;
_Work1.RunWorkerAsync();
}
}
catch
{
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
if (Products.Count() > 0)
{
System.Threading.Thread.Sleep(1000);
_lblerror.Visible = true;
BusinessLayer.ProductMerge _Prd = new BusinessLayer.ProductMerge();
_Prd.ProductDatabaseIntegration(Products, "store.401games", 1);
}
else
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='store.401games'");
_Mail.SendMail("OOPS there is no any product scrapped by app for store.401games Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
}
catch
{
BusinessLayer.DB _Db = new BusinessLayer.DB();
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='store.401games'");
_lblerror.Visible = true;
_Mail.SendMail("Oops Some issue Occured in scrapping data store.401games Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
}
#region closeIEinstance
try
{
_Worker1.Close();
_Worker2.Close();
}
catch
{
}
#endregion closeIEinstance
#endregion
_writer.Close();
this.Close();
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
Erorr_401_1 = true;
if (_IS401games)
{
if (_IsCategorypaging)
{
try
{
int CounterError = 0;
do
{
try
{
_Worker1.GoTo(Url1);
Erorr_401_1 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_1 && CounterError < 20);
}
catch
{
_Iserror = true;
}
}
else if (_IsProduct)
{
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
Erorr_401_1 = false;
}
catch
{
Erorr_401_1 = true;
}
}
}
else
{
if (!_IsProduct)
{
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
}
catch
{
_Iserror = true;
}
}
}
int index = 0;
#region 401games
if (_IS401games)
{
#region 401categorypaging
if (_IsCategorypaging)
{
if (!Erorr_401_1)
{
try
{
_Worker1.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
Erorr_401_1 = true;
if (_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"pages\"")) && checkcounter < 10000);
}
checkcounter = 0;
#endregion CheckPageLoaded
_Work1doc.LoadHtml(_Worker1.Html);
if (_IsCategorypaging)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"pages\"]/ul/li");
int TotalRecords = Convert.ToInt32(_Collection[_Collection.Count - 1].SelectNodes("span")[0].InnerText.Trim());
int TotalPages = 0;
int CurrentPage = 1;
if (TotalRecords % 40 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 40);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 40) + 1;
}
HtmlNodeCollection _Collection1 = _Work1doc.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection1)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread1.Keys.Contains(_Attribute.Value))
{
try
{
_ProductUrlthread1.Add(_Attribute.Value, BrandName1);
}
catch
{
}
}
}
}
}
//for (int i = 0; i < TotalPages; i++)
//{
// SubCategoryUrl.Add(Url1.Substring(0,Url1.IndexOf("#")) + "#st=&begin=" + ((i * 40) + 1) + "&nhit=40");
//}
string ClickTest = "Next";
bool Isexist = false;
if (TotalPages > 1)
{
while (!Isexist)
{
Isexist = true;
try
{
DivCollection Div = _Worker1.Divs.Filter(Find.ByClass("pages"));
LinkCollection _Links = Div[0].Links;
foreach (Link _Link in _Links)
{
if (_Link.InnerHtml.Trim() == ClickTest)
{
Isexist = false;
_Link.Click();
_Worker1.WaitForComplete();
if (ClickTest == "Next")
{
checkcounter = 0;
if (_Worker1.Html == null || _Worker1.Html.ToLower().Contains(_ProductUrlthread1.ToArray()[_ProductUrlthread1.Count - 1].Key.ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker1.Html == null || _Worker1.Html.ToLower().Contains(_ProductUrlthread1.ToArray()[_ProductUrlthread1.Count - 1].Key.ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"pages\"")) && checkcounter < 10000);
}
_Work1doc.LoadHtml(_Worker1.Html);
HtmlNodeCollection _Collection2 = _Work1doc.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection2)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread1.Keys.Contains(_Attribute.Value))
{
try
{
_ProductUrlthread1.Add(_Attribute.Value, BrandName1);
}
catch
{
}
}
else
{
string test = _Attribute.Value;
}
}
}
}
}
else
{
ClickTest = "Next";
}
break;
}
}
}
catch (Exception exp)
{
Isexist = false;
if (ClickTest == "Next")
{
if (!WebUtility.UrlDecode(_Worker1.Url).ToLower().Contains("begin=1&"))
{
ClickTest = "Previous";
}
}
else
{
ClickTest = "Next";
}
_writer.WriteLine("worker1exp3" + exp.Message);
}
}
}
}
}
catch (Exception exp)
{
_writer.WriteLine("workerexp4" + exp.Message);
}
}
_401index++;
_Work.ReportProgress((_401index * 100 / CategoryUrl.Count()));
}
#endregion 401categorypaging
else if (_IsProduct)
{
_401index++;
_Work.ReportProgress((_401index * 100 / Url.Count()));
}
}
#endregion 401games
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
Erorr_401_2 = true;
if (_IS401games)
{
if (_IsCategorypaging)
{
try
{
int CounterError = 0;
do
{
try
{
_Worker2.GoTo(Url2);
Erorr_401_2 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_2 && CounterError < 20);
}
catch
{
_Iserror = true;
}
}
else if (_IsProduct)
{
try
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
Erorr_401_2 = false;
}
catch
{
Erorr_401_2 = true;
}
}
}
else
{
if (!_IsProduct)
{
try
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
}
catch
{
_Iserror = true;
}
}
}
int index = 0;
#region 401games
if (_IS401games)
{
#region 401categorypaging
if (_IsCategorypaging)
{
if (!Erorr_401_2)
{
try
{
_Worker2.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
Erorr_401_2 = true;
if (_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"pages\"")) && checkcounter < 10000);
}
checkcounter = 0;
#endregion CheckPageLoaded
_Work1doc2.LoadHtml(_Worker2.Html);
if (_IsCategorypaging)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"pages\"]/ul/li");
int TotalRecords = Convert.ToInt32(_Collection[_Collection.Count - 1].SelectNodes("span")[0].InnerText.Trim());
int TotalPages = 0;
int CurrentPage = 1;
if (TotalRecords % 40 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 40);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 40) + 1;
}
HtmlNodeCollection _Collection1 = _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection1)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread2.Keys.Contains(_Attribute.Value))
{
try
{
_ProductUrlthread2.Add(_Attribute.Value, BrandName2);
}
catch
{
}
}
}
}
}
string ClickTest = "Next";
bool Isexist = false;
if (TotalPages > 1)
{
while (!Isexist)
{
Isexist = true;
try
{
DivCollection Div = _Worker2.Divs.Filter(Find.ByClass("pages"));
LinkCollection _Links = Div[0].Links;
foreach (Link _Link in _Links)
{
if (_Link.InnerHtml.Trim() == ClickTest)
{
Isexist = false;
_Link.Click();
_Worker2.WaitForComplete();
if (ClickTest == "Next")
{
checkcounter = 0;
if (_Worker2.Html == null || _Worker2.Html.ToLower().Contains(_ProductUrlthread2.ToArray()[_ProductUrlthread2.Count - 1].Key.ToString().ToLower()) || !_Worker2.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker2.Html == null || _Worker2.Html.ToLower().Contains(_ProductUrlthread2.ToArray()[_ProductUrlthread2.Count - 1].Key.ToString().ToLower()) || !_Worker2.Html.ToLower().Contains("class=\"pages\"")) && checkcounter < 10000);
}
_Work1doc2.LoadHtml(_Worker2.Html);
HtmlNodeCollection _Collection2 = _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection2)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread2.Keys.Contains(_Attribute.Value))
{
try
{
_ProductUrlthread2.Add(_Attribute.Value, BrandName2);
}
catch
{
}
}
else
{
string test = _Attribute.Value;
}
}
}
}
}
else
{
ClickTest = "Next";
}
break;
}
}
}
catch (Exception exp)
{
Isexist = false;
Isexist = false;
if (ClickTest == "Next")
{
if (!WebUtility.UrlDecode(_Worker2.Url).ToLower().Contains("begin=1&"))
{
ClickTest = "Previous";
}
}
else
{
ClickTest = "Next";
}
_writer.WriteLine("_Worker2xp3" + exp.Message);
}
}
}
}
}
catch (Exception exp)
{
_writer.WriteLine("worker1exp4" + exp.Message);
}
}
_401index++;
_Work1.ReportProgress((_401index * 100 / CategoryUrl.Count()));
}
#endregion 401categorypaging
else if (_IsProduct)
{
_401index++;
_Work1.ReportProgress((_401index * 100 / Url.Count()));
}
}
#endregion 401games
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
#region 401games
if (_IS401games)
{
if (_IsProduct && !Erorr_401_1)
{
int index = 0;
index = gridindex;
gridindex++;
try
{
BusinessLayer.Product Product = new BusinessLayer.Product();
Product.URL = Url1;
Product.Isparent = true;
#region title
HtmlNodeCollection _Title = _Work1doc.DocumentNode.SelectNodes("//h1[@class=\"title product\"]");
if (_Title != null)
Product.Name = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "");
else
{
HtmlNodeCollection _Title1 = _Work1doc.DocumentNode.SelectNodes("//h1");
if (_Title1 != null)
Product.Name = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())).Replace(">", "").Replace("<", "");
}
#endregion title
#region description
_Description1 = "";
HtmlNodeCollection _description = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab_desc\"]");
if (_description != null)
{
_Description1 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description[0].InnerHtml.Replace("Product Description", "")).Trim());
}
else
{
HtmlNodeCollection _description1 = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ldesc\"]");
if (_description != null)
{
_Description1 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description1[0].InnerHtml).Trim());
}
}
try
{
if (_Description1.Length > 2000)
_Description1 = _Description1.Substring(0, 1997) + "...";
}
catch
{
}
Product.Description = System.Net.WebUtility.HtmlDecode(_Description1.Replace("Â", "").Replace(">", "").Replace("<", ""));
#endregion description
#region manufacturer
Product.Manufacturer = BrandName1;
Product.Brand = BrandName1;
#endregion manufacturer
#region For decsription empty
try
{
if (String.IsNullOrEmpty(Product.Description))
{
Product.Description = Product.Name.ToString().Replace(">", "").Replace("<", "");
Product.Bulletpoints1 = Product.Name.ToString().Replace(">", "").Replace("<", "");
}
else
{
if (Product.Description.Length > 500)
Product.Bulletpoints1 = Product.Description.Substring(0, 497);
else
Product.Bulletpoints1 = Product.Description;
}
}
catch
{
}
#endregion For decsription empty
#region currency
Product.Currency = "CDN";
#endregion currency
#region price,stock
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.Trim() == "0")
{
Product.Stock = "0";
}
else
{
Product.Stock = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.ToLower().Replace("in-stock :", "").Trim();
}
}
else if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.Trim() == "0")
{
Product.Stock = "0";
}
else
{
Product.Stock = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.ToLower().Replace("in-stock :", "").Trim();
}
}
else if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Trim() == "0")
{
Product.Stock = "0";
}
else
{
Product.Stock = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Replace("in-stock :", "").Trim();
}
}
try
{
if ((Convert.ToInt32(Product.Stock) > 30) || String.IsNullOrEmpty(Product.Stock))
{
Product.Stock = "30";
}
}
catch
{
}
HtmlNode _Node = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"prices\"]")[0];
if (_Node != null)
{
if (_Node.SelectNodes(".//div[@class=\"discounted-price\"]") != null)
{
Product.Price = _Node.SelectNodes(".//div[@class=\"discounted-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
else if (_Node.SelectNodes(".//div[@class=\"regular-price\"]") != null)
{
Product.Price = _Node.SelectNodes(".//div[@class=\"regular-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
}
#endregion price,stock
#region sku
try
{
if (String.IsNullOrEmpty(Product.Price))
{
Product.Price = "0";
}
if (Convert.ToDecimal(Product.Price) > 0)
{
Product.SKU = GenrateSkuFromDatbase(CommanFunction.GenerateSku("ST4GAM", CommanFunction.Removeunsuaalcharcterfromstring(Product.Name.Trim())), CommanFunction.Removeunsuaalcharcterfromstring(Product.Name.Trim()), "store.401games", Convert.ToDecimal(Product.Price), Url1);
Product.parentsku = Product.SKU;
}
}
catch
{
Product.SKU = "";
}
#endregion sku
#region Image
if (_Work1doc.DocumentNode.SelectNodes("//img[@id=\"main_image\"]") != null)
{
foreach (HtmlAttribute _Attribute in _Work1doc.DocumentNode.SelectNodes("//img[@id=\"main_image\"]")[0].Attributes)
{
if (_Attribute.Name == "src")
{
Product.Image = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
else if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img") != null)
{
foreach (HtmlAttribute _Attribute in _Work1doc.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img")[0].Attributes)
{
if (_Attribute.Name == "src")
{
Product.Image = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
#endregion Image
#region category
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"breadcrumbs\"]//ul//li[@class=\"category_path\"]//a") != null)
{
Product.Category = "ST4GAM" + _Work1doc.DocumentNode.SelectNodes("//div[@class=\"breadcrumbs\"]//ul//li[@class=\"category_path\"]//a")[0].InnerText.Trim();
}
#endregion category
#region setQuantityTo0IfLessthen3
if (string.IsNullOrEmpty(Product.Stock))
Product.Stock = "0";
Product.Stock =Convert.ToInt32( Product.Stock) < 3 ? "0 ": (Convert.ToInt32( Product.Stock)-2).ToString();
#endregion setQuantityTo0IfLessthen3
Products.Add(Product);
}
catch (Exception exp)
{
_writer.WriteLine("worker issue for product url" + Url1 + " " + exp.Message);
}
}
}
#endregion 401games
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
#region 401games
if (_IS401games)
{
if (_IsProduct && !Erorr_401_2)
{
int index = 0;
index = gridindex;
gridindex++;
try
{
BusinessLayer.Product Product = new BusinessLayer.Product();
Product.URL = Url2;
Product.Isparent = true;
#region title
HtmlNodeCollection _Title = _Work1doc2.DocumentNode.SelectNodes("//h1[@class=\"title product\"]");
if (_Title != null)
Product.Name = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "");
else
{
HtmlNodeCollection _Title1 = _Work1doc2.DocumentNode.SelectNodes("//h1");
if (_Title1 != null)
Product.Name = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())).Replace(">", "").Replace("<", "");
}
#endregion title
#region description
_Description2 = "";
HtmlNodeCollection _description = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab_desc\"]");
if (_description != null)
{
_Description2 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description[0].InnerHtml.Replace("Product Description", "")).Trim());
}
else
{
HtmlNodeCollection _description1 = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ldesc\"]");
if (_description1 != null)
{
_Description2 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description1[0].InnerHtml).Trim());
}
}
try
{
if (_Description2.Length > 2000)
{
_Description2 = _Description2.Substring(0, 1997) + "...";
}
}
catch
{
}
Product.Description = System.Net.WebUtility.HtmlDecode(_Description2.Replace("Â", "").Replace(">", "").Replace("<", ""));
#endregion description
#region manufacturer
Product.Manufacturer = BrandName2;
Product.Brand = BrandName2;
#endregion manufacturer
#region For decsription empty
try
{
if (String.IsNullOrEmpty(Product.Description))
{
Product.Description = Product.Name.ToString().Replace(">", "").Replace("<", "");
Product.Bulletpoints1 = Product.Name.ToString().Replace(">", "").Replace("<", "");
}
else
{
if (Product.Description.Length > 500)
Product.Bulletpoints1 = Product.Description.Substring(0, 497);
else
Product.Bulletpoints1 = Product.Description;
}
}
catch
{
}
#endregion For decsription empty
#region currency
Product.Currency = "CDN";
#endregion currency
#region price,stock
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.Trim() == "0")
{
Product.Stock = "0";
}
else
{
Product.Stock = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.ToLower().Replace("in-stock :", "").Trim();
}
}
else if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.Trim() == "0")
{
Product.Stock = "0";
}
else
{
Product.Stock = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.ToLower().Replace("in-stock :", "").Trim();
}
}
else if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Trim() == "0")
{
Product.Stock = "0";
}
else
{
Product.Stock = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Replace("in-stock :", "").Trim();
}
}
try
{
if ((Convert.ToInt32(Product.Stock) > 30) || String.IsNullOrEmpty(Product.Stock))
{
Product.Stock = "30";
}
}
catch
{
}
HtmlNode _Node = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"prices\"]")[0];
if (_Node != null)
{
if (_Node.SelectNodes(".//div[@class=\"discounted-price\"]") != null)
{
Product.Price = _Node.SelectNodes(".//div[@class=\"discounted-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
else if (_Node.SelectNodes(".//div[@class=\"regular-price\"]") != null)
{
Product.Price = _Node.SelectNodes(".//div[@class=\"regular-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
}
#endregion price,stock
#region sku
try
{
if (String.IsNullOrEmpty(Product.Price))
{
Product.Price = "0";
}
if (Convert.ToDecimal(Product.Price) > 0)
{
Product.SKU = GenrateSkuFromDatbase(CommanFunction.GenerateSku("ST4GAM", CommanFunction.Removeunsuaalcharcterfromstring(Product.Name.Trim())), CommanFunction.Removeunsuaalcharcterfromstring(Product.Name.ToString().Trim()), "store.401games", Convert.ToDecimal(Product.Price), Url2);
Product.parentsku = Product.SKU;
}
}
catch
{
Product.SKU = "";
}
#endregion sku
#region Image
if (_Work1doc2.DocumentNode.SelectNodes("//img[@id=\"main_image\"]") != null)
{
foreach (HtmlAttribute _Attribute in _Work1doc2.DocumentNode.SelectNodes("//img[@id=\"main_image\"]")[0].Attributes)
{
if (_Attribute.Name == "src")
{
Product.Image = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
else if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img") != null)
{
foreach (HtmlAttribute _Attribute in _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img")[0].Attributes)
{
if (_Attribute.Name == "src")
{
Product.Image = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
#endregion Image
#region category
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"breadcrumbs\"]//ul//li[@class=\"category_path\"]//a") != null)
{
Product.Category = "ST4GAM" + _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"breadcrumbs\"]//ul//li[@class=\"category_path\"]//a")[0].InnerText.Trim();
}
#endregion category
#region setQuantityTo0IfLessthen3
if (string.IsNullOrEmpty(Product.Stock))
Product.Stock = "0";
Product.Stock = Convert.ToInt32(Product.Stock) < 3 ? "0 " : (Convert.ToInt32(Product.Stock) - 2).ToString();
#endregion setQuantityTo0IfLessthen3
Products.Add(Product);
}
catch (Exception exp)
{
_writer.WriteLine("worker issue for product url" + Url2 + " " + exp.Message);
}
}
}
#endregion 401games
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename, decimal Price,string url)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.Parameters.AddWithValue("@URL", url);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Go_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
}
private void btnsubmit_Click(object sender, System.EventArgs e)
{
Process();
}
private void Form1_Shown(object sender, System.EventArgs e)
{
base.Show();
this.btnsubmit_Click(null, null);
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
}
}
<file_sep>/Project9-scubagearcanada/Crawler_WithouSizes_Part3/Crawler_WithouSizes_Part3/BusinessLayer/Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Crawler_WithouSizes_Part7.BusinessLayer
{
public class Product
{
public string SKU { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Weight { get; set; }
public string Bulletpoints { get; set; }
public string Manufacturer { get; set; }
public string Brand { get; set; }
public string Price { get; set; }
public string Currency { get; set; }
public string Stock { get; set; }
public string Image { get; set; }
public string URL { get; set; }
public string Size { get; set; }
public string Color { get; set; }
public bool Isparent { get; set; }
public string parentsku { get; set; }
public string Bulletpoints1 { get; set; }
public string Bulletpoints2 { get; set; }
public string Bulletpoints3 { get; set; }
public string Bulletpoints4 { get; set; }
public string Bulletpoints5 { get; set; }
public string Category { get; set; }
}
}
<file_sep>/Project2/copy/Crawler_WithouSizes_Part2/Crawler_WithouSizes_Part2/Form1.cs
using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using HtmlAgilityPack;
using System.Net;
using System.Net.Mail;
using Crawler_Without_Sizes_Part2;
using WatiN.Core;
namespace Crawler_WithouSizes_Part2
{
public partial class Form1 : System.Windows.Forms.Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
#region booltypevariable
bool _Isfind = false;
bool _IS401games = true;
bool _Isreadywebbrowser1 = false;
bool _Isreadywebbrowser2 = false;
bool _IsProduct = false;
bool _IsCategory = true;
bool _IsCategorypaging = false;
bool _Issubcat = false;
bool _Stop = false;
bool _Iscompleted = false;
bool Erorr_401_1 = true;
bool Erorr_401_2 = true;
#endregion booltypevariable
#region intypevariable
int FindCounter = 0;
int _Workindex = 0;
int _WorkIndex1 = 0;
int _Pages = 0;
int _TotalRecords = 0;
int gridindex = 0;
int time = 0;
int _401index = 0;
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string _ScrapeUrl = "";
string Bullets = "";
string _Description1 = "";
string _Description2 = "";
#endregion listtypevariable
#region listtypevariable
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
List<string> _ProductUrl = new List<string>();
List<string> _ProductUrlthread1 = new List<string>();
List<string> _ProductUrlthread2 = new List<string>();
List<string> _Name = new List<string>();
List<string> CategoryUrl = new List<string>();
List<string> SubCategoryUrl = new List<string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
#region IeVariable
IE _Worker1 = null;
IE _Worker2 = null;
#endregion IeVariable
DataTable _Tbale = new DataTable();
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork1);
#endregion backrgoundworketevendeclaration
}
public void DisplayRecordProcessdetails(string Message, string TotalrecordMessage)
{
_lblerror.Visible = true;
_lblerror.Text = Message;
totalrecord.Visible = true;
totalrecord.Text = TotalrecordMessage;
}
public void Process()
{
_IsProduct = false;
_Name.Clear();
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_ProductUrlthread1.Clear();
_ProductUrlthread1.Clear();
_ProductUrl.Clear();
_percent.Visible = false;
_Bar1.Value = 0;
_Url.Clear();
_Tbale.Rows.Clear();
_Tbale.Columns.Clear();
dataGridView1.Rows.Clear();
DataColumn _Dc = new DataColumn();
_Dc.ColumnName = "Rowid";
_Dc.AutoIncrement = true;
_Dc.DataType = typeof(int);
_Dc.AutoIncrementSeed = 1;
_Dc.AutoIncrementStep = 1;
_Tbale.Columns.Add(_Dc);
_Tbale.Columns.Add("SKU", typeof(string));
_Tbale.Columns.Add("Product Name", typeof(string));
_Tbale.Columns.Add("Product Description", typeof(string));
_Tbale.Columns.Add("Bullet Points", typeof(string));
_Tbale.Columns.Add("Manufacturer", typeof(string));
_Tbale.Columns.Add("Brand Name", typeof(string));
_Tbale.Columns.Add("Price", typeof(string));
_Tbale.Columns.Add("Currency", typeof(string));
_Tbale.Columns.Add("In Stock", typeof(string));
_Tbale.Columns.Add("Image URL", typeof(string));
_Tbale.Columns.Add("URL", typeof(string));
_lblerror.Visible = false;
_Pages = 0;
_TotalRecords = 0;
gridindex = 0;
_IsCategory = true;
_Stop = false;
time = 0;
#region 402Games
_IS401games = true;
_ScrapeUrl = "http://store.401games.ca/";
try
{
_Worker1 = new IE();
// _Worker2 = new IE();
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category url of " + chkstorelist.Items[0].ToString() + " Website";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"col left\"]");
CategoryUrl = CommanFunction.GetCategoryUrl(_Collection, "ul", "//li/a", "http://store.401games.ca", "#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/product/sitemap/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/shipping/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/returns/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/terms/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/terms/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/contact_us/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/contact_us/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/product/sitemap/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.cahttp://payd.moneris.com/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/service/privacy/#st=&begin=1&nhit=40");
CategoryUrl.Remove("http://store.401games.ca/catalog/93370C/pre-orders#st=&begin=1&nhit=40");
if (CategoryUrl.Count() > 0)
{
DisplayRecordProcessdetails("We are going to read product url from category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
_IsCategorypaging = true;
foreach (string Caturl in CategoryUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Caturl;
_Work.RunWorkerAsync();
}
else
{
Url2 = Caturl;
_Work1.RunWorkerAsync();
}
break;
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
_Bar1.Value = 0;
_401index = 0;
_IsCategorypaging = false;
_ProductUrl = _ProductUrlthread1.Concat(_ProductUrlthread2).ToList();
DisplayRecordProcessdetails("We are going to read Product information for " + chkstorelist.Items[0].ToString() + " Website", "Total products :" + _ProductUrl.Count());
_IsProduct = true;
foreach (string PrdUrl in _ProductUrl)
{
while (_Work.IsBusy && _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = "http://store.401games.ca"+PrdUrl;
_Work.RunWorkerAsync();
}
else
{
Url2 ="http://store.401games.ca"+ PrdUrl;
_Work1.RunWorkerAsync();
}
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
MessageBox.Show("Process Completed.");
}
catch
{
}
#region closeIEinstance
try
{
_Worker1.Close();
_Worker2.Close();
}
catch
{
}
#endregion closeIEinstance
#endregion
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
if (_IS401games)
{
if (_IsCategorypaging)
{
try
{
Erorr_401_1 = true;
int CounterError = 0;
do
{
try
{
_Worker1.GoTo(Url1);
Erorr_401_1 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_1 && CounterError < 20);
}
catch
{
_Iserror = true;
}
}
else if (_IsProduct)
{
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
}
catch
{
_Iserror = true;
}
}
}
else
{
if (_IsProduct)
{
try
{
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
}
catch
{
_Iserror = true;
}
}
}
int index = 0;
#region 401games
if (_IS401games)
{
#region 401categorypaging
if (_IsCategorypaging)
{
if (!Erorr_401_1)
{
try
{
_Worker1.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
Erorr_401_1 = true;
if (_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker1.Html == null || !_Worker1.Html.ToLower().Contains("class=\"pages\"")) && checkcounter < 1000);
}
checkcounter = 0;
#endregion CheckPageLoaded
_Work1doc.LoadHtml(_Worker1.Html);
if (_IsCategorypaging)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"pages\"]/ul/li");
int TotalRecords = Convert.ToInt32(_Collection[_Collection.Count - 1].SelectNodes("span")[0].InnerText.Trim());
int TotalPages = 0;
int CurrentPage = 0;
if (TotalRecords % 40 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 40);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 40) + 1;
}
HtmlNodeCollection _Collection1 = _Work1doc.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection1)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread1.Contains(_Attribute.Value))
{
_ProductUrlthread1.Add(_Attribute.Value);
}
}
}
}
//for (int i = 0; i < TotalPages; i++)
//{
// SubCategoryUrl.Add(Url1.Substring(0,Url1.IndexOf("#")) + "#st=&begin=" + ((i * 40) + 1) + "&nhit=40");
//}
while (CurrentPage < TotalPages)
{
DivCollection Div = _Worker1.Divs.Filter(Find.ByClass("pages"));
LinkCollection _Links = Div[0].Links;
foreach (Link _Link in _Links)
{
_Worker1.WaitForComplete();
try
{
int value = 0;
if (int.TryParse(_Link.InnerHtml.Trim(), out value))
{
if (value > CurrentPage)
{
CurrentPage = value;
_Link.Click();
System.Threading.Thread.Sleep(1000);
try
{
if (_Worker1.Html == null || _Worker1.Html.ToLower().Contains(_ProductUrlthread1.ToArray()[_ProductUrlthread1.Count - 1].ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker1.Html == null || _Worker1.Html.ToLower().Contains(_ProductUrlthread1.ToArray()[_ProductUrlthread1.Count - 1].ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"pages\"")));
}
_Work1doc.LoadHtml(_Worker1.Html);
HtmlNodeCollection _Collection2 = _Work1doc.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection2)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread1.Contains(_Attribute.Value))
{
_ProductUrlthread1.Add(_Attribute.Value);
}
else
{
string test = _Attribute.Value;
}
}
}
}
}
catch
{
}
break;
}
}
}
catch
{
}
}
}
}
}
catch
{
}
}
_401index++;
_Work.ReportProgress((_401index * 100 / CategoryUrl.Count()));
}
#endregion 401categorypaging
else if (_IsProduct)
{
_401index++;
_Work.ReportProgress((_401index * 100 / _ProductUrl.Count()));
}
}
#endregion 401games
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
if (_IS401games)
{
if (_IsCategorypaging)
{
try
{
Erorr_401_2 = true;
int CounterError = 0;
do
{
try
{
_Worker2.GoTo(Url2);
Erorr_401_2 = false;
}
catch
{
CounterError++;
}
} while (Erorr_401_2 && CounterError < 20);
}
catch
{
_Iserror = true;
}
}
else if (_IsProduct)
{
try
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
}
catch
{
_Iserror = true;
}
}
}
else
{
if (_IsProduct)
{
try
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
}
catch
{
_Iserror = true;
}
}
}
int index = 0;
#region 401games
if (_IS401games)
{
#region 401categorypaging
if (_IsCategorypaging)
{
if (!Erorr_401_2)
{
try
{
_Worker2.WaitForComplete();
#region CheckPageLoaded
#region variable
int checkcounter = 0;
#endregion variable
Erorr_401_2 = true;
if (_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker2.Html == null || !_Worker2.Html.ToLower().Contains("class=\"pages\"")) && checkcounter < 1000);
}
checkcounter = 0;
#endregion CheckPageLoaded
_Work1doc2.LoadHtml(_Worker2.Html);
if (_IsCategorypaging)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"pages\"]/ul/li");
int TotalRecords = Convert.ToInt32(_Collection[_Collection.Count - 1].SelectNodes("span")[0].InnerText.Trim());
int TotalPages = 0;
int CurrentPage = 0;
if (TotalRecords % 40 == 0)
{
TotalPages = Convert.ToInt32(TotalRecords / 40);
}
else
{
TotalPages = Convert.ToInt32(TotalRecords / 40) + 1;
}
HtmlNodeCollection _Collection1 = _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection1)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread2.Contains(_Attribute.Value))
{
_ProductUrlthread2.Add(_Attribute.Value);
}
}
}
}
while (CurrentPage < TotalPages)
{
DivCollection Div = _Worker2.Divs.Filter(Find.ByClass("pages"));
LinkCollection _Links = Div[0].Links;
foreach (Link _Link in _Links)
{
_Worker2.WaitForComplete();
try
{
int value = 0;
if (int.TryParse(_Link.InnerHtml.Trim(), out value))
{
if (value > CurrentPage)
{
CurrentPage = value;
_Link.Click();
System.Threading.Thread.Sleep(1000);
try
{
if (_Worker2.Html == null || _Worker2.Html.ToLower().Contains(_ProductUrlthread2.ToArray()[_ProductUrlthread2.Count - 1].ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"pages\""))
{
do
{
System.Threading.Thread.Sleep(20);
Application.DoEvents();
checkcounter++;
} while ((_Worker2.Html == null || _Worker2.Html.ToLower().Contains(_ProductUrlthread2.ToArray()[_ProductUrlthread2.Count - 1].ToString().ToLower()) || !_Worker1.Html.ToLower().Contains("class=\"pages\"")));
}
_Work1doc2.LoadHtml(_Worker2.Html);
HtmlNodeCollection _Collection2 = _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"product-img\"]");
foreach (HtmlNode _Node in _Collection2)
{
foreach (HtmlAttribute _Attribute in _Node.Attributes)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_ProductUrlthread2.Contains(_Attribute.Value))
{
_ProductUrlthread2.Add(_Attribute.Value);
}
else
{
string test = _Attribute.Value;
}
}
}
}
}
catch
{
}
break;
}
}
}
catch
{
}
}
}
}
}
catch
{
}
}
_401index++;
_Work1.ReportProgress((_401index * 100 / CategoryUrl.Count()));
}
#endregion
#region product
else if (_IsProduct)
{
_401index++;
_Work1.ReportProgress((_401index * 100 / _ProductUrl.Count()));
}
#endregion product
}
#endregion 401games
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
#region 401games
if (_IS401games)
{
if (_IsProduct)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url1;
#region title
HtmlNodeCollection _Title = _Work1doc.DocumentNode.SelectNodes("//h1[@class=\"title product\"]");
if (_Title != null)
{
dataGridView1.Rows[index].Cells[2].Value = CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(CommanFunction.GenerateSku("ST4GAM", CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())), CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim()), "store.401games");
}
else
{
HtmlNodeCollection _Title1 = _Work1doc.DocumentNode.SelectNodes("//h1");
if (_Title1 != null)
{
dataGridView1.Rows[index].Cells[2].Value = CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(CommanFunction.GenerateSku("ST4GAM", CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())), CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim()), ".store401games");
}
}
#endregion title
#region description
_Description1=""
HtmlNodeCollection _description = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"tab_desc\"]");
if (_description != null)
{
_Description1 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description[0].InnerHtml.Replace("Product Description","")).Trim());
}
else
{
HtmlNodeCollection _description1 = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"ldesc\"]");
if (_description != null)
{
_Description1 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description1[0].InnerHtml).Trim());
}
}
try
{
if (_Description1.Length > 2000)
{
_Description1 = _Description1.Substring(0, 1997) + "...";
}
}
catch
{
}
dataGridView1.Rows[index].Cells[3].Value = _Description1.Replace("Â", "");
#endregion description
#region manufacturer
dataGridView1.Rows[index].Cells[5].Value = "Store 401 games";
dataGridView1.Rows[index].Cells[6].Value = "Store 401 games";
#endregion manufacturer
#region For decsription empty
try
{
if (dataGridView1.Rows[index].Cells[3].Value == null || dataGridView1.Rows[index].Cells[3].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[3].Value.ToString()))
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value;
}
}
catch
{
}
#endregion For decsription empty
#region currency
dataGridView1.Rows[index].Cells[8].Value = "CDN";
#endregion currency
#region price,stock
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.Trim() == "0")
{
dataGridView1.Rows[index].Cells[9].Value = "0";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.ToLower().Replace("in-stock :","").Trim();
}
}
else if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.Trim() == "0")
{
dataGridView1.Rows[index].Cells[9].Value = "0";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.ToLower().Replace("in-stock :", "").Trim();
}
}
else if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]") != null)
{
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Trim() == "0")
{
dataGridView1.Rows[index].Cells[9].Value = "0";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Replace("in-stock :", "").Trim();
}
}
if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"discounted-price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"discounted-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
else if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"regular-price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"regular-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
#endregion price,stock
#region Image
if (_Work1doc.DocumentNode.SelectNodes("//img[@id=\"main_image\"]") != null)
{
foreach(HtmlAttribute _Attribute in _Work1doc.DocumentNode.SelectNodes("//img[@id=\"main_image\"]")[0].Attributes)
{
if(_Attribute.Name=="src")
{
dataGridView1.Rows[index].Cells[10].Value = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
else if (_Work1doc.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img") != null)
{
foreach (HtmlAttribute _Attribute in _Work1doc.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img")[0].Attributes)
{
if (_Attribute.Name == "src")
{
dataGridView1.Rows[index].Cells[10].Value = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
#endregion Image
}
}
#endregion 401games
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
#region 401games
if (_IS401games)
{
if (_IsProduct)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = Url2;
#region title
HtmlNodeCollection _Title = _Work1doc2.DocumentNode.SelectNodes("//h1[@class=\"title product\"]");
if (_Title != null)
{
dataGridView1.Rows[index].Cells[2].Value = CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(CommanFunction.GenerateSku("ST4GAM", CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())), CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim()), "store.401games");
}
else
{
HtmlNodeCollection _Title1 = _Work1doc2.DocumentNode.SelectNodes("//h1");
if (_Title1 != null)
{
dataGridView1.Rows[index].Cells[2].Value = CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim());
dataGridView1.Rows[index].Cells[1].Value = GenrateSkuFromDatbase(CommanFunction.GenerateSku("ST4GAM", CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())), CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim()), ".store401games");
}
}
#endregion title
#region description
_Description2 = "";
HtmlNodeCollection _description = _Work1doc2.DocumentNode.SelectNodes("//div[@id=\"tab_desc\"]");
if (_description != null)
{
_Description2 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description[0].InnerHtml.Replace("Product Description", "")).Trim());
}
else
{
HtmlNodeCollection _description1 = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"ldesc\"]");
if (_description1 != null)
{
_Description2 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_description1[0].InnerHtml).Trim());
}
}
try
{
if (_Description2.Length > 2000)
{
_Description2 = _Description2.Substring(0, 1997) + "...";
}
}
catch
{
}
dataGridView1.Rows[index].Cells[3].Value = _Description2.Replace("Â", "");
#endregion description
#region manufacturer
dataGridView1.Rows[index].Cells[5].Value = "Store 401 games";
dataGridView1.Rows[index].Cells[6].Value = "Store 401 games";
#endregion manufacturer
#region For decsription empty
try
{
if (dataGridView1.Rows[index].Cells[3].Value == null || dataGridView1.Rows[index].Cells[3].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[3].Value.ToString()))
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value;
}
}
catch
{
}
#endregion For decsription empty
#region currency
dataGridView1.Rows[index].Cells[8].Value = "CDN";
#endregion currency
#region price,stock
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.Trim() == "0")
{
dataGridView1.Rows[index].Cells[9].Value = "0";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability \"]/span")[0].InnerText.ToLower().Replace("in-stock :", "").Trim();
}
}
else if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.Trim() == "0")
{
dataGridView1.Rows[index].Cells[9].Value = "0";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability\"]/span")[0].InnerText.ToLower().Replace("in-stock :", "").Trim();
}
}
else if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]") != null)
{
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Trim() == "0")
{
dataGridView1.Rows[index].Cells[9].Value = "0";
}
else
{
dataGridView1.Rows[index].Cells[9].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"availability in-stock\"]")[0].InnerText.ToLower().Replace("Quantity :", "").Replace("in-stock :", "").Trim();
}
}
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"discounted-price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"discounted-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
else if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"regular-price\"]") != null)
{
dataGridView1.Rows[index].Cells[7].Value = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"regular-price\"]")[0].InnerText.Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace(":", "").Trim();
}
#endregion price,stock
#region Image
if (_Work1doc2.DocumentNode.SelectNodes("//img[@id=\"main_image\"]") != null)
{
foreach (HtmlAttribute _Attribute in _Work1doc2.DocumentNode.SelectNodes("//img[@id=\"main_image\"]")[0].Attributes)
{
if (_Attribute.Name == "src")
{
dataGridView1.Rows[index].Cells[10].Value = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
else if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img") != null)
{
foreach (HtmlAttribute _Attribute in _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-img-wrapper\"]/img")[0].Attributes)
{
if (_Attribute.Name == "src")
{
dataGridView1.Rows[index].Cells[10].Value = "http://store.401games.ca/" + _Attribute.Value;
}
}
}
#endregion Image
}
}
#endregion 401games
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void _percent_Click(object sender, EventArgs e)
{
}
private void createcsvfile_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Go_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Pause_Click(object sender, EventArgs e)
{
}
private void totalrecord_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
/****************Code to select all check boxes*************/
/************Uncomment durng live**/
for (int i = 0; i < chkstorelist.Items.Count; i++)
{
chkstorelist.SetItemChecked(i, true);
}
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
DataGridViewColumn _Columns = new DataGridViewColumn();
_Columns.Name = "RowID";
_Columns.HeaderText = "RowID";
_Columns.DataPropertyName = "RowID";
_Columns.ValueType = Type.GetType("System.float");
_Columns.SortMode = DataGridViewColumnSortMode.Automatic;
DataGridViewCell cell = new DataGridViewLinkCell();
_Columns.CellTemplate = cell;
dataGridView1.Columns.Add(_Columns);
dataGridView1.Columns.Add("SKU", "SKU");
dataGridView1.Columns.Add("Product Name", "Product Name");
dataGridView1.Columns.Add("Product Description", "Product Description");
dataGridView1.Columns.Add("Bullet Points", "Bullet Points");
dataGridView1.Columns.Add("Manufacturer", "Manufacturer");
dataGridView1.Columns.Add("Brand Name", "Brand Name");
dataGridView1.Columns.Add("Price", "Price");
dataGridView1.Columns.Add("Currency", "Currency");
dataGridView1.Columns.Add("In Stock", "In Stock");
dataGridView1.Columns.Add("Image URL", "Image URL");
dataGridView1.Columns.Add("URL", "URL");
/****************BackGround worker *************************/
}
private void btnsubmit_Click(object sender, System.EventArgs e)
{
Process();
}
private void Form1_Shown(object sender, System.EventArgs e)
{
btnsubmit.PerformClick();
}
}
}
<file_sep>/Project8-saleevent/Crawler_WithouSizes_Part3/Crawler_WithouSizes_Part3/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using Crawler_WithouSizes_Part7;
using System.Xml;
using Newtonsoft.Json;
namespace Crawler_WithouSizes_Part3
{
public partial class Form1 : Form
{
#region DatbaseVariable
SqlConnection Connection = new SqlConnection(System.Configuration.ConfigurationSettings.
AppSettings["connectionstring"]);
#endregion DatbaseVariable
StreamWriter _writer = new StreamWriter(Application.StartupPath + "/test.csv");
#region ClassTypeVariable
List<Crawler_WithouSizes_Part7.BusinessLayer.Product> Worker1Products = new List<Crawler_WithouSizes_Part7.BusinessLayer.Product>();
List<Crawler_WithouSizes_Part7.BusinessLayer.Product> Worker2Products = new List<Crawler_WithouSizes_Part7.BusinessLayer.Product>();
List<string> Url = new List<string>();
#endregion ClassTypeVariable
#region booltypevariable
bool _ISSaleevent = true;
bool _IsProduct = false;
bool _IsCategory = true;
bool _IsCategorypaging = false;
bool _Stop = false;
#endregion booltypevariable
#region intypevariable
int gridindex = 0;
int _Saleeventindex = 0;
#endregion intypevariable
#region stringtypevariable
string Url1 = "";
string Url2 = "";
string BrandName1 = "";
string BrandName2 = "";
string _ScrapeUrl = "";
string Bullets = "";
string _Description1 = "";
string _Description2 = "";
#endregion listtypevariable
#region listtypevariable
List<string> ProductName = new List<string>();
List<string> _Url = new List<string>();
List<string> _dateofbirth = new List<string>();
Dictionary<string, string> _ProductUrl = new Dictionary<string, string>();
List<string> Skus = new List<string>();
List<string> _Name = new List<string>();
Dictionary<string, string> CategoryUrl = new Dictionary<string, string>();
Dictionary<string, string> SubCategoryUrl = new Dictionary<string, string>();
#endregion stringtypevariable
#region backgroundworker
BackgroundWorker _Work = new BackgroundWorker();
BackgroundWorker _Work1 = new BackgroundWorker();
#endregion backgroundworker
#region webclient
WebClient _Client2 = new WebClient();
WebClient _Client1 = new WebClient();
WebClient _Client3 = new WebClient();
WebClient _Client4 = new WebClient();
#endregion webclient
#region htmlagility
HtmlAgilityPack.HtmlDocument _Work1doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc2 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc3 = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlDocument _Work1doc4 = new HtmlAgilityPack.HtmlDocument();
#endregion htmlagility
DataTable _Tbale = new DataTable();
public Form1()
{
InitializeComponent();
#region backrgoundworketevendeclaration
_Work.WorkerReportsProgress = true;
_Work.WorkerSupportsCancellation = true;
_Work.ProgressChanged += new ProgressChangedEventHandler(Work_ProgressChanged);
_Work.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync);
_Work.DoWork += new DoWorkEventHandler(work_dowork);
_Work1.WorkerReportsProgress = true;
_Work1.WorkerSupportsCancellation = true;
_Work1.ProgressChanged += new ProgressChangedEventHandler(Work1_ProgressChanged);
_Work1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(work_RunWorkerAsync1);
_Work1.DoWork += new DoWorkEventHandler(work_dowork);
#endregion backrgoundworketevendeclaration
}
public void DisplayRecordProcessdetails(string Message, string TotalrecordMessage)
{
_lblerror.Visible = true;
_lblerror.Text = Message;
totalrecord.Visible = true;
totalrecord.Text = TotalrecordMessage;
}
public void Process()
{
_IsProduct = false;
_Name.Clear();
CategoryUrl.Clear();
SubCategoryUrl.Clear();
_ProductUrl.Clear();
_percent.Visible = false;
_Bar1.Value = 0;
_Url.Clear();
_Tbale.Rows.Clear();
_Tbale.Columns.Clear();
dataGridView1.Rows.Clear();
DataColumn _Dc = new DataColumn();
_Dc.ColumnName = "Rowid";
_Dc.AutoIncrement = true;
_Dc.DataType = typeof(int);
_Dc.AutoIncrementSeed = 1;
_Dc.AutoIncrementStep = 1;
_Tbale.Columns.Add(_Dc);
_Tbale.Columns.Add("SKU", typeof(string));
_Tbale.Columns.Add("Product Name", typeof(string));
_Tbale.Columns.Add("Product Description", typeof(string));
_Tbale.Columns.Add("Bullet Points", typeof(string));
_Tbale.Columns.Add("Manufacturer", typeof(string));
_Tbale.Columns.Add("Brand Name", typeof(string));
_Tbale.Columns.Add("Price", typeof(string));
_Tbale.Columns.Add("Currency", typeof(string));
_Tbale.Columns.Add("In Stock", typeof(string));
_Tbale.Columns.Add("Image URL", typeof(string));
_Tbale.Columns.Add("URL", typeof(string));
_lblerror.Visible = false;
gridindex = 0;
_IsCategory = true;
_Stop = false;
#region saleevent
_ISSaleevent = true;
_ScrapeUrl = "http://www.saleevent.ca/";
try
{
_lblerror.Visible = true;
_lblerror.Text = "We are going to read category url for " + chkstorelist.Items[0].ToString() + " Website";
_Work1doc.LoadHtml(_Client1.DownloadString(_ScrapeUrl));
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//ul[@class=\"nav navbar-nav\"]/li");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
HtmlNodeCollection _Collection1 = _Node.SelectNodes(".//li/a");
if (_Collection1 != null)
{
foreach (HtmlNode _Node1 in _Collection1)
{
HtmlAttributeCollection _AttributeCollection = _Node1.Attributes;
foreach (HtmlAttribute _Attribute in _AttributeCollection)
{
if (_Attribute.Name.ToLower() == "href")
{
if (!_Node1.InnerText.ToLower().StartsWith("all") && _Attribute.Value.Trim().Length > 0 && _Attribute.Value != "#")
{
try
{
CategoryUrl.Add(_Attribute.Value, _Node1.InnerText.Trim());
}
catch
{
}
}
}
}
}
}
}
}
if (CategoryUrl.Count() > 0)
{
#region Category
DisplayRecordProcessdetails("We are going to read paging from category pages for " + chkstorelist.Items[0].ToString() + " Website", "Total Category :" + CategoryUrl.Count());
_IsCategorypaging = true;
foreach (var Caturl in CategoryUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
Url1 = Caturl.Key;
BrandName1 = Caturl.Value;
_Work.RunWorkerAsync();
}
else
{
Url2 = Caturl.Key;
BrandName2 = Caturl.Value;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion Category
#region ProductUrl
System.Threading.Thread.Sleep(1000);
_Bar1.Value = 0;
_Saleeventindex = 0;
_IsCategorypaging = false;
_IsCategory = true;
DisplayRecordProcessdetails("We are going to read Product url for " + chkstorelist.Items[0].ToString() + " Website", "Total category url :" + SubCategoryUrl.Count());
foreach (var CatUrl in SubCategoryUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
BrandName1 = CatUrl.Value;
Url1 = CatUrl.Key;
_Work.RunWorkerAsync();
}
else
{
BrandName2 = CatUrl.Value;
Url2 = CatUrl.Key;
_Work1.RunWorkerAsync();
}
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#endregion ProductUrl
#region ProductInformation
_Bar1.Value = 0;
System.Threading.Thread.Sleep(1000);
_Saleeventindex = 0;
_IsCategory = false;
_IsProduct = true;
DisplayRecordProcessdetails("We are going to read Product Information for " + chkstorelist.Items[0].ToString() + " Website", "Total Products :" + _ProductUrl.Count());
foreach (var PrdUrl in _ProductUrl)
{
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
while (_Stop)
{
Application.DoEvents();
}
if (!_Work.IsBusy)
{
BrandName1 = PrdUrl.Value;
Url1 = PrdUrl.Key;
_Work.RunWorkerAsync();
}
else
{
BrandName2 = PrdUrl.Value;
Url2 = PrdUrl.Key;
_Work1.RunWorkerAsync();
}
}
while (_Work.IsBusy || _Work1.IsBusy)
{
Application.DoEvents();
}
#region InsertdataIngrid
foreach (Crawler_WithouSizes_Part7.BusinessLayer.Product prd in Worker1Products)
{
int index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[1].Value = prd.SKU;
dataGridView1.Rows[index].Cells[2].Value = prd.Name;
dataGridView1.Rows[index].Cells[3].Value = prd.Description;
dataGridView1.Rows[index].Cells[4].Value = prd.Bulletpoints;
dataGridView1.Rows[index].Cells[5].Value = prd.Manufacturer;
dataGridView1.Rows[index].Cells[6].Value = prd.Brand;
dataGridView1.Rows[index].Cells[7].Value = prd.Price;
dataGridView1.Rows[index].Cells[8].Value = prd.Currency;
dataGridView1.Rows[index].Cells[9].Value = prd.Stock;
dataGridView1.Rows[index].Cells[10].Value = prd.Image;
dataGridView1.Rows[index].Cells[11].Value = prd.URL;
dataGridView1.Rows[index].Cells[12].Value = prd.Size;
dataGridView1.Rows[index].Cells[13].Value = prd.Color;
dataGridView1.Rows[index].Cells[14].Value = prd.Isparent;
dataGridView1.Rows[index].Cells[15].Value = prd.parentsku;
dataGridView1.Rows[index].Cells[16].Value = prd.Bulletpoints1;
dataGridView1.Rows[index].Cells[17].Value = prd.Bulletpoints2;
dataGridView1.Rows[index].Cells[18].Value = prd.Bulletpoints3;
dataGridView1.Rows[index].Cells[19].Value = prd.Bulletpoints4;
dataGridView1.Rows[index].Cells[20].Value = prd.Bulletpoints5;
dataGridView1.Rows[index].Cells[21].Value = prd.Category;
dataGridView1.Rows[index].Cells[22].Value = prd.Weight;
}
#endregion InsertdataIngrid
#endregion ProductInformation
System.Threading.Thread.Sleep(1000);
_lblerror.Visible = true;
_lblerror.Text = "Now we going to generate Csv File";
GenerateCSVFile();
MessageBox.Show("Process Completed.");
}
catch
{
}
#endregion saleevent
_writer.Close();
}
public void work_dowork(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
int CountError = 0;
do
{
try
{
CountError++;
_Work1doc.LoadHtml(_Client1.DownloadString(Url1));
_Iserror = false;
}
catch
{
_Iserror = true;
}
} while (_Iserror && CountError < 5);
#region saleevent
if (_ISSaleevent)
{
if (_IsCategorypaging)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"col-sm-6 text-right\"]");
if (_Collection != null)
{
try
{
string PagingText = _Collection[0].InnerText.ToLower();
PagingText = PagingText.Substring(0, PagingText.IndexOf("pages"));
PagingText = PagingText.Substring(PagingText.IndexOf("(")).Trim();
int _TotalPages = Convert.ToInt32(Regex.Replace(PagingText.Replace("\r", "").Replace("\n", "").ToLower().Replace("page", "").Replace("of", "").Trim(), "[^0-9+]", string.Empty));
for (int Page = 1; Page <= _TotalPages; Page++)
{
try
{
SubCategoryUrl.Add(Url1 + "?page=" + Page, BrandName1);
}
catch
{
}
}
}
catch
{
try
{
SubCategoryUrl.Add(Url1, BrandName1);
}
catch
{
}
}
}
else
{
SubCategoryUrl.Add(Url1, BrandName1);
}
}
else
{
}
_Saleeventindex++;
_Work.ReportProgress((_Saleeventindex * 100 / CategoryUrl.Count()));
}
else if (_IsCategory)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"caption\"]/a");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
if (!ProductName.Contains(_Node.InnerText.Trim()))
{
ProductName.Add(_Node.InnerText.Trim());
HtmlAttributeCollection _AttColl = _Node.Attributes;
foreach (HtmlAttribute _Att in _AttColl)
{
if (_Att.Name.ToLower() == "href")
{
try
{
if (!_ProductUrl.Keys.Contains(_Att.Value.ToLower()))
_ProductUrl.Add(_Att.Value.ToLower(), BrandName1);
}
catch
{
}
}
}
}
}
}
else
{
}
_Saleeventindex++;
_Work.ReportProgress((_Saleeventindex * 100 / SubCategoryUrl.Count()));
}
else
{
}
}
else
{
_Saleeventindex++;
_Work.ReportProgress((_Saleeventindex * 100 / _ProductUrl.Count()));
}
}
#endregion saleevent
}
public void work_dowork1(object sender, DoWorkEventArgs e)
{
bool _Iserror = false;
try
{
_Work1doc2.LoadHtml(_Client2.DownloadString(Url2));
_Iserror = false;
}
catch
{
_Work1doc2 = null;
_Iserror = true;
}
#region saleevent
if (_ISSaleevent)
{
if (_IsCategorypaging)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//p[@class=\"amount\"]");
if (_Collection != null)
{
try
{
string PagingText = _Collection[0].InnerText.ToLower();
PagingText = CommanFunction.ReverseString(PagingText.Replace("total", "").Trim());
PagingText = CommanFunction.ReverseString(PagingText.Substring(0, PagingText.IndexOf(" ")));
int TotalRecords = Convert.ToInt32(Regex.Replace(PagingText.Replace("\r", "").Replace("\n", "").ToLower().Replace("page", "").Replace("of", "").Trim(), "[^0-9+]", string.Empty));
int _TotalPages = 0;
if (TotalRecords % 15 == 0)
{
_TotalPages = Convert.ToInt32(TotalRecords / 15);
}
else
{
_TotalPages = Convert.ToInt32(TotalRecords / 15) + 1;
}
for (int Page = 1; Page <= _TotalPages; Page++)
{
try
{
SubCategoryUrl.Add(Url2 + "?limit=15&p=" + Page, BrandName2);
}
catch
{
}
}
}
catch
{
try
{
SubCategoryUrl.Add(Url2, BrandName2);
}
catch
{
}
}
}
else
{
}
}
else
{
}
_Saleeventindex++;
_Work1.ReportProgress((_Saleeventindex * 100 / CategoryUrl.Count()));
}
else if (_IsCategory)
{
if (!_Iserror)
{
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//a[@class=\"product-image\"]");
if (_Collection != null)
{
foreach (HtmlNode _Node in _Collection)
{
HtmlAttributeCollection _AttColl = _Node.Attributes;
foreach (HtmlAttribute _Att in _AttColl)
{
if (_Att.Name.ToLower() == "href")
{
try
{
if (!_ProductUrl.Keys.Contains(_Att.Value.ToLower()))
_ProductUrl.Add(_Att.Value.ToLower(), BrandName1);
}
catch
{
}
}
}
}
}
else
{
}
_Saleeventindex++;
_Work1.ReportProgress((_Saleeventindex * 100 / SubCategoryUrl.Count()));
}
else
{
}
}
else
{
_Saleeventindex++;
_Work1.ReportProgress((_Saleeventindex * 100 / _ProductUrl.Count()));
}
}
#endregion saleevent
}
public void work_RunWorkerAsync(object sender, RunWorkerCompletedEventArgs e)
{
#region saleevent
if (_ISSaleevent)
{
if (_IsProduct)
{
if (_Work1doc.DocumentNode != null)
{
bool Isexist = false;
bool Isoption = true;
bool IsColorFirst = false;
Isexist = true;
try
{
try
{
#region Title
string Title = "";
HtmlNodeCollection _Title = _Work1doc.DocumentNode.SelectNodes("//h1[@itemprop=\"name\"]");
if (_Title != null)
{
Title = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "").Replace("â„¢", "™");
}
#endregion Title
#region Description
_Description1 = "";
HtmlNodeCollection _description = _Work1doc.DocumentNode.SelectNodes("//div[@itemprop=\"description\"]");
if (_description != null)
{
_Description1 = _description[0].InnerHtml.Replace("Quick Overview", "").Trim();
_Description1 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_Description1).Trim());
}
try
{
if (_Description1.Length > 2000)
_Description1 = _Description1.Substring(0, 1997) + "...";
}
catch
{
}
string Desc = System.Net.WebUtility.HtmlDecode(_Description1.Replace("Â", "").Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("online only", "").Replace("Online Only", "")).Replace(",", " ");
if (Desc.Trim() != "")
{
if (Desc.Substring(0, 1) == "\"")
_Description1 = Desc.Substring(1);
else
_Description1 = Desc;
}
#endregion Description
#region BulletPoints
string BulletPoints = "";
List<string> LstBulletPoints = new List<string>();
HtmlNodeCollection _Bullets1 = null;
_Bullets1 = _Work1doc.DocumentNode.SelectNodes("//div[@itemprop=\"description\"]");
if (_Bullets1 != null)
{
HtmlNodeCollection _Bullets = null;
_Bullets = _Bullets1[0].SelectNodes(".//li");
if (_Bullets == null)
_Bullets = _Bullets1[0].SelectNodes(".//h3");
if (_Bullets != null)
{
foreach (HtmlNode _BullNode in _Bullets)
{
if (BulletPoints.Length + System.Net.WebUtility.HtmlDecode(CommanFunction.StripHTML(_BullNode.InnerText).Trim()).Length + 1 < 500)
{
BulletPoints = BulletPoints + System.Net.WebUtility.HtmlDecode(CommanFunction.StripHTML(_BullNode.InnerText).Trim()) + ".";
}
else
{
if (BulletPoints.Length > 500)
BulletPoints = BulletPoints.Substring(0, 500);
LstBulletPoints.Add(BulletPoints.Replace("â„¢", "™"));
BulletPoints = System.Net.WebUtility.HtmlDecode(CommanFunction.StripHTML(_BullNode.InnerText).Trim());
}
}
}
}
if (BulletPoints.Trim() != "")
LstBulletPoints.Add(BulletPoints.Replace("â„¢", "™"));
#endregion BulletPoints
#region Brand
string Brand = "";
HtmlNodeCollection _Brand = _Work1doc.DocumentNode.SelectNodes("//span[@itemprop=\"name\"]");
if (_Brand != null)
{
Brand = _Brand[0].InnerText.Trim();
}
if (Brand.Trim() == "")
Brand = "SALEENT";
#endregion Brand
#region Images
string Images = "";
HtmlNodeCollection _Image = _Work1doc.DocumentNode.SelectNodes("//img[@itemprop=\"image\"]");
if (_Image != null)
{
foreach (HtmlAttribute _Att in _Image[0].Attributes)
{
if (_Att.Name == "src")
{
Images = _Att.Value.Trim() + "@";
}
}
}
//HtmlNodeCollection _ThumImage = _Work1doc.DocumentNode.SelectNodes("//ul[@id=\"ProductThumbs\"]/li/a");
//if (_ThumImage != null)
//{
// foreach (HtmlNode ThumNode in _ThumImage)
// {
// foreach (HtmlAttribute _Att in ThumNode.Attributes)
// {
// if (_Att.Name.ToLower() == "href")
// {
// if (!Images.Contains(_Att.Value))
// {
// if (!_Att.Value.ToLower().Contains("https:"))
// {
// Images = Images + "https:" + _Att.Value.Trim() + "@";
// }
// else
// {
// Images = Images + _Att.Value.Trim() + "@";
// }
// }
// }
// }
// }
//}
if (Images.Length > 0)
Images = Images.Substring(0, Images.Length - 1);
#endregion Images
int VariantsCounter = 0;
string ParentSku = "";
VariantsCounter++;
string Price = "";
string Stock = "";
string Sku = "";
#region Price
HtmlNodeCollection _Price = _Work1doc.DocumentNode.SelectNodes("//h2[@itemprop=\"price\"]");
if (_Price != null)
{
Price = _Price[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
#endregion price
#region stock
Stock = "5";
HtmlNodeCollection _Stock1 = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"content\"]");
if (_Stock1 != null)
{
HtmlNodeCollection _Stock = _Stock1[0].SelectNodes(".//ul[@class=\"list-unstyled\"]");
if (_Stock != null)
{
if (_Stock[0].InnerHtml.ToLower().Contains("out of stock") || _Stock[0].InnerHtml.ToLower().Contains("out stock"))
Stock = "0";
}
}
#endregion stock
#region sku
HtmlNodeCollection _Sku1 = _Work1doc.DocumentNode.SelectNodes("//div[@id=\"content\"]");
if (_Sku1 != null)
{
HtmlNodeCollection _Sku = _Sku1[0].SelectNodes(".//ul[@class=\"list-unstyled\"]/li");
if (_Sku != null)
{
foreach (HtmlNode _Node in _Sku)
{
if (_Node.InnerText.ToLower().Contains("product code:"))
{
Sku = _Node.InnerText.ToLower().Replace("product code:", "").Trim();
ParentSku = Sku;
}
}
if (ParentSku == "")
{
ParentSku = CommanFunction.GeneratecolorSku("", Title);
Sku = ParentSku;
}
ParentSku = ParentSku + "prnt";
}
}
#endregion sku
if (Skus.Contains(Sku))
return;
else
Skus.Add(Sku);
HtmlNodeCollection _Coll = _Work1doc.DocumentNode.SelectNodes("//div[@class=\"optiondropdown\"]/select/option");
if (_Coll == null)
{
Isoption = false;
Crawler_WithouSizes_Part7.BusinessLayer.Product Prd = new Crawler_WithouSizes_Part7.BusinessLayer.Product();
Prd.Brand = Brand;
Prd.Category = BrandName1;
Prd.Manufacturer = Brand;
Prd.Currency = "CAD";
Prd.Description = _Description1;
Prd.URL = Url1;
int BulletPointCounter = 0;
foreach (var Points in LstBulletPoints)
{
BulletPointCounter++;
switch (BulletPointCounter)
{
case 1:
Prd.Bulletpoints1 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 2:
Prd.Bulletpoints2 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 3:
Prd.Bulletpoints3 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 4:
Prd.Bulletpoints4 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 5:
Prd.Bulletpoints5 = Points.Replace("..", "").Replace("â€", "\"");
break;
}
}
Prd.Isparent = true;
if (Sku.Length + 3 > 30)
Prd.SKU = "SEL" + Sku.Substring(0, 27);
else
Prd.SKU = "SEL" + Sku;
Prd.Stock = Stock;
Prd.Price = Price;
if (ParentSku.Length + 3 > 30)
Prd.parentsku = "SEL" + ParentSku.Substring(0, 27);
else
Prd.parentsku = "SEL" + ParentSku;
Prd.Weight = "0";
Prd.Name = Title;
Prd.Image = Images;
Worker1Products.Add(Prd);
}
else
{
List<string> Colors = new List<string>();
foreach (HtmlNode _NodeColor in _Coll)
{
if (!_NodeColor.NextSibling.InnerText.ToLower().Contains("select colour"))
{
string Color = _NodeColor.NextSibling.InnerText.Replace("\r", "").Replace("\n", "").Trim();
if (Color.Contains("x"))
{
Color = Color.Substring(0, Color.IndexOf(" x")).Trim();
}
if (Color.Contains("#"))
{
Color = Color.Substring(0, Color.IndexOf("#")).Trim();
}
if(!Colors.Contains(Color.ToLower()))
Colors.Add(Color.ToLower());
}
}
if (Colors.Count == 0)
{
}
else
{
int Variantcounter = 0;
foreach (string ColorText in Colors)
{
Variantcounter++;
Crawler_WithouSizes_Part7.BusinessLayer.Product Prd = new Crawler_WithouSizes_Part7.BusinessLayer.Product();
Prd.Brand = Brand;
Prd.Category = BrandName1;
Prd.Manufacturer = Brand;
Prd.Currency = "CAD";
Prd.Description = _Description1;
Prd.URL = Url1;
int BulletPointCounter = 0;
foreach (var Points in LstBulletPoints)
{
BulletPointCounter++;
switch (BulletPointCounter)
{
case 1:
Prd.Bulletpoints1 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 2:
Prd.Bulletpoints2 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 3:
Prd.Bulletpoints3 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 4:
Prd.Bulletpoints4 = Points.Replace("..", "").Replace("â€", "\"");
break;
case 5:
Prd.Bulletpoints5 = Points.Replace("..", "").Replace("â€", "\"");
break;
}
}
if (Variantcounter == 1)
Prd.Isparent = true;
Prd.Color = ColorText;
string ColorSku = Sku + "-" + ColorText.Replace(" x","").Replace("#","").Replace(" ","").Trim();
if (ColorSku.Length + 3 > 30)
Prd.SKU = "SEL" + ColorSku.Substring(0, 27);
else
Prd.SKU = "SEL" + ColorSku;
Prd.Stock = Stock;
Prd.Price = Price;
if (ParentSku.Length + 3 > 30)
Prd.parentsku = "SEL" + ParentSku.Substring(0, 27);
else
Prd.parentsku = "SEL" + ParentSku;
Prd.Weight = "0";
Prd.Name = Title;
Prd.Image = Images;
Worker1Products.Add(Prd);
}
}
}
}
catch
{
_writer.WriteLine(Url1 + "error occured in code to process this link");
}
}
catch
{
_writer.WriteLine(Url1 + "error occured in code to process this link");
}
}
else
{
}
}
else
{
_writer.WriteLine(Url1 + "Url data is not loaded.");
}
}
else
{
}
#endregion saleevent
}
public void work_RunWorkerAsync1(object sender, RunWorkerCompletedEventArgs e)
{
#region saleevent
if (_ISSaleevent)
{
if (_IsProduct)
{
if (_Work1doc2.DocumentNode != null)
{
int index = 0;
index = gridindex;
gridindex++;
dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = index;
dataGridView1.Rows[index].Cells[11].Value = BrandName2;
dataGridView1.Rows[index].Cells[12].Value = Url2;
#region title
HtmlNodeCollection _Title = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-name\"]/h1");
if (_Title != null)
{
dataGridView1.Rows[index].Cells[2].Value = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "").Replace("â„¢", "™");
}
else
{
HtmlNodeCollection _Title1 = _Work1doc2.DocumentNode.SelectNodes("//meta[@property=\"og:title\"]");
if (_Title1 != null)
{
dataGridView1.Rows[index].Cells[2].Value = System.Net.WebUtility.HtmlDecode(CommanFunction.Removeunsuaalcharcterfromstring(_Title1[0].InnerText.Trim())).Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("Online Only", "").Replace("online only", "").Replace("â„¢", "™");
}
}
#endregion title
#region description
_Description2 = "";
HtmlNodeCollection _description = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"short-description\"]");
if (_description != null)
{
_Description2 = _description[0].InnerHtml.Replace("Quick Overview", "").Trim();
#region CodeToReMoveText
if (_Description2.Trim().Length > 0)
{
List<string> _Remove = new List<string>();
foreach (HtmlNode _Node in _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"short-description\"]")[0].ChildNodes)
{
if (_Node.InnerText.ToLower().Contains("special orders") || _Node.InnerText.ToLower().Contains("stock is limited") || _Node.InnerText.ToLower().Contains("please note") || _Node.InnerText.ToLower().Contains("credit card"))
{
_Remove.Add(_Node.InnerHtml);
}
}
foreach (string _rem in _Remove)
{
_Description2 = _Description2.Replace(_rem, "");
}
}
#endregion CodeToReMoveText
_Description2 = CommanFunction.Removeunsuaalcharcterfromstring(CommanFunction.StripHTML(_Description2).Trim());
}
else
{
}
try
{
if (_Description2.Length > 2000)
{
_Description2 = _Description2.Substring(0, 1997) + "...";
}
}
catch
{
}
string Desc = System.Net.WebUtility.HtmlDecode(_Description2.Replace("Â", "").Replace(">", "").Replace("<", "").Replace("- Online Only", "").Replace("- online only", "").Replace("online only", "").Replace("Online Only", "")).Replace(",", " ");
if (Desc.Trim() != "")
{
if (Desc.Substring(0, 1) == "\"")
{
dataGridView1.Rows[index].Cells[3].Value = Desc.Substring(1);
}
else
{
dataGridView1.Rows[index].Cells[3].Value = Desc;
}
}
#endregion description
#region Bullets
string Bullets = "";
HtmlNodeCollection _Collection = _Work1doc2.DocumentNode.SelectNodes("//table[@id=\"product-attribute-specs-table\"]");
if (_Collection != null)
{
HtmlNodeCollection _Collection1 = _Collection[0].SelectNodes(".//tr");
if (_Collection1 != null)
{
foreach (HtmlNode _Node in _Collection1)
{
try
{
if (_Node.SelectNodes(".//th") != null)
{
if (_Node.SelectNodes(".//th")[0].InnerText.ToLower().Trim() == "product id")
{
dataGridView1.Rows[index].Cells[1].Value = "GS" + _Node.SelectNodes(".//td")[0].InnerText.Trim();
}
else if (_Node.SelectNodes(".//th")[0].InnerText.ToLower().Trim().Contains("manufacturer") || _Node.SelectNodes(".//th")[0].InnerText.ToLower().Trim().Contains("publisher"))
{
dataGridView1.Rows[index].Cells[5].Value = _Node.SelectNodes(".//td")[0].InnerText.Trim();
dataGridView1.Rows[index].Cells[6].Value = _Node.SelectNodes(".//td")[0].InnerText.Trim();
}
else
{
string Feature = "<li>" + _Node.SelectNodes(".//th")[0].InnerText.Trim() + " " + _Node.SelectNodes(".//td")[0].InnerText.Trim() + "</li>";
if (Bullets.Length + Feature.Length + 11 <= 500)
{
Bullets = Bullets + Feature;
}
}
}
}
catch
{
}
}
}
}
if (_Work1doc2.DocumentNode.SelectNodes("//div[@class=\"box-collateral box-description\"]") != null)
{
string Feature = "<li>" + _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"box-collateral box-description\"]")[0].InnerText.Trim() + "</li>";
if (Bullets.Length + Feature.Length + 11 <= 500)
{
Bullets = Feature + Bullets;
}
}
if (Bullets.Length > 4)
{
Bullets = "<ul>" + Bullets + "</ul>";
}
dataGridView1.Rows[index].Cells[4].Value = Bullets.Replace(",", " ");
#endregion Bullets
#region manufacturer
if (dataGridView1.Rows[index].Cells[5].Value == null || dataGridView1.Rows[index].Cells[5].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[5].Value.ToString()))
{
dataGridView1.Rows[index].Cells[5].Value = BrandName1;
dataGridView1.Rows[index].Cells[6].Value = BrandName1;
}
#endregion manufacturer
#region For decsription empty
try
{
if (dataGridView1.Rows[index].Cells[3].Value == null || dataGridView1.Rows[index].Cells[3].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[3].Value.ToString()))
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value.ToString().Replace(">", "").Replace("<", "");
}
else if (dataGridView1.Rows[index].Cells[3].Value.ToString().Length < 10)
{
dataGridView1.Rows[index].Cells[3].Value = dataGridView1.Rows[index].Cells[2].Value.ToString().Replace(">", "").Replace("<", "");
}
}
catch
{
}
#endregion For decsription empty
#region currency
dataGridView1.Rows[index].Cells[8].Value = "CDN";
#endregion currency
#region price,stock
dataGridView1.Rows[index].Cells[9].Value = "5";
HtmlNodeCollection _NodeAvailcoll = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-view\"]");
if (_NodeAvailcoll != null)
{
HtmlNodeCollection _NodeAvail = null;
_NodeAvail = _NodeAvailcoll[0].SelectNodes(".//p[@class=\"availability\"]");
if (_NodeAvail == null)
_NodeAvail = _NodeAvailcoll[0].SelectNodes(".//p[@class=\"availability in-stock\"]");
if (_NodeAvail != null)
{
if (_NodeAvail[0].InnerText.ToLower().Contains("sold out") || _NodeAvail[0].InnerText.ToLower().Contains("out of stock"))
{
dataGridView1.Rows[index].Cells[9].Value = "0";
}
}
}
HtmlNodeCollection _NodePricecoll = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-view\"]");
if (_NodePricecoll != null)
{
HtmlNodeCollection _NodePrice = _NodePricecoll[0].SelectNodes(".//span[@class=\"price\"]");
if (_NodePrice != null)
{
dataGridView1.Rows[index].Cells[7].Value = _NodePrice[0].InnerText.ToLower().Replace("\"", "").Replace(",", "").Replace("$", "").Replace("price", "").Replace("cdn", "").Replace(":", "").Trim();
}
}
if (dataGridView1.Rows[index].Cells[7].Value == null || dataGridView1.Rows[index].Cells[7].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[index].Cells[7].Value.ToString()))
{
dataGridView1.Rows[index].Cells[7].Value = "0";
}
#endregion price,stock
#region Image
string Images = "";
HtmlNodeCollection _Collectionimg = _Work1doc2.DocumentNode.SelectNodes("//div[@class=\"product-img-box\"]/a");
if (_Collectionimg != null)
{
foreach (HtmlAttribute _Node1 in _Collectionimg[0].Attributes)
{
if (_Node1.Name.ToLower() == "href")
{
if (!Images.Contains(_Node1.Value))
{
Images = Images + _Node1.Value + "@";
}
}
}
}
if (Images.Length > 0)
{
Images = Images.Substring(0, Images.Length - 1);
}
dataGridView1.Rows[index].Cells[10].Value = Images;
#endregion Image
}
}
else
{
}
}
#endregion saleevent
}
public string GenrateSkuFromDatbase(string sku, string Name, string storename, decimal Price)
{
string Result = sku;
try
{
using (SqlCommand Cmd = new SqlCommand())
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.Connection = Connection;
Cmd.Parameters.AddWithValue("@SKU", sku);
Cmd.Parameters.AddWithValue("@Name", Name);
Cmd.Parameters.AddWithValue("@Storename", storename);
Cmd.CommandText = "Getsku";
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = Cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Result = dr[0].ToString();
}
}
dr.Close();
}
}
catch
{
}
return Result;
}
public void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
public void Work1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
_Bar1.Value = e.ProgressPercentage;
_percent.Visible = true;
_percent.Text = e.ProgressPercentage + "% Completed";
}
private void _percent_Click(object sender, EventArgs e)
{
}
private void createcsvfile_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
Application.ExitThread();
Environment.Exit(0);
}
private void Go_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Pause_Click(object sender, EventArgs e)
{
}
private void totalrecord_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
/****************Code to select all check boxes*************/
/************Uncomment durng live**/
for (int i = 0; i < chkstorelist.Items.Count; i++)
{
chkstorelist.SetItemChecked(i, true);
}
/********************End*************************************/
/***************Grid view************************************/
totalrecord.Visible = false;
_lblerror.Visible = false;
_percent.Visible = false;
dataGridView1.Columns.Add("RowID", "RowID");
dataGridView1.Columns.Add("SKU", "SKU");
dataGridView1.Columns.Add("Product Name", "Product Name");
dataGridView1.Columns.Add("Product Description", "Product Description");
dataGridView1.Columns.Add("Bullet Points", "Bullet Points");
dataGridView1.Columns.Add("Manufacturer", "Manufacturer");
dataGridView1.Columns.Add("Brand Name", "Brand Name");
dataGridView1.Columns.Add("Price", "Price");
dataGridView1.Columns.Add("Currency", "Currency");
dataGridView1.Columns.Add("In Stock", "In Stock");
dataGridView1.Columns.Add("Image URL", "Image URL");
dataGridView1.Columns.Add("URL", "URL");
dataGridView1.Columns.Add("Size", "Size");
dataGridView1.Columns.Add("Color", "Color");
dataGridView1.Columns.Add("Isdefault", "Isdefault");
dataGridView1.Columns.Add("ParentSku", "ParentSku");
dataGridView1.Columns.Add("BullPoint1", "BullPoint1");
dataGridView1.Columns.Add("BullPoint2", "BullPoint2");
dataGridView1.Columns.Add("BullPoint3", "BullPoint3");
dataGridView1.Columns.Add("BullPoint4", "BullPoint4");
dataGridView1.Columns.Add("BullPoint5", "BullPoint5");
dataGridView1.Columns.Add("Category", "Category");
dataGridView1.Columns.Add("Weight", "Weight");
/****************BackGround worker *************************/
}
public void GenerateCSVFile()
{
try
{
string Filename = "data" + DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "");
DataTable exceldt = new DataTable();
exceldt.Columns.Add("Rowid", typeof(int));
exceldt.Columns.Add("SKU", typeof(string));
exceldt.Columns.Add("Product Name", typeof(string));
exceldt.Columns.Add("Product Description", typeof(string));
exceldt.Columns.Add("Bullet Points", typeof(string));
exceldt.Columns.Add("Manufacturer", typeof(string));
exceldt.Columns.Add("Brand Name", typeof(string));
exceldt.Columns.Add("Price", typeof(decimal));
exceldt.Columns.Add("Currency", typeof(string));
exceldt.Columns.Add("In Stock", typeof(string));
exceldt.Columns.Add("Image URL", typeof(string));
exceldt.Columns.Add("URL", typeof(string));
exceldt.Columns.Add("Size", typeof(string));
exceldt.Columns.Add("Color", typeof(string));
exceldt.Columns.Add("Isdefault", typeof(bool));
exceldt.Columns.Add("ParentSku", typeof(string));
exceldt.Columns.Add("Bulletpoints1", typeof(string));
exceldt.Columns.Add("Bulletpoints2", typeof(string));
exceldt.Columns.Add("Bulletpoints3", typeof(string));
exceldt.Columns.Add("Bulletpoints4", typeof(string));
exceldt.Columns.Add("Bulletpoints5", typeof(string));
exceldt.Columns.Add("Category", typeof(string));
exceldt.Columns.Add("Weight", typeof(string));
for (int m = 0; m < dataGridView1.Rows.Count; m++)
{
exceldt.Rows.Add();
try
{
for (int n = 0; n < dataGridView1.Columns.Count; n++)
{
if (dataGridView1.Rows[m].Cells[n].Value == null || dataGridView1.Rows[m].Cells[n].Value == DBNull.Value || String.IsNullOrEmpty(dataGridView1.Rows[m].Cells[n].Value.ToString()))
continue;
exceldt.Rows[m][n] = dataGridView1.Rows[m].Cells[n].Value.ToString();
}
}
catch
{
}
}
#region sqlcode
DataSet _Ds = new DataSet();
DataTable _Product = new DataTable();
using (SqlCommand Cmd = new SqlCommand())
{
try
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandTimeout = 0;
Cmd.Connection = Connection;
Cmd.CommandText = "MarkHub_ScrapeProductMerging";
Cmd.Parameters.AddWithValue("@StoreName", "saleevent.ca");
Cmd.Parameters.AddWithValue("@Products", exceldt);
SqlDataAdapter _ADP = new SqlDataAdapter(Cmd);
_ADP.Fill(_Ds);
}
catch
{
}
}
_Product = _Ds.Tables[0];
#endregion sqlcode
if (_Product.Rows.Count > 0)
{
try
{
using (CsvFileWriter writer = new CsvFileWriter(Application.StartupPath + "/" + Filename + ".txt"))
{
CsvFileWriter.CsvRow row = new CsvFileWriter.CsvRow();//HEADER FOR CSV FILE
foreach (DataColumn _Dc in _Product.Columns)
{
row.Add(_Dc.ColumnName);
}
row.Add("Image URL2");
row.Add("Image URL3");
row.Add("Image URL4");
row.Add("Image URL5");
writer.WriteRow(row);//INSERT TO CSV FILE HEADER
for (int m = 0; m < _Product.Rows.Count; m++)
{
CsvFileWriter.CsvRow row1 = new CsvFileWriter.CsvRow();
for (int n = 0; n < _Product.Columns.Count; n++)
{
if (n == _Product.Columns.Count - 1)
{
if (_Product.Rows[m][n] != null)
{
string[] ImageArray = _Product.Rows[m][n].ToString().Split('@');
for (int count = 0; count < ImageArray.Length; count++)
{
if (count < 5)
row1.Add(String.Format("{0}", ImageArray[count].ToString()));
}
}
else
row1.Add(String.Format("{0}", ""));
}
else
{
if (_Product.Rows[m][n] != null)
row1.Add(String.Format("{0}", _Product.Rows[m][n].ToString().Replace("\n", "").Replace("\r", "").Replace("\t", "")));
else
row1.Add(String.Format("{0}", ""));
}
}
writer.WriteRow(row1);
}
}
System.Diagnostics.Process.Start(Application.StartupPath + "/" + Filename + ".txt");//OPEN THE CSV FILE ,,CSV FILE NAMED AS DATA.CSV
}
catch (Exception) { MessageBox.Show("file is already open\nclose the file"); }
return;
}
else
{
_lblerror.Visible = true;
_lblerror.Text = "OOPS there is some iossue occured. Please contact developer as soon as possible";
}
}
catch
{
_lblerror.Visible = true;
_lblerror.Text = "OOPS there is some iossue occured. Please contact developer as soon as possible";
}
}
public class CsvFileWriter : StreamWriter //Writing data to CSV
{
public CsvFileWriter(Stream stream)
: base(stream)
{
}
public CsvFileWriter(string filename)
: base(filename)
{
}
public class CsvRow : List<string> //Making each CSV rows
{
public string LineText { get; set; }
}
public void WriteRow(CsvRow row)
{
StringBuilder builder = new StringBuilder();
bool firstColumn = true;
foreach (string value in row)
{
builder.Append(value.Replace("\n", "") + "\t");
}
row.LineText = builder.ToString();
WriteLine(row.LineText);
}
}
private void btnsubmit_Click(object sender, System.EventArgs e)
{
Process();
}
private void Form1_Shown(object sender, System.EventArgs e)
{
}
private void chkstorelist_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>/Project factorydirect/palyerborndate/palyerborndate/ComonFunction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bestbuy
{
class ComonFunction
{
}
public class Pickup
{
public string status { get; set; }
public bool purchasable { get; set; }
}
public class Shipping
{
public string status { get; set; }
public bool purchasable { get; set; }
}
public class Availability
{
public Pickup pickup { get; set; }
public Shipping shipping { get; set; }
public string sku { get; set; }
public string saleChannelExclusivity { get; set; }
public bool scheduledDelivery { get; set; }
public bool isGiftCard { get; set; }
public bool isService { get; set; }
}
public class RootObject
{
public List<Availability> availabilities { get; set; }
public PdpProduct pdpProduct { get; set; }
}
#region pdproduct
public class AdditionalMedia
{
public string thumbnailUrl { get; set; }
public string url { get; set; }
public string mimeType { get; set; }
}
public class Seller
{
public object name { get; set; }
public object id { get; set; }
public string url { get; set; }
}
public class PdpProduct
{
public string sku { get; set; }
public string name { get; set; }
public double regularPrice { get; set; }
public double salePrice { get; set; }
public string thumbnailImage { get; set; }
public string productUrl { get; set; }
public double ehf { get; set; }
public bool hideSavings { get; set; }
public bool isSpecialDelivery { get; set; }
public object saleEndDate { get; set; }
public List<AdditionalMedia> additionalMedia { get; set; }
public Seller seller { get; set; }
public bool isMarketplace { get; set; }
public string brandName { get; set; }
}
#endregion pdpproduct
}
<file_sep>/Project 1/crawler/palyerborndate/BusinessLayer/Mail.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace BusinessLayer
{
public class Mail
{
public void SendMail(string body, string subject, bool Isattachment, bool Exception, int ErrorTypeID)
{
DB _db = new DB();
try
{
string MailServerDNS = "";
string MailServerUserName = "";
string MailServerPassword = "";
int MailServerTCPPort = 0;
bool MailServerRequireSSL = false;
string MailsendTO = "";
#region GetDetailsOfHost
SqlDataReader _Reader = _db.GetDR("SELECT * FROM EmailCreditionals");
if (_Reader.HasRows)
{
while (_Reader.Read())
{
try
{
MailServerDNS = _Reader["Mail Server DNS"].ToString();
MailServerUserName = _Reader["Mail Server Username"].ToString();
MailServerPassword = _Reader["Mail Server Password"].ToString();
MailServerTCPPort = Convert.ToInt32(_Reader["Mail Server TCP Port"]);
MailServerRequireSSL = Convert.ToBoolean(_Reader["Mail Server Requires SSL"]);
MailsendTO = _Reader["Mail Send To"].ToString();
}
catch { }
}
_Reader.Close();
}
try { _Reader.Close(); }
catch { }
#endregion GetDetailsOfHost
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
MailAddress Fromaddress = new MailAddress(MailServerUserName, "Vishal Consultancy");
message.From = Fromaddress;
message.Subject = subject;
message.To.Add(new MailAddress(MailServerUserName));
message.Body = body;
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient mclient = new System.Net.Mail.SmtpClient();
mclient.Host = MailServerDNS;
mclient.Port = MailServerTCPPort;
mclient.EnableSsl = MailServerRequireSSL;
try
{
string[] mails = MailsendTO.Split(',');
MailsendTO = "";
foreach (string mail in mails)
{
if (mail.Length > 0)
{
try
{
message.CC.Add(mail);
MailsendTO = MailsendTO + "," + mail;
}
catch { }
}
}
}
catch
{
}
mclient.Credentials = new System.Net.NetworkCredential(MailServerUserName, MailServerPassword);
mclient.Send(message);
#region InsertErrorEmails
_db.ExecuteCommand("insert into ErrorEmails(ErrorDescription,ErrorTypeID,SendTo,CreatedOn) values('" + body + "',"+ErrorTypeID+",'" + MailsendTO + "','" + DateTime.Now + "')");
#endregion InsertErrorEmails
}
catch
{
#region InsertErrorEmails
_db.ExecuteCommand("insert into ErrorEmails(ErrorDescription,ErrorTypeID,SendTo,CreatedOn) values('" + body + "',"+ErrorTypeID+",'','" + DateTime.Now + "')");
#endregion InsertErrorEmails
}
}
}
}
<file_sep>/Project 1/crawler/palyerborndate/BusinessLayer/Product.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BusinessLayer
{
public class Product
{
public string SKU { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Weight { get; set; }
public decimal Shipping { get; set; }
public string Bulletpoints { get; set; }
public string Manufacturer { get; set; }
public string Brand { get; set; }
public string Price { get; set; }
public string Currency { get; set; }
public string Stock { get; set; }
public string Image { get; set; }
public string URL { get; set; }
public string Size { get; set; }
public string Color { get; set; }
public bool Isparent { get; set; }
public string parentsku { get; set; }
public string Bulletpoints1 { get; set; }
public string Bulletpoints2 { get; set; }
public string Bulletpoints3 { get; set; }
public string Bulletpoints4 { get; set; }
public string Bulletpoints5 { get; set; }
public string Category { get; set; }
public string Style { get; set; }
public int MinimumAgeRecommend { get; set; }
public string AgeUnitMeasure { get; set; }
}
public class ProductMerge
{
public bool ProductDatabaseIntegration(List<Product> Products, string StoreName, int ErrorTypeID)
{
#region delete Products with no sku and name information
Mail _Mail = new Mail();
List<Product> PrdList = (from _prd in Products
where _prd.SKU.Trim() != "" && _prd.Name.Trim() != ""
select _prd).ToList();
List<Product> query = (PrdList.GroupBy(x => x.SKU).Select(y => y.FirstOrDefault())).ToList();
#endregion delete Products with no sku and name information
DataTable exceldt = new DataTable();
exceldt.Columns.Add("Rowid", typeof(int));
exceldt.Columns.Add("SKU", typeof(string));
exceldt.Columns.Add("Product Name", typeof(string));
exceldt.Columns.Add("Product Description", typeof(string));
exceldt.Columns.Add("Bullet Points", typeof(string));
exceldt.Columns.Add("Manufacturer", typeof(string));
exceldt.Columns.Add("Brand Name", typeof(string));
exceldt.Columns.Add("Price", typeof(decimal));
exceldt.Columns.Add("Currency", typeof(string));
exceldt.Columns.Add("In Stock", typeof(string));
exceldt.Columns.Add("Image URL", typeof(string));
exceldt.Columns.Add("URL", typeof(string));
exceldt.Columns.Add("Size", typeof(string));
exceldt.Columns.Add("Color", typeof(string));
exceldt.Columns.Add("Isdefault", typeof(bool));
exceldt.Columns.Add("ParentSku", typeof(string));
exceldt.Columns.Add("Bulletpoints1", typeof(string));
exceldt.Columns.Add("Bulletpoints2", typeof(string));
exceldt.Columns.Add("Bulletpoints3", typeof(string));
exceldt.Columns.Add("Bulletpoints4", typeof(string));
exceldt.Columns.Add("Bulletpoints5", typeof(string));
exceldt.Columns.Add("Category", typeof(string));
exceldt.Columns.Add("Weight", typeof(string));
exceldt.Columns.Add("Style", typeof(string));
exceldt.Columns.Add("Shipping", typeof(string));
exceldt.Columns.Add("Minimum_Manufacturer_Age_Recommended", typeof(string));
exceldt.Columns.Add("AGE_Unit_Of_Measure", typeof(string));
try
{
int Counter = 0;
foreach (Product Prd in query)
{
try
{
exceldt.Rows.Add();
exceldt.Rows[Counter][0] = Counter;
exceldt.Rows[Counter][1] = string.IsNullOrEmpty(Prd.SKU) ? "" : Regex.Replace(Prd.SKU, @"\\t|\n|\r", "");
exceldt.Rows[Counter][2] = string.IsNullOrEmpty(Prd.Name) ? "" : Regex.Replace(Prd.Name, @"\\t|\n|\r", "");
exceldt.Rows[Counter][3] = string.IsNullOrEmpty(Prd.Description) ? "" : Regex.Replace(Prd.Description, @"\\t|\n|\r", "");
exceldt.Rows[Counter][4] = string.IsNullOrEmpty(Prd.Bulletpoints) ? "" : Regex.Replace(Prd.Bulletpoints, @"\\t|\n|\r", "");
exceldt.Rows[Counter][5] = string.IsNullOrEmpty(Prd.Manufacturer) ? "" : Regex.Replace(Prd.Manufacturer, @"\\t|\n|\r", "");
exceldt.Rows[Counter][6] = string.IsNullOrEmpty(Prd.Brand) ? "" : Regex.Replace(Prd.Brand, @"\\t|\n|\r", "");
exceldt.Rows[Counter][7] = Prd.Price;
exceldt.Rows[Counter][8] = Prd.Currency;
exceldt.Rows[Counter][9] = Prd.Stock;
exceldt.Rows[Counter][10] = string.IsNullOrEmpty(Prd.Image) ? "" : Regex.Replace(Prd.Image, @"\\t|\n|\r", "");
exceldt.Rows[Counter][11] = string.IsNullOrEmpty(Prd.URL) ? "" : Regex.Replace(Prd.URL, @"\\t|\n|\r", "");
exceldt.Rows[Counter][12] = string.IsNullOrEmpty(Prd.Size) ? "" : Regex.Replace(Prd.Size, @"\\t|\n|\r", "");
exceldt.Rows[Counter][13] = string.IsNullOrEmpty(Prd.Color) ? "" : Regex.Replace(Prd.Color, @"\\t|\n|\r", "");
exceldt.Rows[Counter][14] = Prd.Isparent;
exceldt.Rows[Counter][15] = string.IsNullOrEmpty(Prd.parentsku) ? "" : Regex.Replace(Prd.parentsku, @"\\t|\n|\r", "");
exceldt.Rows[Counter][16] = string.IsNullOrEmpty(Prd.Bulletpoints1) ? "" : Regex.Replace(Prd.Bulletpoints1, @"\\t|\n|\r", "");
exceldt.Rows[Counter][17] = string.IsNullOrEmpty(Prd.Bulletpoints2) ? "" : Regex.Replace(Prd.Bulletpoints2, @"\\t|\n|\r", "");
exceldt.Rows[Counter][18] = string.IsNullOrEmpty(Prd.Bulletpoints3) ? "" : Regex.Replace(Prd.Bulletpoints3, @"\\t|\n|\r", "");
exceldt.Rows[Counter][19] = string.IsNullOrEmpty(Prd.Bulletpoints4) ? "" : Regex.Replace(Prd.Bulletpoints4, @"\\t|\n|\r", "");
exceldt.Rows[Counter][20] = string.IsNullOrEmpty(Prd.Bulletpoints5) ? "" : Regex.Replace(Prd.Bulletpoints5, @"\\t|\n|\r", "");
exceldt.Rows[Counter][21] = string.IsNullOrEmpty(Prd.Category) ? "" : Regex.Replace(Prd.Category, @"\\t|\n|\r", "");
exceldt.Rows[Counter][22] = Prd.Weight;
exceldt.Rows[Counter][23] = string.IsNullOrEmpty(Prd.Style) ? "" : Regex.Replace(Prd.Style, @"\\t|\n|\r", "");
exceldt.Rows[Counter][24] = Prd.Shipping;
exceldt.Rows[Counter][25] = Prd.MinimumAgeRecommend;
exceldt.Rows[Counter][26] = string.IsNullOrEmpty(Prd.AgeUnitMeasure) ? "" : Regex.Replace(Prd.AgeUnitMeasure, @"\\t|\n|\r", "");
}
catch
{
}
Counter++;
}
#region DBChanges
int ProcessedStatus = 1;
DB _Db = new DB();
#region MarkProductsAsOutofStock
try
{
_Db.GetDatasetByPassDatatable("MarkProductsAsOutOfStock", exceldt, "@Products", CommandType.StoredProcedure, "@StoreName," + StoreName);
}
catch
{
_Mail.SendMail("OOPS there is issue accured in mark products as out of stock in database " + StoreName , ", due to which all products that is going out of stock on website is remain in stock on amazon.", false, true, ErrorTypeID);
}
#endregion MarkProductsAsOutofStock
int TotalNoOfRecords = exceldt.Rows.Count;
int NoOfFeeds = 0;
if (TotalNoOfRecords % 2000 == 0)
NoOfFeeds = Convert.ToInt32(TotalNoOfRecords / 2000);
else
NoOfFeeds = Convert.ToInt32(TotalNoOfRecords / 2000) + 1;
for (int i = 0; i < NoOfFeeds; i++)
{
if (!_Db.ProductInsert(StoreName, exceldt.AsEnumerable().Skip(i * 2000).Take(2000).CopyToDataTable()))
{
_Mail.SendMail("OOPS issue accured in insertion of products in database for store " + StoreName, "Issue Occured In insertion of products in database", false, true, ErrorTypeID);
ProcessedStatus = 0;
}
}
if (exceldt.Rows.Count == 0)
{
_Mail.SendMail("OOPS there is no any product go to insert in database for " + StoreName + ", due to which all products of this store have updated inventory to 0 in database", "Issue Occured In insertion of products in database", false, true, ErrorTypeID);
ProcessedStatus = 0;
}
_Db.ExecuteCommand("update Schduler set LastProcessedStatus=" + ProcessedStatus + " where StoreName='" + StoreName + "'");
#endregion DBChanges
return true;
}
catch (Exception exp)
{
_Mail.SendMail("OOPS issue accured in insertion of products for store " + StoreName + " exp=" + exp.Message, "Issue Occured In insertion of products in database", false, true, ErrorTypeID);
return false;
}
}
}
}
| 4c288b0d65b806395a6805f3acd4cd119258e4b7 | [
"C#"
] | 21 | C# | zoharromm/Merchant-Management-System | 4a4c3f0bed1c705a87e9bcfd0cbff7bc4c377a50 | 9006ae12559be652926d765887077f9a6943cc1b |
refs/heads/master | <file_sep># Copyright (c) 2016 The OpenTracing Authors.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
class UnsupportedFormatException(Exception):
"""UnsupportedFormatException should be used when the provided format
value is unknown or disallowed by the Tracer.
See Tracer.inject() and Tracer.extract().
"""
pass
class InvalidCarrierException(Exception):
"""InvalidCarrierException should be used when the provided carrier
instance does not match what the `format` argument requires.
See Tracer.inject() and Tracer.extract().
"""
pass
class SpanContextCorruptedException(Exception):
"""SpanContextCorruptedException should be used when the underlying span
context state is seemingly present but not well-formed.
See Tracer.inject() and Tracer.extract().
"""
pass
class Format(object):
"""A namespace for builtin carrier formats.
These static constants are intended for use in the Tracer.inject() and
Tracer.extract() methods. E.g.::
tracer.inject(span.context, Format.BINARY, binary_carrier)
"""
BINARY = 'binary'
"""
The BINARY format represents SpanContexts in an opaque bytearray carrier.
For both Tracer.inject() and Tracer.extract() the carrier should be a
bytearray instance. Tracer.inject() must append to the bytearray carrier
(rather than replace its contents).
"""
TEXT_MAP = 'text_map'
"""
The TEXT_MAP format represents SpanContexts in a python dict mapping from
strings to strings.
Both the keys and the values have unrestricted character sets (unlike the
HTTP_HEADERS format).
NOTE: The TEXT_MAP carrier dict may contain unrelated data (e.g.,
arbitrary gRPC metadata). As such, the Tracer implementation should use a
prefix or other convention to distinguish Tracer-specific key:value
pairs.
"""
HTTP_HEADERS = 'http_headers'
"""
The HTTP_HEADERS format represents SpanContexts in a python dict mapping
from character-restricted strings to strings.
Keys and values in the HTTP_HEADERS carrier must be suitable for use as
HTTP headers (without modification or further escaping). That is, the
keys have a greatly restricted character set, casing for the keys may not
be preserved by various intermediaries, and the values should be
URL-escaped.
NOTE: The HTTP_HEADERS carrier dict may contain unrelated data (e.g.,
arbitrary gRPC metadata). As such, the Tracer implementation should use a
prefix or other convention to distinguish Tracer-specific key:value
pairs.
"""
<file_sep>Python API
==========
Classes
-------
.. autoclass:: opentracing.Span
:members:
.. autoclass:: opentracing.SpanContext
:members:
.. autoclass:: opentracing.Tracer
:members:
.. autoclass:: opentracing.ReferenceType
:members:
.. autoclass:: opentracing.Reference
:members:
.. autoclass:: opentracing.Format
:members:
Utility Functions
-----------------
.. autofunction:: opentracing.start_child_span
.. autofunction:: opentracing.child_of
.. autofunction:: opentracing.follows_from
Exceptions
----------
.. autoclass:: opentracing.InvalidCarrierException
:members:
.. autoclass:: opentracing.SpanContextCorruptedException
:members:
.. autoclass:: opentracing.UnsupportedFormatException
:members:
<file_sep># Copyright (c) 2016 The OpenTracing Authors.
#
# Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
# The following tags are described in greater detail at the following url:
# https://github.com/opentracing/specification/blob/master/semantic_conventions.md
# Here we define standard names for tags that can be added to spans by the
# instrumentation code. The actual tracing systems are not required to
# retain these as tags in the stored spans if they have other means of
# representing the same data. For example, the SPAN_KIND='server' can be
# inferred from a Zipkin span by the presence of ss/sr annotations.
# ---------------------------------------------------------------------------
# SPAN_KIND hints at relationship between spans, e.g. client/server
# ---------------------------------------------------------------------------
SPAN_KIND = 'span.kind'
# Marks a span representing the client-side of an RPC or other remote call
SPAN_KIND_RPC_CLIENT = 'client'
# Marks a span representing the server-side of an RPC or other remote call
SPAN_KIND_RPC_SERVER = 'server'
# ---------------------------------------------------------------------------
# ERROR indicates whether a Span ended in an error state.
# ---------------------------------------------------------------------------
ERROR = 'error'
# ---------------------------------------------------------------------------
# COMPONENT (string) ia s low-cardinality identifier of the module, library,
# or package that is generating a span.
# ---------------------------------------------------------------------------
COMPONENT = 'component'
# ---------------------------------------------------------------------------
# SAMPLING_PRIORITY (uint16) determines the priority of sampling this Span.
# ---------------------------------------------------------------------------
SAMPLING_PRIORITY = 'sampling.priority'
# ---------------------------------------------------------------------------
# PEER_* tags can be emitted by either client-side of server-side to describe
# the other side/service in a peer-to-peer communications, like an RPC call.
# ---------------------------------------------------------------------------
# PEER_SERVICE (string) records the service name of the peer
PEER_SERVICE = 'peer.service'
# PEER_HOSTNAME (string) records the host name of the peer
PEER_HOSTNAME = 'peer.hostname'
# PEER_ADDRESS (string) suitable for use in a networking client library.
# This may be a "ip:port", a bare "hostname", a FQDN, or even a
# JDBC substring like "mysql://prod-db:3306"
PEER_ADDRESS = 'peer.address'
# PEER_HOST_IPV4 (uint32) records IP v4 host address of the peer
PEER_HOST_IPV4 = 'peer.ipv4'
# PEER_HOST_IPV6 (string) records IP v6 host address of the peer
PEER_HOST_IPV6 = 'peer.ipv6'
# PEER_PORT (uint16) records port number of the peer
PEER_PORT = 'peer.port'
# ---------------------------------------------------------------------------
# HTTP tags
# ---------------------------------------------------------------------------
# HTTP_URL (string) should be the URL of the request being handled in this
# segment of the trace, in standard URI format. The protocol is optional.
HTTP_URL = 'http.url'
# HTTP_METHOD (string) is the HTTP method of the request.
# Both upper/lower case values are allowed.
HTTP_METHOD = 'http.method'
# HTTP_STATUS_CODE (int) is the numeric HTTP status code (200, 404, etc)
# of the HTTP response.
HTTP_STATUS_CODE = 'http.status_code'
# ---------------------------------------------------------------------------
# DATABASE tags
# ---------------------------------------------------------------------------
# DATABASE_INSTANCE (string) The database instance name. E.g., In java, if
# the jdbc.url="jdbc:mysql://127.0.0.1:3306/customers", the instance
# name is "customers"
DATABASE_INSTANCE = 'db.instance'
# DATABASE_STATEMENT (string) A database statement for the given database
# type. E.g., for db.type="SQL", "SELECT * FROM user_table";
# for db.type="redis", "SET mykey 'WuValue'".
DATABASE_STATEMENT = 'db.statement'
# DATABASE_TYPE (string) For any SQL database, "sql". For others,
# the lower-case database category, e.g. "cassandra", "hbase", or "redis".
DATABASE_TYPE = 'db.type'
# DATABASE_USER (string) Username for accessing database. E.g.,
# "readonly_user" or "reporting_user"
DATABASE_USER = 'db.user'
# ---------------------------------------------------------------------------
# MESSAGE_BUS tags
# ---------------------------------------------------------------------------
# MESSAGE_BUS_DESTINATION (string) An address at which messages can be
# exchanged. E.g. A Kafka record has an associated "topic name" that can
# be extracted by the instrumented producer or consumer and stored
# using this tag.
MESSAGE_BUS_DESTINATION = 'message_bus.destination'
| 3152bc9c6f323ad58c4f17ca56bbd5d506ca20da | [
"Python",
"reStructuredText"
] | 3 | Python | Shreya1771/opentracing-python | c564cd7cb07b6bbefe1335f9b214e95e828561b2 | 4036cec62e52d3ba14e63f9e0d96a126f1f8b314 |
refs/heads/master | <file_sep>class Engine {
static time: number = 0; //frames since the game started
//what happens every frame
private static loop = () => {
Engine.scene.updateAll();
gl.clear(gl.COLOR_BUFFER_BIT);
Engine.scene.camera.drawAll();
Input.resetKeys();
Engine.time++;
requestAnimationFrame(Engine.loop);
}
//kicks off the engine
static start = () => {
requestAnimationFrame(Engine.loop);
}
static canvas: HTMLCanvasElement = document.getElementById("game") as HTMLCanvasElement;
static scene: Scene;
static loadSprite(url: string) {
let spr = new Image();
spr.src = workingDir + url;
let loadIndex = this.loadQueue.push(spr);
spr.onload = () => {
Engine.onResourceLoaded(loadIndex);
}
log("Loading " + url);
return spr;
}
private static onResourceLoaded(loadIndex: ListNode<any>) {
this.loadQueue.remove(loadIndex);
if (this.loadQueue.length == 0) {
log("All resources loaded!");
Engine.start();
}
}
private static loadQueue = new List<any>();
}
log("Loading engine...");<file_sep>let canvas = <HTMLCanvasElement>$("#game")[0];
let gl = canvas.getContext("webgl");
function createShader(type: number, source: string): WebGLShader {
let shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (success) {
return shader;
}
console.log(gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
}
function createProgram(verterShader: WebGLShader, fragmentShader: WebGLShader) {
let program = gl.createProgram();
gl.attachShader(program, verterShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (success) {
return program;
}
console.log(gl.getProgramInfoLog(program));
gl.deleteProgram(program);
}
let imageVertexCode =
`attribute vec4 a_position;
attribute vec2 a_texCoord;
uniform mat4 u_matrix;
varying vec2 v_texCoord;
void main() {
gl_Position = u_matrix * a_position;
v_texCoord = a_texCoord;
}`
let imageFragmentCode =
`precision mediump float;
uniform sampler2D u_texture;
varying vec2 v_texCoord;
void main() {
gl_FragColor = texture2D(u_texture, v_texCoord);
}`;
gl.clearColor(0, 0, 0, 1);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
let imageVertexShader = createShader(gl.VERTEX_SHADER, imageVertexCode);
let imageFragmentShader = createShader(gl.FRAGMENT_SHADER, imageFragmentCode);
let imageProgram = createProgram(imageVertexShader, imageFragmentShader);
let a_position_image = gl.getAttribLocation(imageProgram, "a_position");
let a_texCoord_image = gl.getAttribLocation(imageProgram, "a_texCoord");
let u_matrix_image = gl.getUniformLocation(imageProgram, "u_matrix");
let u_texture_image = gl.getUniformLocation(imageProgram, "u_texture");
//buffering coords
let rectCoords = new Float32Array([
0, 0,
0, 1,
1, 0,
1, 0,
0, 1,
1, 1,
]);
let positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, rectCoords, gl.STATIC_DRAW);
let texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, rectCoords, gl.STATIC_DRAW);
function drawImage(tInfo: {width: number, height: number, tex: WebGLTexture}, x: number, y: number) {
gl.bindTexture(gl.TEXTURE_2D, tInfo.tex);
gl.useProgram(imageProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.enableVertexAttribArray(a_position_image);
gl.vertexAttribPointer(a_position_image, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.enableVertexAttribArray(a_texCoord_image);
gl.vertexAttribPointer(a_texCoord_image, 2, gl.FLOAT, false, 0, 0);
let matrix = m4.orthographic(0, 0, gl.canvas.width, gl.canvas.height, -1, 1);
matrix = m4.translate(matrix, x, y, 0);
matrix = m4.scale(matrix, tInfo.width, tInfo.height, 1);
gl.uniformMatrix4fv(u_matrix_image, false, matrix);
gl.uniform1i(u_texture_image, 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
function createTexture(url: string) {
let tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
let textureInfo = {
width: 1,
height: 1,
tex: tex,
};
let img = new Image();
img.onload = () => {
textureInfo.width = img.width;
textureInfo.height = img.height;
gl.bindTexture(gl.TEXTURE_2D, textureInfo.tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
drawImage(textureInfo, 100, 100);
}
img.src = url;
img.crossOrigin = "";
return textureInfo;
}
let shapeVertexCode =
`attribute vec4 a_position;
uniform mat4 u_matrix;
void main() {
gl_Position = u_matrix * a_position;
}`;
let shapeFragmentCode =
`precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}`;
let shapeVertexShader = createShader(gl.VERTEX_SHADER, shapeVertexCode);
let shapeFragmentShader = createShader(gl.FRAGMENT_SHADER, shapeFragmentCode);
let shapeProgram = createProgram(shapeVertexShader, shapeFragmentShader);
let a_position_shape = gl.getAttribLocation(shapeProgram, "a_position");
let u_matrix_shape = gl.getUniformLocation(shapeProgram, "u_matrix");
let u_color_shape = gl.getUniformLocation(shapeProgram, "u_color");
let shapePositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, shapePositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, rectCoords, gl.STATIC_DRAW);
function drawRect(x: number, y: number, width: number, height: number, color: Color) {
gl.useProgram(shapeProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, shapePositionBuffer);
gl.enableVertexAttribArray(a_position_shape);
gl.vertexAttribPointer(a_position_shape, 2, gl.FLOAT, false, 0, 0);
let matrix = m4.orthographic(0, 0, gl.canvas.width, gl.canvas.height, -1, 1);
matrix = m4.translate(matrix, x, y, 0);
matrix = m4.scale(matrix, width, height, 1);
gl.uniformMatrix4fv(u_matrix_shape, false, matrix);
color = color.float();
gl.uniform4fv(u_color_shape, new Float32Array([color.r, color.g, color.b, color.a]));
gl.drawArrays(gl.TRIANGLES, 0, 6);
}<file_sep>Engine.scene = new Scene(460, 320);
let amount = 1;
class PTest extends GameObject {
emitter: ParticleEmitter;
o: GameObject = null;
constructor(pos: Vector) {
super(pos);
this.emitter = new ParticleEmitter();
}
update() {
this.emitter.burst(this.pos, amount);
}
}
let pt = new PTest(new Vector(Engine.scene.width/2, Engine.scene.height/2));
$(document).ready(function() {
$(".part__input").children().each(function() {
$(this).trigger("input");
});
});
$("#amount").on("input", (o) => {
amount = Number($("#amount").val());
});
$("#minAlpha").on("input", (o) => {
pt.emitter.minAlpha = Number($("#minAlpha").val());
});
$("#maxAlpha").on("input", (o) => {
pt.emitter.maxAlpha = Number($("#maxAlpha").val());
});
$("#alphaIncr").on("input", (o) => {
pt.emitter.alphaIncr = Number($("#alphaIncr").val());
});
$("#minLifetime").on("input", (o) => {
pt.emitter.minLifetime = Number($("#minLifetime").val());
});
$("#maxLifetime").on("input", (o) => {
pt.emitter.maxLifetime = Number($("#maxLifetime").val());
});
$("#minSpeed").on("input", (o) => {
pt.emitter.minSpeed = Number($("#minSpeed").val());
});
$("#maxSpeed").on("input", (o) => {
pt.emitter.maxSpeed = Number($("#maxSpeed").val());
});
$("#speedIncr").on("input", (o) => {
pt.emitter.speedIncr = Number($("#speedIncr").val());
});
$("#minDirection").on("input", (o) => {
pt.emitter.minDirection = Number($("#minDirection").val());
});
$("#maxDirection").on("input", (o) => {
pt.emitter.maxDirection = Number($("#maxDirection").val());
});
$("#directionIncr").on("input", (o) => {
pt.emitter.directionIncr = Number($("#directionIncr").val());
});
$("#minSize").on("input", (o) => {
pt.emitter.minSize = Number($("#minSize").val());
});
$("#maxSize").on("input", (o) => {
pt.emitter.maxSize = Number($("#maxSize").val());
});
$("#sizeIncr").on("input", (o) => {
pt.emitter.sizeIncr = Number($("#sizeIncr").val());
});
$("#minAngle").on("input", (o) => {
pt.emitter.minAngle = Number($("#minAngle").val());
});
$("#maxAngle").on("input", (o) => {
pt.emitter.maxAngle = Number($("#maxAngle").val());
});
$("#angleIncr").on("input", function() {
pt.emitter.angleIncr = Number($("#angleIncr").val());
});
$("#scaleX").on("input", function() {
pt.emitter.scale.x = Number($("#scaleX").val());
});
$("#scaleY").on("input", function() {
pt.emitter.scale.y = Number($("#scaleY").val());
});
$("#startColor").children().children(".r").on("input", function() {
pt.emitter.startColor.r = Number($(this).val());
});
$("#startColor").children().children(".g").on("input", function() {
pt.emitter.startColor.g = Number($(this).val());
});
$("#startColor").children().children(".b").on("input", function() {
pt.emitter.startColor.b = Number($(this).val());
});
$("#endColor").children().children(".r").on("input", function() {
pt.emitter.endColor.r = Number($(this).val());
});
$("#endColor").children().children(".g").on("input", function() {
pt.emitter.endColor.g = Number($(this).val());
});
$("#endColor").children().children(".b").on("input", function() {
pt.emitter.endColor.b = Number($(this).val());
});
<file_sep>const abs = Math.abs;
const sqrt = Math.sqrt;
const pow = Math.pow;
const random = Math.random;
const sqr = (x) => { return x*x };
const sign = (a) => {
if (a > 0) {
return 1;
} else if (a < 0) {
return -1;
} else {
return 0;
}
}
const degToRad = Math.PI/180;
const sin = (a:number) => { return Math.sin(a * degToRad) };
const cos = (a:number) => { return Math.cos(a * degToRad) };
var loc = window.location.pathname;
const workingDir = loc.substring(0, loc.lastIndexOf('/'));
class Vector {
x: number;
y: number;
constructor(x: number = 0, y: number = 0) {
this.x = x;
this.y = y;
}
add(other: Vector) {
return new Vector(this.x + other.x, this.y + other.y);
}
sub(other: Vector) {
return new Vector(this.x - other.x, this.y - other.y);
}
mult(n: number) {
return new Vector(this.x*n, this.y*n);
}
mod() {
return sqrt(this.x*this.x + this.y*this.y);
}
norm() {
let mod = this.mod();
if (mod == 0) {
return new Vector(0, 0);
}
return this.mult(1/mod);
}
translate(other: Vector) {
this.x += other.x;
this.y += other.y;
}
toString() {
return this.x + ", " + this.y;
}
}
let debugOn: boolean = true;
function log(...text: any[]) {
if (debugOn) {
console.log(text.join(", "));
}
}
class List<T> {
first: ListNode<T> = null;
last: ListNode<T> = null;
length: number = 0;
push(val: T) {
let prev = this.last;
let newNode = new ListNode(val, prev, null);
if (prev == null) {
this.first = newNode;
this.last = newNode;
this.length++;
return newNode;
}
this.last = newNode;
prev.next = newNode;
this.length++;
return newNode;
}
remove(node: ListNode<T>) {
let prev = node.prev;
let next = node.next;
if (prev == null) {
this.first = next;
} else {
prev.next = next;
}
if (next == null) {
this.last = prev;
} else {
next.prev = prev;
}
this.length--;
}
forEach(callback: (elem: T) => any, that: any = this) {
let curr = this.first;
while(curr != null) {
callback.call(that, curr.val);
curr = curr.next;
}
}
}
class ListNode<T> {
constructor(
public val: T,
public prev: ListNode<T>,
public next: ListNode<T>
) {}
}
class Rect {
constructor(
public left: number,
public top: number,
public right: number,
public bottom: number
) {}
}
class Color {
constructor(
public r: number,
public g: number,
public b: number,
public a: number = 1
) {}
string() {
return "rgb("+this.r+","+this.g+","+this.b+")";
}
add(other: Color) {
this.r += other.r;
this.g += other.g;
this.b += other.b;
this.a += other.a;
}
float() {
return new Color(this.r/255, this.g/255, this.b/255, this.a);
}
}
function randomRange(min: number, max: number) {
return Math.random() * (max - min) + min;
}
class Stack<T> {
private last: StackNode<T>;
public length: number = 0;
constructor(public cap: number = 0) {};
push(val: T) {
this.length++;
if (this.cap > 0 && this.length > this.cap) {
log("Error! Stack capacity exceeded.");
this.length--;
return;
}
this.last = new StackNode(val, this.last);
}
pop() {
if (this.last == undefined) {
return null;
}
let res = this.last.val;
this.last = this.last.prev;
this.length--;
return res;
}
peek() {
if (this.last == undefined) {
return null;
}
return this.last.val;
}
forEach(handler: (elem: T) => any, that: any = this) {
let curr = this.pop();
while (curr !== null) {
handler.call(that, curr);
curr = this.pop();
}
}
}
class StackNode<T> {
constructor(
public val: T,
public prev: StackNode<T>
) {}
}
log("Loading utitlities...");<file_sep>class GameObject implements Drawable, Updatable {
pos: Vector; //position in the scene
scale: Vector; // object scale affects both renderer and colliders
angle: number; //rotation
sprite: HTMLImageElement;
spriteOff: Vector;
alpha: number;
private layer: number;
updateIndex: ListNode<Updatable>;
drawIndex: ListNode<Drawable>;
constructor(pos: Vector) {
this.pos = pos;
this.scale = new Vector(1, 1);
this.angle = 0;
this.updateIndex = Engine.scene.updaters.push(this);
this.layer = 0;
if (Engine.scene.renderers[this.layer] == undefined) {
Engine.scene.renderers[this.layer] = new List<Drawable>();
}
this.drawIndex = Engine.scene.renderers[this.layer].push(this);
}
update() {}
drawSelf() {
drawSprite(this.sprite, this.pos, this.spriteOff, this.alpha, this.angle, this.scale);
}
draw() {
this.drawSelf();
}
destroy() {
Engine.scene.updaters.remove(this.updateIndex);
Engine.scene.renderers[this.layer].remove(this.drawIndex);
}
setLayer(layer: number) {
Engine.scene.renderers[this.layer].remove(this.drawIndex);
this.drawIndex = Engine.scene.renderers[layer].push(this);
this.layer = layer;
}
}
let sprPlayer = Engine.loadSprite("/js/resources/sprites/player.png");
class Player extends GameObject {
sparkles: ParticleEmitter;
constructor(pos: Vector) {
super(pos);
this.sprite = sprPlayer;
this.spriteOff = new Vector(16, 16);
this.sparkles = new ParticleEmitter();
this.sparkles.setAngle(0, 0, 0);
this.sparkles.setLayer(1);
this.sparkles.setShape("box");
this.sparkles.setAlpha(0.6, 0.8, -0.01);
this.sparkles.setScale(new Vector(10, 10), 1, 4, -0.1);
this.sparkles.setSpeed(2, 4, -0.05);
this.sparkles.setColor(new Color(255, 100, 40), new Color(50, 255, 30));
}
update() {
this.sparkles.burst(this.pos, 5);
}
draw() {
this.drawSelf();
}
}
log("Loading game objects...");<file_sep>class Particle implements Drawable, Updatable {
shape: string;
lifetime: number;
pos: Vector;
speed: Vector;
maxSpeed: number;
speedIncr: number;
direction: number;
directionIncr: number;
scale: Vector;
scaleIncr: number;
alpha: number;
alphaIncr: number;
angle: number;
angleIncr: number;
color: Color;
colorIncr: Color;
updateIndex: ListNode<Updatable>;
drawIndex: ListNode<Drawable>;
layer: number;
constructor() {
this.speed = new Vector();
}
draw() {
let cam = Engine.scene.camera;
let x = this.pos.x - cam.pos.x;
let y = this.pos.y - cam.pos.y;
//console.log(this.color);
//color
switch (this.shape) {
case "box": {
drawRect(
x-this.scale.x/2,
y-this.scale.y/2,
this.scale.x,
this.scale.y,
this.color,
);
break;
}
case "circle": {
// ctx.beginPath();
// ctx.arc(x, y, this.scale.x, 0, Math.PI*2, true);
// ctx.closePath();
// ctx.fill();
break;
}
}
}
update() {
this.speed.x = this.maxSpeed*cos(this.direction);
this.speed.y = -this.maxSpeed*sin(this.direction);
this.speed = this.speed.norm().mult(this.maxSpeed * sign(this.maxSpeed));
this.pos.translate(this.speed);
this.maxSpeed += this.speedIncr;
this.scale.translate(new Vector(this.scaleIncr, this.scaleIncr));
this.alpha += this.alphaIncr;
this.angle += this.angleIncr;
this.direction += this.directionIncr;
this.color.add(this.colorIncr);
let cam = Engine.scene.camera;
if (this.lifetime <= 0 || this.alpha < 0 || this.scale.x < 0 || this.scale.y < 0 ||
this.pos.x < 0 || this.pos.x > cam.view.x || this.pos.y < 0 || this.pos.y > cam.view.y) {
this.destroy();
}
this.lifetime--;
}
destroy() {
Engine.scene.renderers[this.layer].remove(this.drawIndex);
Engine.scene.updaters.remove(this.updateIndex);
}
}
log("Loading particles...");<file_sep>class ParticleEmitter {
//emitter properties
emitRegion: Rect = new Rect(0, 0, 0, 0);
//particle properties
shape: string = "box";
minLifetime: number = 40;
maxLifetime: number = 150;
minSpeed: number = 1;
maxSpeed: number = 2;
speedIncr: number = 0.1;
minDirection: number = 0;
maxDirection: number = 360;
directionIncr: number = 0;
scale: Vector = new Vector(5, 5);
sizeIncr: number = 0;
minSize: number = 1;
maxSize: number = 3;
minAlpha: number = 0.5;
maxAlpha: number = 1;
alphaIncr: number = 0;
minAngle: number = 0;
maxAngle: number = 0;
angleIncr: number = 0;
startColor: Color = new Color(0, 0, 255);
endColor: Color = new Color(0, 255, 0);
layer: number = 0;
burst(pos: Vector, amount: number) {
for (let i = 0; i < amount; i++) {
let p = this.createParticle(pos);
}
}
setRegion(region: Rect) {
this.emitRegion = region;
}
setShape(shape: string) {
this.shape = shape;
}
setLifetime(minLifetime: number, maxLifetime: number) {
this.minLifetime = minLifetime;
this.maxLifetime = maxLifetime;
}
setSpeed(minSpeed: number, maxSpeed: number, speedIncr: number) {
this.minSpeed = minSpeed;
this.maxSpeed = maxSpeed;
this.speedIncr = speedIncr;
}
setDirection(minDirection: number, maxDirection: number, directionIncr: number) {
this.minDirection = minDirection;
this.maxDirection = maxDirection;
this.directionIncr = directionIncr;
}
setScale(scale: Vector, minSize: number, maxSize: number, sizeIncr: number) {
this.scale = scale;
this.minSize = minSize;
this.maxSize = maxSize;
this.sizeIncr = sizeIncr;
}
setAlpha(minAlpha: number, maxAlpha: number, alphaIncr: number) {
this.minAlpha = minAlpha;
this.maxAlpha = maxAlpha;
this.alphaIncr = alphaIncr;
}
setAngle(minAngle: number, maxAngle: number, angleIncr: number) {
this.minAngle = minAngle;
this.maxAngle = maxAngle;
this.angleIncr = angleIncr;
}
setColor(startColor: Color, endColor: Color) {
this.startColor = startColor;
this.endColor = endColor;
}
setLayer(layer: number) {
this.layer = layer;
}
private createParticle(pos: Vector) {
let p = new Particle();
p.pos = pos.add(new Vector(
randomRange(this.emitRegion.left, this.emitRegion.right),
randomRange(this.emitRegion.top, this.emitRegion.bottom)
));
p.shape = this.shape;
p.lifetime = randomRange(this.minLifetime, this.maxLifetime);
p.maxSpeed = randomRange(this.minSpeed, this.maxSpeed);
p.speedIncr = this.speedIncr;
p.direction = randomRange(this.minDirection, this.maxDirection);
p.directionIncr = this.directionIncr;
let size = randomRange(this.minSize, this.maxSize);
p.scale = this.scale.mult(size);
p.scaleIncr = this.sizeIncr;
p.alpha = randomRange(this.minAlpha, this.maxAlpha);
p.alphaIncr = this.alphaIncr;
p.angle = randomRange(this.minAngle, this.maxAngle);
p.angleIncr = this.angleIncr;
p.color = new Color(this.startColor.r, this.startColor.g, this.startColor.b, p.alpha);
p.colorIncr = new Color(
Math.floor((this.endColor.r - this.startColor.r)/p.lifetime),
Math.floor((this.endColor.g - this.startColor.g)/p.lifetime),
Math.floor((this.endColor.b - this.startColor.b)/p.lifetime),
p.alphaIncr,
);
p.layer = this.layer;
if (Engine.scene.renderers[p.layer] == undefined) {
Engine.scene.renderers[p.layer] = new List<Drawable>();
}
p.drawIndex = Engine.scene.renderers[p.layer].push(p);
p.updateIndex = Engine.scene.updaters.push(p);
return p;
}
}
log("Loading particle emitters...");<file_sep>class Camera {
private canvas: HTMLCanvasElement;
context: CanvasRenderingContext2D;
constructor(canvas: HTMLCanvasElement) {
this.context = canvas.getContext("2d");
this.pos = new Vector(0, 0);
this.size = new Vector(canvas.width, canvas.height);
this.view = new Vector(canvas.width, canvas.height);
}
pos: Vector;
size: Vector;
view: Vector;
bgColor: string = "black";
drawAll() {
//clearing with background color
//gl.clear(gl.COLOR_BUFFER_BIT);
//drawing all renderers
for (let i = 0; i < Engine.scene.renderers.length; i++) {
Engine.scene.renderers[i].forEach(function(rend) {
rend.draw();
}, this);
}
}
}
function drawSprite(sprite: HTMLImageElement, pos: Vector,
offset: Vector = new Vector(), alpha: number = 1, angle: number = 0, scale: Vector = new Vector()) {
if (sprite == null) {
return;
}
let cam = Engine.scene.camera;
let ctx = cam.context;
let x = pos.x - cam.pos.x;
let y = pos.y - cam.pos.y;
ctx.save();
//sprite position
ctx.translate(x, y);
//sprite rotation
if (angle != 0) {
ctx.rotate(-angle*degToRad);
}
//sprite alpha
if (alpha != 1) {
ctx.globalAlpha = alpha;
}
//sprite scale
if (scale.x != 1 || scale.y != 1) {
ctx.scale(scale.x, scale.y);
}
ctx.drawImage(sprite, -offset.x, -offset.y);
ctx.restore();
}
log("Loading cameras...");<file_sep>class Input {
static keysPressed: boolean[] = [];
static keysDown: boolean[] = [];
static keysUp: boolean[] = [];
static getKeyPressed(keyCode) {
return Input.keysPressed[keyCode];
}
static getKeyDown(keyCode) {
return Input.keysDown[keyCode];
}
static getKeyUp(keyCode) {
return Input.keysUp[keyCode];
}
static resetKeys() {
for (var i = 0; i < Input.keysDown.length; i++) {
Input.keysDown[i] = false;
}
for (var i = 0; i < Input.keysUp.length; i++) {
Input.keysUp[i] = false;
}
}
}
window.addEventListener("keydown", (e) => {
if (Input.keysPressed[e.keyCode]) {
return;
}
Input.keysPressed[e.keyCode] = true;
Input.keysDown[e.keyCode] = true;
});
window.addEventListener("keyup", (e) => {
Input.keysPressed[e.keyCode] = false;
Input.keysUp[e.keyCode] = true;
});
const enum keyCode {
left = 37,
up = 38,
right = 39,
down = 40,
num_add = 107,
num_sub = 109,
enter = 13,
tab = 9,
esc = 27,
caps_lock = 20,
shift = 16,
space = 32,
page_up = 33,
page_down = 34,
a = 65,
b = 66,
c = 67,
d = 68,
e = 69,
f = 70,
g = 71,
h = 72,
i = 73,
j = 74,
k = 75,
l = 76,
m = 77,
n = 78,
o = 79,
p = 80,
q = 81,
r = 82,
s = 83,
t = 84,
u = 85,
v = 86,
w = 87,
x = 88,
y = 89,
z = 90
};
log("Loading input system...");<file_sep>class Scene {
camera: Camera;
width: number;
height: number;
constructor(width: number, height: number) {
this.camera = new Camera(Engine.canvas);
this.width = width;
this.height = height;
this.updaters = new List<Updatable>();
this.renderers = [];
}
renderers: List<Drawable>[];
updaters: List<Updatable>;
updateAll() {
this.updaters.forEach((upd) => {
upd.update();
}, this);
}
}
interface Drawable {
draw();
}
interface Updatable {
update();
}
log("Loading scenes..."); | 41808743ba0fcfea9f1b5a65a95d32f44ad10d36 | [
"TypeScript"
] | 10 | TypeScript | lvl5hm/tsEngine | bde8cc9472d8b3f05c0de34f0ac054492b102730 | 805df4a479c0c35e9ad1bb963bf26e6942f9af2e |
refs/heads/master | <file_sep><div class="container">
<h2>Budget Note</h2>
<div>
<span>Name:</span> {{note?.name}}
</div>
<div>
<span>Type:</span> {{note?.type}}
</div>
<div>
<span>Amount:</span> {{note?.amount}}
</div>
<div>
<span>Date:</span> {{note?.date}}
</div>
<div>
<span>Description:</span> {{note?.description}}
</div>
<button class="btn btn-primary" (click)="onDeleteNote()">Delete</button>
</div>
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { BudgetNote } from 'src/app/model/BudgetNote';
import { NotesService } from 'src/app/note.service';
@Component({
selector: 'app-create-note',
templateUrl: './create-note.component.html',
styleUrls: ['./create-note.component.css']
})
export class CreateNoteComponent implements OnInit {
noteForm !: FormGroup;
constructor(private notesService: NotesService, private router: Router) {
}
ngOnInit(): void {
let noteName = new FormControl();
let noteType = new FormControl();
let noteAmount = new FormControl();
let noteDate = new FormControl();
let noteDescription = new FormControl();
this.noteForm = new FormGroup({
noteName: noteName,
noteType: noteType,
noteAmount: noteAmount,
noteDate: noteDate,
noteDescription: noteDescription
});
}
onNoteSubmit() {
let newNote = new BudgetNote();
newNote.id = this.notesService.getLastNoteIndex() + 1;
newNote.name = this.noteForm.get('noteName')?.value;
newNote.type = this.noteForm.get('noteType')?.value;
newNote.amount = this.noteForm.get('noteAmount')?.value;
newNote.date = this.noteForm.get('noteDate')?.value;
newNote.description = this.noteForm.get('noteDescription')?.value
this.notesService.noteElements.push(newNote);
this.router.navigate(['notes']);
}
onCancelForm() {
this.router.navigate(['notes'])
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { BudgetNoteType } from '../model/BudgetNote';
import { NotesService } from '../note.service';
@Component({
selector: 'app-budget-balance',
templateUrl: './budget-balance.component.html',
styleUrls: ['./budget-balance.component.css']
})
export class BudgetBalanceComponent implements OnInit {
budgetBalance = 0;
constructor(private notesService: NotesService) { }
ngOnInit(): void {
this.notesService.getBudgetNotes().forEach(n => {
if (n.type == BudgetNoteType.Income) {
this.budgetBalance += n.amount
} else {
this.budgetBalance -= n.amount
}
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BudgetNote } from '../model/BudgetNote';
import { NotesService } from '../note.service';
@Component({
selector: 'app-budget-board',
templateUrl: './budget-board.component.html',
styleUrls: ['./budget-board.component.css']
})
export class BudgetBoardComponent implements OnInit {
notes: Array<BudgetNote> | undefined;
constructor(private noteService: NotesService, private router: Router) { }
ngOnInit(): void {
this.notes = this.noteService.getBudgetNotes();
}
handleNoteThumbnailClick(id: number | undefined) {
this.router.navigate(['note' , id])
}
}
<file_sep>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { BudgetBoardComponent } from './budget-board/budget-board.component';
import { NavigationComponent } from './navigation/navigation.component';
import { NoteThumbnailComponent } from './budget-note/note-thumbnail.component';
import { NotesService } from './note.service';
import { BudgetNoteDetailComponent } from './budget-note-detail/budget-note-detail.component';
import { Error404Component } from './error404/error404.component';
import { RouterModule } from '@angular/router';
import { routes } from './routes';
import { NotesRouteService } from './notes-rooute.service';
import { CreateNoteComponent } from './create/create-note/create-note.component';
import { ReactiveFormsModule } from '@angular/forms';
import { BudgetBalanceComponent } from './budget-balance/budget-balance.component';
@NgModule({
declarations: [
AppComponent,
BudgetBoardComponent,
NavigationComponent,
NoteThumbnailComponent,
BudgetNoteDetailComponent,
Error404Component,
CreateNoteComponent,
BudgetBalanceComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(routes),
ReactiveFormsModule
],
providers: [NotesService, NotesRouteService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { BudgetNote, BudgetNoteType } from '../model/BudgetNote';
import { NotesService } from '../note.service';
@Component({
selector: 'note-thumbnail',
templateUrl: './note-thumbnail.component.html',
styleUrls: ['./note-thumbnail.component.css']
})
export class NoteThumbnailComponent implements OnInit {
@Input() note: BudgetNote | undefined
id: number | undefined;
constructor(private notesService: NotesService) { }
ngOnInit(): void {
}
handleDeleteNote() {
this.notesService.noteElements = this.notesService.getBudgetNotes().filter(note => this.note?.id === this.id)
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BudgetNote } from '../model/BudgetNote';
import { NotesService } from '../note.service';
@Component({
selector: 'app-budget-note-detail',
templateUrl: './budget-note-detail.component.html',
styleUrls: ['./budget-note-detail.component.css']
})
export class BudgetNoteDetailComponent implements OnInit {
note: BudgetNote | undefined;
noteId = 0;
constructor(private route: ActivatedRoute, private noteService: NotesService) {
}
ngOnInit(): void {
this.noteId = this.route.snapshot.params['id'];
this.note = this.noteService.getNoteById(+this.route.snapshot.params['id'])
console.log(this.note)
}
onDeleteNote() {
this.noteService.noteElements = this.noteService.noteElements.filter(el => el.id = this.noteId);
}
}
<file_sep>export class BudgetNote {
id: number | undefined;
name: string | undefined;
type: BudgetNoteType | undefined;
amount = 0;
date: Date = new Date();
description: string| undefined;
}
export enum BudgetNoteType {
Expence = "EXPENCE",
Income = 'INCOME'
}
<file_sep>import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from "@angular/router";
import { Observable } from "rxjs";
import { NotesService } from "./note.service";
@Injectable()
export class NotesRouteService implements CanActivate {
constructor(private notesService: NotesService, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot) {
const noteExists = !!this.notesService.getNoteById(+route.params['id'])
if (!noteExists) {
this.router.navigate(['/404'])
}
return noteExists;
}
}
<file_sep>import { Injectable } from "@angular/core";
import { OnInit } from "@angular/core";
import { BudgetNote, BudgetNoteType } from "./model/BudgetNote";
@Injectable()
export class NotesService {
note1: BudgetNote | undefined;
note2: BudgetNote | undefined;
note3: BudgetNote | undefined;
noteElements = new Array<BudgetNote>();
constructor() {
}
getBudgetNotes() {
this.note1 = new BudgetNote();
this.note1.id = 1;
this.note1.name = '<NAME>';
this.note1.type = BudgetNoteType.Expence;
this.note1.amount = 150;
this.note1.date = new Date();
this.note1.description = 'remont boiler';
this.note2 = new BudgetNote();
this.note2.id = 2;
this.note2.name = 'Laminat spalnq';
this.note2.type = BudgetNoteType.Expence;
this.note2.amount = 350;
this.note2.date = new Date();
this.note2.description = 'laminat za spalnq';
this.note3 = new BudgetNote();
this.note3.id = 3;
this.note3.name = '<NAME>';
this.note3.type = BudgetNoteType.Income;
this.note3.amount = 550;
this.note3.date = new Date();
this.note3.description = 'avans do zaplat';
this.noteElements.push(this.note1);
this.noteElements.push(this.note2);
this.noteElements.push(this.note3);
return this.noteElements;
}
getNoteById(id: number) {
this.noteElements = this.getBudgetNotes();
console.log('------------------')
console.log(this.noteElements.find(n => n.id === id))
return this.noteElements.find(n => n.id === id);
}
getLastNoteIndex() {
return this.noteElements.length;
}
}
<file_sep>import { Routes } from "@angular/router";
import { BudgetBoardComponent } from "./budget-board/budget-board.component";
import { BudgetNoteDetailComponent } from "./budget-note-detail/budget-note-detail.component";
import { CreateNoteComponent } from "./create/create-note/create-note.component";
import { Error404Component } from "./error404/error404.component";
import { NotesRouteService } from "./notes-rooute.service";
export const routes: Routes = [
{path: 'notes', component: BudgetBoardComponent },
{path: 'notes/create', component: CreateNoteComponent, pathMatch: 'full'},
{path: 'note/:id', component: BudgetNoteDetailComponent, canActivate: [NotesRouteService]},
{ path: '404', component: Error404Component },
{path: '', component: BudgetBoardComponent, pathMatch: 'full'}
]
| c396832509d29b2e6c51f8d0bc24e86262620889 | [
"TypeScript",
"HTML"
] | 11 | HTML | MartinValchev/BudgetApp | ee60c27e82699c1bf3332a8bf5de5ee6d1bb5521 | 9fb15a33317f5e5537ac0ad56376aec1d51a8a44 |
refs/heads/master | <repo_name>SanchezHernandezChristian/prueba-practica<file_sep>/seeders/20210515081404-crear-empresa.js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
let listaEmpresas = [
{
nombre_legal: "<NAME>",
nombre_comercial: "<NAME>",
rfc: "PRO840423SG8",
telefono: "5515195000",
fecha_registro: new Date(),
},
{
nombre_legal: "PEPSICO INTERNACIONAL MÉXICO, S DE R.L DE C.V",
nombre_comercial: "Pepsi",
rfc: "PIM001026NF2",
telefono: "5515195012",
fecha_registro: new Date(),
},
];
await queryInterface.bulkInsert("empresas", listaEmpresas, {});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete("empresas", null, {});
},
};
<file_sep>/seeders/20210515081423-crear-usuario.js
"use strict";
const models = require("./../models/index");
const bcrypt = require("bcrypt");
module.exports = {
up: async (queryInterface, Sequelize) => {
let listaRoles = await models.Rol.findAll();
let listaEmpresas = await models.Empresa.findAll();
const salt = await bcrypt.genSaltSync(10, "a");
let contraseña = bcrypt.hashSync("1234", salt);
let listaUsuarios = [
{
nombre: "Christian",
apellido: "Sanchez",
correo: "<EMAIL>",
password: <PASSWORD>,
rolId: listaRoles[0].id,
empresaId: listaEmpresas[0].id,
},
{
nombre: "Monserrat",
apellido: "Villegas",
correo: "<EMAIL>",
password: <PASSWORD>,
rolId: listaRoles[1].id,
empresaId: listaEmpresas[0].id,
},
{
nombre: "Bruno",
apellido: "Sanchez",
correo: "<EMAIL>",
password: <PASSWORD>,
rolId: listaRoles[2].id,
empresaId: listaEmpresas[0].id,
},
{
nombre: "Johan",
apellido: "Hernandez",
correo: "<EMAIL>",
password: <PASSWORD>,
rolId: listaRoles[1].id,
empresaId: listaEmpresas[1].id,
},
{
nombre: "Jordy",
apellido: "Juarez",
correo: "<EMAIL>",
password: <PASSWORD>,
rolId: listaRoles[3].id,
empresaId: listaEmpresas[1].id,
},
];
await queryInterface.bulkInsert("usuarios", listaUsuarios, {});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete("usuarios", null, {});
},
};
<file_sep>/src/controllers/usuarioController.js
const models = require("../../models/index");
const router = require("express").Router();
router.get("/", async (req, res) => {
try {
const Usuarios = await models.Usuario.findAll();
return res.json(Usuarios);
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
router.post("/", async (req, res) => {
try {
console.log(req.body);
const Usuario = await models.Usuario.create(req.body);
res.json(Usuario);
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
router.put("/:UsuarioId", async (req, res) => {
try {
await models.Usuario.update(req.body, {
where: { id: req.params.UsuarioId },
});
res.json({ success: "Se ha modificado exitosamente" });
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
router.delete("/:UsuarioId", async (req, res) => {
try {
await models.Usuario.destroy({
where: {
id: req.params.UsuarioId,
},
});
res.json({ success: "Se ha eliminado exitosamente" });
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
module.exports = router;
<file_sep>/src/controllers/empresaController.js
const models = require("../../models/index");
const router = require("express").Router();
router.get("/", async (req, res) => {
try {
const empresas = await models.Empresa.findAll();
return res.json(empresas);
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
router.post("/", async (req, res) => {
try {
console.log(req.body);
const empresa = await models.Empresa.create(req.body);
res.json(empresa);
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
router.put("/:empresaId", async (req, res) => {
try {
await models.Empresa.update(req.body, {
where: { id: req.params.empresaId },
});
res.json({ success: "Se ha modificado exitosamente" });
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
router.delete("/:empresaId", async (req, res) => {
try {
await models.Empresa.destroy({
where: {
id: req.params.empresaId,
},
});
res.json({ success: "Se ha eliminado exitosamente" });
} catch (err) {
console.log(err);
return res.status(500).json({ error: "Algo salió mal" });
}
});
module.exports = router;
<file_sep>/src/controllers/api.js
const router = require("express").Router();
const apiEmpresa = require("./empresaController");
const apiUsuario = require("./usuarioController");
router.use("/empresas", apiEmpresa);
router.use("/usuarios", apiUsuario);
module.exports = router;
<file_sep>/Readme.txt
Instrucciones de uso
Pasos para iniciar la aplicacion:
* Clonar desde el repositorio https://github.com/SanchezHernandezChristian/prueba-practica.git
* Cambiar los accesos y direccion del manejador de base de datos en el archivo: Config/config.json (la base de datos seleccionada es mySQL)
* Teclear el comando: npm run iniciar
La aplicacion quedara iniciada con los datos iniciales creados.
Para ejecutar la aplicacion teclear: nodemon app.js O npm run dev
Para ejecutar las pruebas teclear: npm run test.
Rutas de acceso:
La url sera determinado por donde se accese a la aplicacion
CRUD Empresa:
Obtener empresas: get("URL/api/empresas");
Crear empresa: post("URL/api/empresas");
Datos para crear correctamente:
{
nombre_legal: "nombre",
nombre_comercial: "nombre",
rfc: "alfanumerico",
telefono: "numerico",
fecha_registro: new Date(),
},
Editar empresa: put("URL/api/empresas/:idempresa");
Datos para crear correctamente (puede ser uno o varios):
{
nombre_legal: "nombre",
nombre_comercial: "nombre",
rfc: "alfanumerico",
telefono: "numerico",
fecha_registro: new Date(),
},
Eliminar empresa: delete("URL/api/empresas/:idempresa");
CRUD Usuario:
Obtener Usuarios: get("URL/api/usuarios");
Crear usuario: post("URL/api/usuarios");
Datos para crear correctamente:
{
nombre: "nombre",
apellido: "apellido",
correo: "<EMAIL>",
password: "<PASSWORD>",
rolId: id de un rol ,
empresaId: id de una empresa,
},
Editar usuario: put("URL/api/usuarios/:idusuario");
Datos para crear correctamente (puede ser uno o varios):
{
nombre: "nombre",
apellido: "apellido",
correo: "<EMAIL>",
password: "<PASSWORD>",
rolId: id de un rol ,
empresaId: id de una empresa,
},
Eliminar usuario: delete("URL/api/usuarios/:idusuario");
Los datos de los roles quedaron en el orden inicial indicado:
admin
manager
accounting
employee
<file_sep>/app.js
const express = require("express");
const mysql = require("mysql2");
const { sequelize } = require("./models");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const apiRouter = require("./src/controllers/api");
app.use("/api", apiRouter);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is live at localhost:${PORT}`));
module.exports = app;
<file_sep>/models/empresa.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Empresa extends Model {
static associate({ Usuario }) {
this.hasMany(Usuario, {
foreignKey: "empresaId",
as: "usuarios",
onDelete: "cascade",
hooks: true,
});
}
toJSON() {
return { ...this.get() };
}
}
Empresa.init(
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
nombre_legal: {
type: DataTypes.STRING(300),
allowNull: false,
},
nombre_comercial: {
type: DataTypes.STRING(300),
},
rfc: {
type: DataTypes.STRING(12),
allowNull: false,
},
telefono: {
type: DataTypes.BIGINT(11),
allowNull: false,
},
fecha_registro: {
type: DataTypes.DATE,
allowNull: false,
},
},
{
sequelize,
tableName: "empresas",
modelName: "Empresa",
timestamps: false,
}
);
return Empresa;
};
<file_sep>/seeders/20210515081416-crear-rol.js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
let listaRoles = [
{
nombre_rol: "admin",
},
{
nombre_rol: "manager",
},
{
nombre_rol: "accounting",
},
{
nombre_rol: "employee",
},
];
await queryInterface.bulkInsert("roles", listaRoles, {});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete("roles", null, {});
},
};
<file_sep>/migrations/20210515040931-create_empresas_table.js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
queryInterface.createTable("Empresas", {
id: {
type: Sequelize.INTEGER(11),
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
nombre_legal: {
type: Sequelize.STRING(300),
allowNull: false,
},
nombre_comercial: {
type: Sequelize.STRING(300),
},
rfc: {
type: Sequelize.STRING(12),
allowNull: false,
},
telefono: {
type: Sequelize.BIGINT(11),
allowNull: false,
},
fecha_registro: {
type: Sequelize.DATE,
allowNull: false,
},
});
},
down: async (queryInterface, Sequelize) => {
return queryInterface.dropTable("Empresas");
},
};
<file_sep>/tests/usuarios.test.js
const supertest = require("supertest");
const app = require("../app");
const api = supertest(app);
test("Obtener usuarios", async () => {
const response = await api.get("/api/usuarios");
expect(response.body).toHaveLength(response.body.length);
});
test("Crear usuario", async () => {
const newusuario = {
nombre: "Rafael",
apellido: "Garcia",
correo: "<EMAIL>",
password: "<PASSWORD>",
rolId: 1,
empresaId: 2,
};
await api
.post("/api/usuarios")
.send(newusuario)
.expect(200)
.expect("Content-Type", /application\/json/);
const response = await api.get("/api/usuarios");
const contents = response.body.map((usuario) => usuario.nombre);
expect(contents).toContain(newusuario.nombre);
});
test("Modificar usuario", async () => {
const newusuario = {
apellido: "Hernandez",
};
var nombre = "Rafael";
const response1 = await api.get("/api/usuarios");
var id;
for (var i in response1.body) {
if (response1.body[i].nombre === nombre) {
id = response1.body[i].id;
}
}
await api
.put(`/api/usuarios/${id}`)
.send(newusuario)
.expect(200)
.expect("Content-Type", /application\/json/);
const response = await api.get("/api/usuarios");
const contents = response.body.map((usuario) => usuario.apellido);
expect(contents).toContain(newusuario.apellido);
});
test("Eliminar usuario", async () => {
var nombre = "Jordy";
const response1 = await api.get("/api/usuarios");
var id;
for (var i in response1.body) {
if (response1.body[i].nombre === nombre) {
id = response1.body[i].id;
}
}
await api
.delete(`/api/usuarios/${id}`)
.expect(200)
.expect("Content-Type", /application\/json/);
});
| 06bcd018f513c5208c7f6678399b217cda2fdf64 | [
"JavaScript",
"Text"
] | 11 | JavaScript | SanchezHernandezChristian/prueba-practica | 8fc59d2eb8e067aa20c8845e2b9a4f609942e5c8 | 49b728cb6478986ade3a76d3cad8efe72eb07fb5 |
refs/heads/master | <file_sep>package com.ironmansapps.currencyconvertor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void convert(View view){
EditText amount = (EditText) findViewById(R.id.dollar);
Double dollarAmt = Double.parseDouble(amount.getText().toString());
Double Rupee = dollarAmt * 50;
Toast.makeText(MainActivity.this,Rupee.toString(),Toast.LENGTH_LONG).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| e35cffac0e5b716e8459d8bc5bd70d8a19ae3e0f | [
"Java"
] | 1 | Java | Tirth21896/AndroidWork | 8dabd969b25c8566b1428ca4507de66a543dad7e | b711335968a7cfb181ef4c8865eb483c961fca9c |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PasswordSaver.Forms
{
public partial class EditApp : Form
{
Repositories.PasswordLookupRepo pr = new Repositories.PasswordLookupRepo();
Repositories.AddNewAppRepo ar = new Repositories.AddNewAppRepo();
public EditApp()
{
InitializeComponent();
}
private void searchAppToEditBtn_Click(object sender, EventArgs e)
{
var info = pr.GetAppInfo(appToEditTextbox.Text);
if (info != null)
{
curUsernameLabel.Text = info.Username;
curPasswordLabel.Text = info.Password;
}
}
private void submitChangesBtn_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Please verify that the details are correct:\nUsername: " + newUsernameTextbox.Text + "\nPassword: " + newPasswordTextbox.Text, "Verification", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
ar.EditApp(appToEditTextbox.Text, newUsernameTextbox.Text, newPasswordTextbox.Text);
MessageBox.Show("Details updated submitted.");
}
}
}
}
<file_sep>namespace PasswordSaver
{
}
namespace PasswordSaver
{
public partial class Password_SaverDataSet
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace PasswordSaver.Repositories
{
class PasswordLookupRepo
{
DataClasses1DataContext db = new DataClasses1DataContext();
public App GetAppInfo(string name)
{
var info = (from i in db.Apps
where i.AppName.ToUpper() == name.ToUpper()
select i).FirstOrDefault();
return info;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace PasswordSaver.Repositories
{
class AddNewAppRepo
{
DataClasses1DataContext db = new DataClasses1DataContext();
public bool checkIfUnique(string name)
{
bool isUnique = true;
App app = (from a in db.Apps
where a.AppName.ToLower() == name.ToLower()
select a).Single();
if(app != null)
{
isUnique = false;
}
return isUnique;
}
public void AddNewApp(App newApp)
{
db.Apps.InsertOnSubmit(newApp);
db.SubmitChanges();
}
public void EditApp(string name, string username, string password)
{
App app = (from a in db.Apps
where a.AppName.ToLower() == name.ToLower()
select a).Single();
if(username != null)
{
app.Username = username;
}
if(password != null)
{
app.Password = <PASSWORD>;
}
db.SubmitChanges();
}
public void DeleteApp(string name)
{
App app = (from a in db.Apps
where a.AppName.ToLower() == name.ToLower()
select a).Single();
db.Apps.DeleteOnSubmit(app);
db.SubmitChanges();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PasswordSaver
{
public partial class AddNewApp : Form
{
Repositories.AddNewAppRepo ar = new Repositories.AddNewAppRepo();
public AddNewApp()
{
InitializeComponent();
}
private void submitNewAppButton_Click(object sender, EventArgs e)
{
if(appNameTextbox.Text.Length < 1)
{
MessageBox.Show("Please enter an app name.");
}
if(ar.checkIfUnique(appNameTextbox.Text) == false)
{
MessageBox.Show("This app already exists");
}
else if (usernameTextbox.Text.Length < 1 || passwordTextbox.Text.Length < 1)
{
DialogResult dr = MessageBox.Show("Do you want to leave the username/password field blank?", "Verficiation", MessageBoxButtons.YesNo);
if(dr == DialogResult.Yes)
{
submitDetails();
}
}
else
{
submitDetails();
}
/*DialogResult result = MessageBox.Show("Please verify that the details are correct:\nApp Name: " + appNameTextbox.Text + "\nUsername: " + usernameTextbox.Text + "\nPassword: " + <PASSWORD>Textbox.Text, "Verification", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
App newApp = new App();
newApp.AppName = appNameTextbox.Text;
newApp.Username = usernameTextbox.Text;
newApp.Password = <PASSWORD>;
ar.AddNewApp(newApp);
MessageBox.Show("Details successfully submitted.");
}*/
}
private void submitDetails()
{
DialogResult result = MessageBox.Show("Please verify that the details are correct:\nApp Name: " + appNameTextbox.Text + "\nUsername: " + usernameTextbox.Text + "\nPassword: " + <PASSWORD>.Text, "Verification", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
App newApp = new App();
newApp.AppName = appNameTextbox.Text;
newApp.Username = usernameTextbox.Text;
newApp.Password = <PASSWORD>;
ar.AddNewApp(newApp);
MessageBox.Show("Details successfully submitted.");
}
}
private void goToLookupButton_Click(object sender, EventArgs e)
{
PasswordLookup form = new PasswordLookup();
this.Hide();
form.Show();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PasswordSaver
{
public partial class PasswordLookup : Form
{
Repositories.PasswordLookupRepo pr = new Repositories.PasswordLookupRepo();
Repositories.AddNewAppRepo ar = new Repositories.AddNewAppRepo();
public PasswordLookup()
{
InitializeComponent();
editAppPanel.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
var info = pr.GetAppInfo(searchTextbox.Text);
if (info != null)
{
AppNameLabel.Text = info.AppName;
uName.Text = info.Username;
pWord.Text = info.Password;
}
}
private void goToAddNewAppButton_Click(object sender, EventArgs e)
{
AddNewApp newApp = new AddNewApp();
this.Hide();
newApp.Show();
}
private void editAppButton_Click(object sender, EventArgs e)
{
if(searchTextbox.Text.Length > 0)
{
editAppPanel.Show();
var info = pr.GetAppInfo(searchTextbox.Text);
newUsernameTxtbox.Text = info.Username;
newPasswordTxtbox.Text = info.Password;
}
else
{
MessageBox.Show("Please enter an app to edit");
}
}
private void exitEditPanel_Click(object sender, EventArgs e)
{
newUsernameTxtbox.Clear();
newPasswordTxtbox.Clear();
editAppPanel.Hide();
}
private void submitChangesButton_Click(object sender, EventArgs e)
{
if (newUsernameTxtbox.Text.Length > 0 && newPasswordTxtbox.Text.Length > 0)
{
DialogResult result = MessageBox.Show("Please verify that the details are correct:\nUsername: " + newUsernameTxtbox.Text + "\nPassword: " + newPasswordTxtbox.Text, "Verification", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
ar.EditApp(searchTextbox.Text, newUsernameTxtbox.Text, newPasswordTxtbox.Text);
MessageBox.Show("Details updated submitted.");
}
newUsernameTxtbox.Clear();
newPasswordTxtbox.Clear();
editAppPanel.Hide();
}
else
{
MessageBox.Show("Please enter a username/password");
}
}
private void deleteAppButton_Click(object sender, EventArgs e)
{
if (searchTextbox.Text.Length > 0)
{
DialogResult result = MessageBox.Show("Are you sure you want to delete " + searchTextbox.Text + "?", "Verification", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
ar.DeleteApp(searchTextbox.Text);
MessageBox.Show("App deleted successfully");
}
}
else
{
MessageBox.Show("Please enter an app to delete");
}
}
}
} | 9dcd2baf617ab51067c745f9210816fb55008d54 | [
"C#"
] | 6 | C# | ABrown94/PasswordSaver | 0bd737a949e647755ff04b00fb1712d876a7b71c | a9086dff75f97c7a8e190c3d7bf9dbd09c7320c9 |
refs/heads/master | <file_sep>import networkx as nx
from math import atan2, degrees
from threading import Thread
from time import sleep
#from Car import Car
class Network:
def __init__(self):
self.matrix = nx.MultiDiGraph()
Thread(target=self.dynamic_roads).start()
def dynamic_roads(self):
while 1:
sleep(1)
our_edges = self.matrix.edges()
various_our_edges = set()
for edges in our_edges:
various_our_edges.add(edges)
#for i in various_our_edges:
# for j in self.matrix[i[0]][i[1]]:
# print(self.matrix[i[0]][i[1]][j]['weight'])
#print('###############################################################')
for edges in various_our_edges:
self.update_weigth(edges)
#for i in various_our_edges:
# for j in self.matrix[i[0]][i[1]]:
# print(self.matrix[i[0]][i[1]][j]['weight'])
#print('###############################################################')
def update_weigth(self, edge):
for road in self.matrix[edge[0]][edge[1]]:
length = len(self.matrix[edge[0]][edge[1]][road]['on_road'])
numbers_cars = 0
place_car_min = 0
velocity_min = 1000
for i in range(length):
if self.matrix[edge[0]][edge[1]][road]['on_road'][i] != 0:
numbers_cars += 1
if self.matrix[edge[0]][edge[1]][road]['on_road'][i].velocity < velocity_min:
velocity_min = self.matrix[edge[0]][edge[1]][road]['on_road'][i].velocity
place_car_min = i
if numbers_cars != 0:
self.matrix[edge[0]][edge[1]][road]['weight'] = self.matrix[edge[0]][edge[1]][road]['weight_const'] * (1 + 30 * numbers_cars / length)
def add_node(self, name):
self.matrix.add_node(name)
def add_edge(self, name1, name2, w, list_points):
length = len(list_points)
array_angle_s = []
for i in range(8, 30, 2):
array_angle_s.append(degrees(atan2(-list_points[i + 2][1] + list_points[i][1], list_points[i + 2][0] - list_points[i][0])))
array_angle_s.sort()
first_angle = 0
len_s = len(array_angle_s)
for i in range(2, len_s - 2):
first_angle += array_angle_s[i]
first_angle /= len_s - 4
array_angle_f = []
for i in range(2, 30, 2):
array_angle_f.append(degrees(atan2(list_points[length - i][1] - list_points[length - i - 2][1], -list_points[length - i][0] + list_points[length - i - 2][0])))
array_angle_f.sort()
second_angle = 0
len_f = len(array_angle_f)
for i in range(2, len_f - 2):
second_angle += array_angle_f[i]
second_angle /= len_f - 4
#print(first_angle, second_angle)
self.matrix.add_edge(name1, name2, weight=w, weight_const=w, dots=list_points, on_road=[0] * length, start_angle=first_angle, finish_angle=second_angle)
def remove_node(self, name):
self.matrix.remove_node(name)
def remove_edge(self, name1, name2):
self.matrix.remove_edge(name1, name2)
<file_sep>from PyQt5.QtCore import QPoint
from PyQt5.QtGui import QPolygon, QPen
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtCore import Qt
import functions
class Road:
def __init__(self, beginningVertex, net, n, isOneSided):
self.vertex1 = beginningVertex
self.ready = False
self.net = net
self.borders = []
self.trajectories = []
self.n = n
self.isOneSided = isOneSided
def found(self, points, endingVertex):
if self.ready == False:
self.vertex2 = endingVertex
borderlist = []
trajlist = []
if self.isOneSided:
if self.n % 2 == 0:
pointsList = functions.multiplecurves(points, self.n, 10)
borderlist.append(LaneBorder(points))
for i in range(0, len(pointsList) - 2, 2):
if i % 4 == 0:
pointsList[i].insert(0, self.vertex1)
pointsList[i].insert(len(pointsList[i + 1]), self.vertex2)
pointsList[i + 1].insert(0, self.vertex1)
pointsList[i + 1].insert(len(pointsList[i + 1]), self.vertex2)
trajlist.append(Trajectory(pointsList[i], True))
trajlist.append(Trajectory(pointsList[i + 1], True))
else:
borderlist.append(LaneBorder(pointsList[i]))
borderlist.append(LaneBorder(pointsList[i + 1]))
borderlist.append(SideBorder(pointsList[-2]))
borderlist.append(SideBorder(pointsList[-1]))
else:
pointsList = functions.multiplecurves(points, self.n, 10)
trajlist.append(Trajectory(points, True))
for i in range(0, len(pointsList) - 2, 2):
if i % 4 == 0:
borderlist.append(LaneBorder(pointsList[i]))
borderlist.append(LaneBorder(pointsList[i + 1]))
else:
pointsList[i].insert(0, self.vertex1)
pointsList[i].insert(len(pointsList[i + 1]), self.vertex2)
pointsList[i + 1].insert(0, self.vertex1)
pointsList[i + 1].insert(len(pointsList[i + 1]), self.vertex2)
trajlist.append(Trajectory(pointsList[i], True))
trajlist.append(Trajectory(pointsList[i + 1], True))
borderlist.append(SideBorder(pointsList[-2]))
borderlist.append(SideBorder(pointsList[-1]))
else:
borderlist.append(DoubleSolid(points))
pointsList = functions.multiplecurves(points, 2*self.n, 10)
#for sublist in pointsList:
# sublist.insert(0, self.vertex1)
# sublist.insert(len(sublist), self.vertex2)
for i in range(0, len(pointsList) - 2, 2):
if i % 4 == 0:
pointsList[i].insert(0, self.vertex1)
pointsList[i].insert(len(pointsList[i]), self.vertex2)
pointsList[i+1].insert(0, self.vertex1)
pointsList[i+1].insert(len(pointsList[i+1]), self.vertex2)
trajlist.append(Trajectory(pointsList[i], False))
trajlist.append(Trajectory(pointsList[i + 1], True))
else:
borderlist.append(LaneBorder(pointsList[i]))
borderlist.append(LaneBorder(pointsList[i + 1]))
borderlist.append(SideBorder(pointsList[-2]))
borderlist.append(SideBorder(pointsList[-1]))
length = len(pointsList[-1])
self.finish(length, borderlist, trajlist)
def finish(self, length, borderslist, trajlist):
if self.ready == False:
self.length = length
self.borders = borderslist
trajlist.reverse()
self.trajectories = trajlist
for trajectory in self.trajectories:
if trajectory.isStraight:
self.net.add_edge(self.vertex1.name, self.vertex2.name, self.length, trajectory.extract())
else:
self.net.add_edge(self.vertex2.name, self.vertex1.name, self.length, trajectory.extract())
self.ready = True
def draw(self, drawer, painter):
for border in self.borders:
border.draw(drawer, painter)
class RoadElement:
def __init__(self, points):
self.points = points
class Border(RoadElement):
def draw(self, drawer, painter):
pass
def polygonize(self, points):
qpoints = []
for point in points:
qpoints.append(point.myQPoint())
return QPolygon(qpoints)
class DoubleSolid(Border):
def __init__(self, points):
super().__init__(points)
list = functions.multiplecurves(points, 1, 2)
self.p1 = self.polygonize(list[0])
self.p2 = self.polygonize(list[1])
def draw(self, drawer, painter):
painter.begin(drawer)
pen = QPen(Qt.black, 2, Qt.SolidLine)
painter.setPen(pen)
painter.drawPolyline(self.p1)
painter.drawPolyline(self.p2)
painter.end()
class LaneBorder(Border):
def __init__(self, points):
super().__init__(points)
def draw(self, drawer, painter):
painter.begin(drawer)
pen = QPen(Qt.black, 2, Qt.DashLine)
painter.setPen(pen)
painter.drawPolyline(self.polygonize(self.points))
painter.end()
class SideBorder(Border):
def __init__(self, points):
super().__init__(points)
def draw(self, drawer, painter):
painter.begin(drawer)
pen = QPen(Qt.black, 3, Qt.SolidLine)
painter.setPen(pen)
painter.drawPolyline(self.polygonize(self.points))
painter.end()
class Trajectory(RoadElement):
def __init__(self, points, isStraight):
super().__init__(points)
self.isStraight = isStraight
def extract(self):
points = []
if self.isStraight:
for point in self.points:
points.append((point.x(), point.y()))
else:
p = self.points.copy()
p.reverse()
for point in p:
points.append((point.x(), point.y()))
return points<file_sep>import networkx
import matplotlib.pyplot as plt
G=networkx.Graph()
e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2)]
G.add_weighted_edges_from(e)
print(G.nodes())
print(networkx.dijkstra_path(G,'a','d'))
networkx.draw(G)
plt.show()
Q=networkx.cubical_graph()
lollipop=networkx.lollipop_graph(10,20)
networkx.draw_circular(Q)
plt.show()
networkx.draw_spectral(lollipop)
plt.show()
networkx.draw(Q) # тип по умолчанию spring_layout
networkx.draw(Q,pos=networkx.spectral_layout(Q), nodecolor='r',edge_color='b')
plt.show()
S = networkx.path_graph(4)
cities = {0: "Toronto", 1: "London", 2: "Berlin", 3: "New York"}
H = networkx.relabel_nodes(S, cities)
print("Nodes of graph: ")
print(H.nodes())
print("Edges of graph: ")
print(H.edges())
networkx.draw(H)
plt.show()<file_sep>
class Tracker:
i = 1
def __init__(self, car):
self.pos = None
self.car = car
self.name = 'car' + str(Tracker.i)
Tracker.i = Tracker.i + 1
self.car.drawer.signal.addCarItem.emit(self.name, self.car.velocity, self.car.finish_vertex)
def setPos(self, point):
self.pos = point<file_sep>import sys, math, threading
from Matrix import Network
from Points import Point, Vertex
from Road import Road
from Chaos import Chaos
from Stream import Stream
from Car import Car
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Communicate(QObject):
switch = pyqtSignal()
addCarItem = pyqtSignal(str, int, str)
newvelocity = pyqtSignal(int, str)
removeCar = pyqtSignal(str)
class Controller:
def __init__(self, drawer):
self.drawer = drawer
self.i = 1
self.setControllerSchema()
self.setDrawerSchema(self.schema)
def setControllerSchema(self):
self.schema = (Drawer.pressMethods[self.i], Drawer.moveMethods[self.i], Drawer.drawMethods[self.i], Drawer.carMethods[self.i])
def setDrawerSchema(self, schema):
self.drawer.customMousePressEvent = schema[0]
self.drawer.customMouseMoveEvent = schema[1]
self.drawer.drawAdditional = schema[2]
self.drawer.move = schema[3]
def switchBehavior(self):
if self.i == 0:
self.i = 1
elif self.i == 1:
self.i = 0
self.setControllerSchema()
self.setDrawerSchema(self.schema)
def switchByButton(self):
if self.i == 1:
self.i = 2
elif self.i == 2:
self.i = 1
self.setControllerSchema()
self.setDrawerSchema(self.schema)
def switchBehaviorToValue(self, i):
self.i = i
self.setControllerSchema()
self.setDrawerSchema(self.schema)
def switchBehaviorToDrawing(self):
self.i = 1
self.setControllerSchema()
self.setDrawerSchema(self.schema)
def switchBehaviorToMovement(self):
self.i = 2
self.setControllerSchema()
self.setDrawerSchema(self.schema)
def switchBehaviourToSingleton(self):
self.i = 3
self.setControllerSchema()
self.setDrawerSchema(self.schema)
def setOneSided(self):
self.drawer.isOneSided = True
def setTwoSided(self):
self.drawer.isOneSided = False
def changen(self, str):
i = int(str)
self.drawer.n = i
def deleteAll(self):
self.drawer.carList = []
self.drawer.vertices = []
self.drawer.roads = []
self.drawer.net = Network()
class Drawer(QWidget):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.controller = Controller(self)
self.signal = Communicate()
self.signal.switch.connect(self.controller.switchBehavior)
self.signal.addCarItem.connect(self.parent.parent.CarList.addItem)
self.signal.newvelocity.connect(self.parent.parent.CarList.setNewVelocity)
self.signal.removeCar.connect(self.parent.parent.CarList.removeItem)
self.initUI()
self.setMouseTracking(True)
def initUI(self):
self.setGeometry(200, 200, 1000, 500)
self.setWindowTitle('Drawer')
self.vertices = []
self.roads = []
self.pointList = []
self.carList = []
self.show()
self.count = 0
self.pos = None
self.hasBegun = False
self.timer = QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(20)
self.net = Network()
self.n = 1
self.isOneSided = False
def loadFromFile(self, verticeslist, roadlists):
pass
self.vertices = []
self.roads = []
for vcortege in verticeslist:
self.vertices.append(Vertex.newVertex(vcortege[0], vcortege[1], self.net))
i = 0
for cortege in roadlists:
n = cortege[0]
bool = cortege[1]
rlist = cortege[2]
for vertex in self.vertices:
if vertex.x() == rlist[0][0] and vertex.y() == rlist[0][1]:
begv = vertex
break
road = Road(begv, self.net, n, bool)
for vertex in self.vertices:
if vertex.x() == rlist[-1][0] and vertex.y() == rlist[-1][1]:
endv = vertex
break
points = []
for cortege in rlist:
points.append(Point(cortege[0], cortege[1]))
road.found(points, endv)
self.roads.append(road)
def mousePressEvent(self, event):
self.customMousePressEvent(self, event)
def mouseMoveEvent(self, event):
self.customMouseMoveEvent(self, event)
def drawCurve(self, qp):
pen = QPen(Qt.black, 3, Qt.DashLine)
qp.setPen(pen)
points = []
for point in self.pointList:
points.append(point.myQPoint())
polygon = QPolygon(points)
qp.drawPolyline(polygon)
def paintEvent(self, event):
q1 = QPainter()
q2 = QPainter()
for road in self.roads:
if road.ready:
road.draw(self, q1)
q3 = QPainter()
q4 = QPainter()
for vertex in self.vertices:
q2.begin(self)
brush = QBrush(Qt.white, Qt.SolidPattern)
pen = QPen(Qt.black, 3, Qt.DashLine)
q2.setBrush(brush)
q2.setPen(pen)
q2.drawEllipse(vertex.myQPoint(), 50, 50)
q2.setFont(QFont('Decorative', 10))
q2.drawText(vertex.x() + 20, vertex.y() + 20, 30, 20, 0, vertex.name)
q2.end()
q2.begin(self)
brush = QBrush(Qt.black, Qt.SolidPattern)
q2.setBrush(brush)
q2.drawEllipse(vertex.myQPoint(), 25, 25)
for vertex in self.vertices:
if vertex.isBeginning > 0:
q3.begin(self)
pen = QPen(Qt.blue, 2, Qt.DashLine)
q3.setPen(pen)
q3.drawEllipse(vertex.myQPoint(), 51 , 51)
if vertex.isEnd > 0:
q3.begin(self)
pen = QPen(Qt.red, 2, Qt.DashLine)
q3.setPen(pen)
q3.drawEllipse(vertex.myQPoint(), 52, 52)
for tracker in self.carList:
if tracker.pos:
q4.begin(self)
brush = QBrush(Qt.SolidPattern)
q4.setBrush(brush)
q4.drawEllipse(tracker.pos.myQPoint(), 5, 5)
q1.end()
q2.end()
q3.end()
q4.end()
self.drawAdditional(self)
def closestvertex(self, point):
distlist = []
for vertex in self.vertices:
distlist.append(Point.dist(point, vertex))
if distlist:
index = distlist.index(min(distlist))
return self.vertices[index]
else:
return None
def mindistance(self, point):
distlist = []
for vertex in self.vertices:
distlist.append(Point.dist(point, vertex))
if distlist:
return min(distlist)
else:
return None
def moveAndDraw(self, event):
m = 1
point = Point(event.x(), event.y())
distance_from_previous_point = Point.dist(point, self.basepoint)
self.pos = event.pos()
if distance_from_previous_point >= m:
if distance_from_previous_point >= 2*m:
cos = (point.x() - self.basepoint.x()) / distance_from_previous_point
sin = (point.y() - self.basepoint.y()) / distance_from_previous_point
point = Point(self.basepoint.x() + round(cos), self.basepoint.y() + round(sin))
for i in range(m, math.ceil(distance_from_previous_point), m):
self.pointList.append(point)
point = Point(self.basepoint.x() + round(cos*i), self.basepoint.y() + round(sin*i))
self.pointList.append(point)
self.basepoint = point
if self.mindistance(point) <= 20 and len(self.pointList) >= 50:
v = self.closestvertex(point)
self.pointList.append(Point(v.x(), v.y()))
self.finishTheRoad(v)
def previous(self, point):
i = self.pointList.index(point)
if i != 0:
return self.pointList[i - 1]
else:
return Point(-1, -1)
def finishTheRoad(self, v):
for point in self.pointList:
d = Point.dist(self.previous(point), point)
if d == 0.0:
self.pointList.remove(point)
points = self.pointList.copy()
road = self.newroad
road.found(points, v)
self.roads.append(road)
self.pointList.clear()
self.signal.switch.emit()
self.pos = None
def noChanges(self, event):
QWidget.mouseMoveEvent(self, event)
def waitForFinish(self, event):
if event.button() == Qt.LeftButton:
point = Point(event.x(), event.y())
if self.mindistance(point) > 100:
self.pointList.append(point)
v = Vertex.newVertex(event.x(), event.y(), self.net)
self.vertices.append(v)
self.finishTheRoad(v)
def makeVertexStartRoad(self, event):
if event.button() == Qt.RightButton:
point = Point(event.x(), event.y())
if not self.vertices or self.mindistance(point) > 50:
self.vertices.append(Vertex.newVertex(event.x(), event.y(), self.net))
point = Point(event.x(), event.y())
if event.button() == Qt.LeftButton and self.vertices and self.mindistance(point) <= 20:
v = self.closestvertex(point)
self.newroad = Road(v, self.net, self.n, self.isOneSided)
self.basepoint = Point(v.x(), v.y())
self.pointList.append(self.basepoint)
self.signal.switch.emit()
def mouseTracePainter(self):
q1 = QPainter()
q1.begin(self)
self.drawCurve(q1)
if self.pos:
q2 = QPainter()
q2.begin(self)
pen = QPen(Qt.black, 3, Qt.DashLine)
q2.setPen(pen)
q2.drawLine(self.pos.x(), self.pos.y(), self.pointList[-1].x(), self.pointList[-1].y())
q2.end()
self.borderPaint()
def allocate(self, event):
point = Point(event.x(), event.y())
if event.button() == Qt.LeftButton and self.vertices and self.mindistance(point) <= 20:
if self.hasBegun == False:
self.v1 = self.closestvertex(point)
self.v1.setBeginning()
self.hasBegun = True
else:
self.v2 = self.closestvertex(point)
self.v2.setEnd()
self.count += 1
if self.count == 2:
self.move(self, self.v1, self.v2)
self.count = 0
self.hasBegun = False
def startStream(self, v1, v2):
s = Stream(self, v1, v2, 10)
def startSingleton(self, v1, v2):
def behavior(drawer, v1, v2):
car = Car(100, drawer)
car.moveAtoB(drawer.net, v1, v2)
threading.Thread(target = behavior, args = (self, v1, v2,)).start()
def chaos(self):
self.controller.switchBehaviorToValue(2)
c = Chaos(self)
def nothingToAdd(self):
self.borderPaint()
def borderPaint(self):
q = QPainter()
for vertex in self.vertices:
q.begin(self)
brush = QBrush(Qt.BDiagPattern)
pen = QPen(Qt.black, 1, Qt.DashLine)
if self.pos and Point.dist(Point(self.pos.x(), self.pos.y()), vertex) <= 100:
q.setBrush(brush)
q.setPen(pen)
q.drawEllipse(vertex.myQPoint(), 100, 100)
q.end()
def noBorders(self):
return
def straightPath(self):
pass
pressMethods = (waitForFinish, makeVertexStartRoad, allocate, allocate)
moveMethods = (moveAndDraw, noChanges, noChanges, noChanges)
drawMethods = (mouseTracePainter, nothingToAdd, noBorders, noBorders)
carMethods = (noChanges, noChanges, startStream, startSingleton)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Drawer(None)
sys.exit(app.exec_())
<file_sep>import time
import networkx as nx
from Tracker import Tracker
from Points import Point, Vertex
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject, Qt, QPoint
import math
inf = 10 ** 6
waiting = 300
class Car:
def __init__(self, v, drawer):
self.velocity = v
self.drawer = drawer
self.current_velocity = 2
def way(self, net, whence):
try:
result = (nx.dijkstra_path(net.matrix, whence, self.finish_vertex))[1]
except nx.exception.NetworkXNoPath:
result = None
return result
def moveAtoB(self, net, start, finish):
self.current_vertex = start.name
self.start_vertex = start.name
self.finish_vertex = finish.name
self.tracker = Tracker(self)
self.report_velocity()
self.drawer.carList.append(self.tracker)
self.movement(net)
self.drawer.carList.remove(self.tracker)
self.removeCar()
start.setUnallocated()
finish.setUnallocated()
def report_velocity(self):
self.drawer.signal.newvelocity.emit(self.current_velocity, self.tracker.name)
def removeCar(self):
self.drawer.signal.removeCar.emit(self.tracker.name)
def movement(self, net):
if self.current_vertex == self.finish_vertex: ## if arrives
return
if self.current_vertex == self.start_vertex: ## if starts, where
self.where = self.way(net, self.start_vertex)
if self.where == None:
return
best_len = inf
self.best_road = 0
for road in net.matrix[self.current_vertex][self.where].keys():
if net.matrix[self.current_vertex][self.where][road]['weight'] < best_len:
best_len = net.matrix[self.current_vertex][self.where][road]['weight']
self.best_road = road
vmin = 2
self.future_best_road = 0
self.future_where = self.where
distance = len(net.matrix[self.current_vertex][self.where][self.best_road]['dots']) ## traffic
for i in range(distance):
if self.where != self.finish_vertex and distance == i + 30: ## where
self.future_where = self.way(net, self.where)
best_len = inf
self.future_best_road = 0
for road in net.matrix[self.where][self.future_where].keys():
if net.matrix[self.where][self.future_where][road]['weight'] < best_len:
best_len = net.matrix[self.where][self.future_where][road]['weight']
self.future_best_road = road
if distance < 200: ## to determine velocity
accel = distance / 2
else:
accel = 100
if i <= accel:
self.current_velocity = math.sqrt(vmin ** 2 + i/accel * (self.velocity ** 2 - vmin ** 2))
self.report_velocity()
if distance <= i + accel - 1:
self.current_velocity = math.sqrt(self.velocity ** 2 - (accel - distance + i + 1)/accel * (self.velocity ** 2 - vmin ** 2))
self.report_velocity()
if i != 0:
time.sleep(1/self.current_velocity)
no_wait = 0 ## when may go
if distance > i + 10:
while net.matrix[self.current_vertex][self.where][self.best_road]['on_road'][i + 10] != 0:
time.sleep(1/waiting)
else:
while no_wait == 0 and self.where != self.finish_vertex:
no_wait = 1
for vertex_predecessors in net.matrix.predecessors(self.where):
for road in net.matrix[vertex_predecessors][self.where].keys():
if vertex_predecessors != self.current_vertex or road != self.best_road: ## vertex_predecessors
first_angle = net.matrix[self.where][self.future_where][self.future_best_road]['start_angle'] ## edge
second_angle = net.matrix[self.current_vertex][self.where][self.best_road]['finish_angle'] ## edge
other_angle = net.matrix[vertex_predecessors][self.where][road]['finish_angle']
len_road = len(net.matrix[vertex_predecessors][self.where][road]['on_road'])
if second_angle < first_angle and second_angle < other_angle and other_angle < first_angle\
or second_angle < other_angle and second_angle > first_angle\
or second_angle > first_angle and second_angle > other_angle and first_angle > other_angle:
for j in range(len_road - 30, len_road):
if net.matrix[vertex_predecessors][self.where][road]['on_road'][j] != 0:
if net.matrix[vertex_predecessors][self.where][road]['on_road'][j].future_best_road == self.future_best_road:
no_wait *= 0
for close in nx.neighbors(net.matrix, self.where): ##do not merge
for road in net.matrix[self.where][close].keys():
num = 0
for point in net.matrix[self.where][close][road]['on_road']:
if num > 10 - distance + 1 + i:
break
num += 1
if point == 1:
no_wait *= 0
if no_wait == 0:
time.sleep(1/waiting)
#if i < 35 or i > 400:
# print(i, self.velocity)
#print(self.current_velocity)
net.matrix[self.current_vertex][self.where][self.best_road]['on_road'][i] = self ## car on road
if i > 0:
net.matrix[self.current_vertex][self.where][self.best_road]['on_road'][i - 1] = 0
self.current_point = net.matrix[self.current_vertex][self.where][self.best_road]['dots'][i]
point = Point(self.current_point[0], self.current_point[1])
self.tracker.setPos(point)
net.matrix[self.current_vertex][self.where][self.best_road]['on_road'][distance - 1] = 0
self.current_vertex = self.where
self.where = self.future_where
self.best_road = self.future_best_road
self.movement(net)
<file_sep># Road-organization
test<file_sep>import random, threading, time
from Car import Car
from PyQt5.QtWidgets import QApplication
class Chaos :
def __init__(self,drawer):
self.drawer = drawer
self.net = self.drawer.net
self.enum = self.net.matrix.number_of_edges()
self.probabilities = {}
counter = 1
for name in self.net.matrix.nodes():
d = self.net.matrix.degree(name)
self.probabilities.update([[name,[counter,counter+d-1]]])
counter += d
self.beginChaos()
def beginChaos(self):
def behaviour(net,startVN,drawer, i):
time.sleep(i/10)
nodes = self.net.matrix.nodes().copy()
nodes.remove(startVN)
endVN = random.choice(self.net.matrix.nodes())
velocity = random.randint(5,15)*20
for vert in drawer.vertices :
if vert.name == startVN:
startV = vert
break
for vert in drawer.vertices :
if vert.name == endVN:
endV = vert
break
car = Car(velocity,drawer)
car.moveAtoB(drawer.net,startV,endV)
for i in range(60):
a = random.randint(1, 2 * self.enum)
for key in self.probabilities.keys():
if self.probabilities[key][0] <= a and self.probabilities[key][1] >= a:
startVN = key
threading.Thread(target=behaviour, args=(self.net,startVN,self.drawer, i)).start()
<file_sep>from PyQt5.QtCore import QPoint
from PyQt5.QtGui import QPolygon, QPen
class Point:
def __init__(self, abs, ord):
self.abs = abs
self.ord = ord
def x(self):
return(self.abs)
def y(self):
return(self.ord)
def myQPoint(self):
return QPoint(self.abs, self.ord)
@staticmethod
def dist(point1, point2):
return ((point2.x() - point1.x()) ** 2 + (point2.y() - point1.y()) ** 2) ** 0.5
class Vertex(Point):
def __init__(self, abs, ord, net, name):
super().__init__(abs, ord)
self.name = name
self.isBeginning = False
self.isEnd = False
self.addition(net)
def addition(self, net):
net.add_node(self.name)
def setBeginning(self):
self.isBeginning = True
def setEnd(self):
self.isEnd = True
def setUnallocated(self):
self.isBeginning = False
self.isEnd = False
def setName(self, str):
self.name = str
def getName(self):
return self.name
c = ord('A')
i = c
@staticmethod
def newVertex(x, y, net):
if Vertex.i <= Vertex.c + 51:
k = ((Vertex.i - Vertex.c) % 2) + 1
name = chr(Vertex.c + (Vertex.i - Vertex.c) // 2 ) + str(k)
Vertex.i = Vertex.i + 1
else:
name = ''
v = Vertex(x, y, net, name)
return v
def extract(self):
return (self.x(), self.y())
<file_sep>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from drawer import Drawer
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.CarList = CarListWidget(self)
self.widget = MyWidget(self)
self.setCentralWidget(self.widget)
col = QColor(255, 255, 255)
mydocwidget2 = QDockWidget('menu', self)
mydocwidget2.setWidget(self.CarList)
self.addDockWidget(Qt.RightDockWidgetArea, mydocwidget2)
exitAction = QAction( QIcon('../resources/exit2.png'),'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.close)
previousAction = QAction(QIcon('../resources/left.png'), 'previous', self)
previousAction.setShortcut('F4')
previousAction.setStatusTip('previous')
previousAction.triggered.connect(self.close)
nextAction = QAction(QIcon('../resources/right.png'), 'next', self)
nextAction.setShortcut('F3')
nextAction.setStatusTip('next')
nextAction.triggered.connect(self.close)
saveAction = QAction(QIcon('../resources/save.png'), 'Save', self)
saveAction.setShortcut('F2')
saveAction.setStatusTip('save current file')
saveAction.triggered.connect(self.save)
downloadAction = QAction(QIcon('../resources/globe.png'), 'Download', self)
downloadAction.setShortcut('F5')
downloadAction.setStatusTip('Download road network')
downloadAction.triggered.connect(self.close)
loadAction = QAction(QIcon('../resources/load.png'), 'load file', self)
loadAction.setShortcut('F6')
loadAction.setStatusTip('Download existing file')
loadAction.triggered.connect(self.load)
cleanAction = QAction(QIcon('../resources/cleaningicon.png'), 'Clean', self)
cleanAction.setStatusTip('Clean screen')
cleanAction.triggered.connect(self.clean)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
fileMenu.addAction(saveAction)
fileMenu.addAction(loadAction)
fileMenu.addAction(cleanAction)
toolbar = self.addToolBar('Exit')
toolbar.addAction(exitAction)
toolbar4 = self.addToolBar('Save')
toolbar4.addAction(saveAction)
toolbar5 = self.addToolBar('Load')
toolbar5.addAction(loadAction)
toolbar6 = self.addToolBar('Clean screen')
toolbar6.addAction(cleanAction)
QToolTip.setFont(QFont('SansSerif', 10))
self.setGeometry(300, 200, 650, 550)
self.setWindowTitle('Main window')
self.show()
def clean(self):
msg = QMessageBox.question(self, 'Question', "Are you sure to clean the screen?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if msg == QMessageBox.Yes:
self.widget.drawer.controller.deleteAll()
def closeEvent(self, event):
reply = QMessageBox.question(self, 'Message',
"Save current file?", QMessageBox.Yes |
QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
result = self.save()
if result == -1 :
event.ignore()
def save(self):
fname = QFileDialog.getOpenFileName(self, 'save file', '/home')
if fname[0]:
fd = open(fname[0], 'w')
roads = self.widget.drawer.roads
vertices = self.widget.drawer.vertices
for vertex in vertices:
cortege = vertex.extract()
fd.write(str(cortege) + ' ')
fd.write('\n')
for road in roads:
list = road.extract()
fd.write(str(road.n))
if road.isOneSided:
fd.write(' 1 ')
else:
fd.write(' 0 ')
for cortege in list:
fd.write(str(cortege) + ' ')
fd.write('\n')
fd.close()
return 0
else:
return -1
def load(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
if fname[0]:
fd = open(fname[0], 'r')
line = fd.readline()
vertices = []
roads = []
list1 = line.split()
list2 = []
for element in list1:
element = element.replace('(', '')
element = element.replace(')', '')
element = element.replace(',', '')
element = element.replace(' ', '')
list2.append(int(element))
for i in range(len(list2)//2) :
vertices.append((list2[2*i], list2[2*i+1]))
line = fd.readline()
while line != '':
road = []
list1 = line.split()
list2 = []
n = int(list1.pop(0))
i = int(list1.pop(0))
bool = True
if i == 0:
bool = False
for element in list1:
element = element.replace('(', '')
element = element.replace(')', '')
element = element.replace(',', '')
element = element.replace(' ', '')
list2.append(int(element))
for i in range(len(list2) // 2):
road.append((list2[2 * i], list2[2 * i + 1]))
roads.append((n, bool, road))
line = fd.readline()
fd.close()
self.widget.drawer.loadFromFile(vertices, roads)
def showDialog(self):
col = QColorDialog.getColor()
if col.isValid():
self.widget.setStyleSheet("QWidget { background-color: %s }"
% col.name())
self.p.setColor(self.backgroundRole(), col)
self.setPalette(self.p)
class MyWidget(QWidget) :
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.initUI()
def initUI(self):
self.drawer = Drawer(self)
drawAction = QAction('Draw schema', self)
drawAction.triggered.connect(self.drawer.controller.switchBehaviorToDrawing)
streamAction = QAction('Stream', self)
streamAction.triggered.connect(self.drawer.controller.switchBehaviorToMovement)
singleton = QAction('Singleton', self)
singleton.triggered.connect(self.drawer.controller.switchBehaviourToSingleton)
self.listofactions2 = []
self.listofactions2.append(drawAction)
self.listofactions2.append(streamAction)
self.listofactions2.append(singleton)
self.btn1 = QComboBox(self)
self.btn1.addItem('Draw schema')
self.btn1.addItem('Stream')
self.btn1.addItem('Singleton')
self.btn1.resize(self.btn1.sizeHint())
self.btn1.setFont(QFont('SansSerif', 10))
self.btn1.activated[str].connect(self.chooseWorkingType)
self.btn2 = QPushButton('Chaos', self)
self.btn2.setFont(QFont('SansSerif', 10))
self.btn2.resize(self.btn2.sizeHint())
self.btn2.clicked.connect(self.drawer.chaos)
oneSided = QAction('OneSided road', self)
oneSided.triggered.connect(self.drawer.controller.setOneSided)
twoSided = QAction('TwoSided road', self)
twoSided.triggered.connect(self.drawer.controller.setTwoSided)
self.listofactions = []
self.listofactions.append(oneSided)
self.listofactions.append(twoSided)
btn3 = QComboBox(self)
btn3.addItem('TwoSided road')
btn3.addItem('OneSided road')
btn3.resize(btn3.sizeHint())
btn3.setFont(QFont('SansSerif', 10))
btn3.activated[str].connect(self.chooseRoadSchema)
self.lanes = QLabel('Lanes', self)
self.lane = QLineEdit(self)
self.lane.setText('1')
self.lane.setMaximumWidth(20)
self.lane.setFont(QFont('SansSerif', 10))
self.lane.textChanged[str].connect(self.drawer.controller.changen)
hbox = QHBoxLayout()
hbox.addWidget(btn3)
hbox.addStretch(1)
hbox.addWidget(self.btn1)
hbox.addWidget(self.btn2)
hbox.addWidget(self.lanes)
hbox.addWidget(self.lane)
vbox = QVBoxLayout()
vbox.addWidget(self.drawer)
vbox.addLayout(hbox)
self.setLayout(vbox)
def chooseRoadSchema(self, str):
for action in self.listofactions :
if action.text() == str :
action.trigger()
break
def chooseWorkingType(self, str):
for action in self.listofactions2 :
if action.text() == str :
action.trigger()
break
class CarListWidget(QWidget):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.initUI()
def initUI(self):
self.myList = QListWidget(self)
def addItem(self, name, vel, finish):
self.myList.addItems([name + ' ' + str(vel) + ' ' + finish])
def setNewVelocity(self, int, name):
for i in range(self.myList.count()):
item = self.myList.item(i)
list = item.text().split()
if list[0] == name:
item.setText(list[0] + ' ' + list[1] + ' ' + list[2] + ' ' + str(int))
break
def removeItem(self, name):
for i in range(self.myList.count()):
item = self.myList.item(i)
list = item.text().split()
if list[0] == name:
self.myList.takeItem(i)
break
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())<file_sep>import sys
from Points import Point
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
def center(p1, p2, p3):
x12 = p1.x() - p2.x()
x23 = p2.x() - p3.x()
x31 = p3.x() - p1.x()
y12 = p1.y() - p2.y()
y23 = p2.y() - p3.y()
y31 = p3.y() - p1.y()
z1 = (p1.x()) ** 2 + (p1.y()) ** 2
z2 = (p2.x()) ** 2 + (p2.y()) ** 2
z3 = (p3.x()) ** 2 + (p3.y()) ** 2
zx = y12*z3 + y23*z1 + y31*z2
zy = x12*z3 + x23*z1 + x31*z2
z = x12*y31 - y12*x31
a = - zx/(2*z)
b = zy/(2*z)
return QPoint(a, b)
def onLine(p1, p2, p3):
if (p2.x() - p1.x())*(p3.y() - p2.y()) == (p3.x() - p2.x())*(p2.y() - p1.y()):
return True
else:
return False
def lower(p1, p2, p3):
return (p3.x() - p1.x())*(p2.y() - p1.y()) > (p3.y() - p1.y())*(p2.x() - p1.x())
def sidecurve(points, l):
points1 = []
points2 = []
n = 10
for i in range(n, len(points) - n):
if onLine(points[i - n], points[i], points[i + n]) == False:
p = center(points[i - n], points[i], points[i + n])
p1 = Point(round(points[i].x() + (p.x() - points[i].x())*l/Point.dist(points[i], p)), round(points[i].y() + (p.y() - points[i].y())*l/Point.dist(points[i], p)))
p2 = Point(round(points[i].x() - (p.x() - points[i].x()) * l / Point.dist(points[i], p)),
round(points[i].y() - (p.y() - points[i].y()) * l / Point.dist(points[i], p)))
if lower(points[i-n], points[i], p1):
points1.append(p1)
points2.append(p2)
else:
points1.append(p2)
points2.append(p1)
else:
n1 = points[i].y() - points[i - n].y()
n2 = points[i - n].x() - points[i].x()
#print(n1, n2)
mod = (n1 ** 2 + n2 ** 2) ** 0.5
p1 = Point(round(points[i].x() - n1 * l / mod), round(points[i].y() - n2 * l / mod))
p2 = Point(round(points[i].x() + n1 * l / mod), round(points[i].y() + n2 * l / mod))
#print(p1, p2)
#if lower(points[i - 2], points[i], points1[-1]) == lower(points[i - 2], points[i], p1):
if lower(points[i - n], points[i], p1):
points1.append(p1)
points2.append(p2)
else:
points1.append(p2)
points2.append(p1)
#else:
# points1.append(p2)
# points2.append(p1)
return [points1, points2]
def multiplecurves(points, n, l):
list = []
for i in range(1, n + 1):
s = sidecurve(points, i*l)
list.append(s[0])
list.append(s[1])
return list
<file_sep>import threading, time
from Car import Car
class Stream:
def __init__(self, drawer, startV, endV, probability):
self.drawer = drawer
self.net = self.drawer.net
self.endV = endV
self.startV = startV
self.probability = probability
self.beginStream()
def beginStream(self):
def behavior(startV, endV, drawer, i, probability):
time.sleep(3*i/probability)
velocity = 200
#velocity = random.randint(5,15)*20
car = Car(velocity,drawer)
car.moveAtoB(drawer.net,startV,endV)
for i in range(30):
threading.Thread(target=behavior, args=(self.startV, self.endV, self.drawer, i, self.probability)).start()<file_sep>import networkx as nx
import random
g = nx.MultiDiGraph()
n = 5
for i in range(n):
g.add_node(i)
for i in range(2 * n):
a = random.randint(0, n - 1)
b = random.randint(0, n - 1)
g.add_edge(a, b, weight=random.randint(1, 10))
#print(g.edges())
#print(g.predecessors(1))
#print(nx.neighbors(g, 1))
'''for i in range(10):
print(nx.degree(g, 1, i))
#print("The shortest path between 1 and 2:")
#print(*nx.dijkstra_path(g, 1, 2))
for i in range(n):
print(i, ":", end = " ")
print(g.neighbors(i))
#print()
#print(nx.degree(g, 1))
MG=nx.MultiGraph()
MG.add_weighted_edges_from([(1,2,.5), (1,2,.75), (2,3,.5)])
MG.degree(weight='weight')
GG=nx.Graph()
for n,nbrs in MG.adjacency_iter():
for nbr,edict in nbrs.items():
minvalue=min([d['weight'] for d in edict.values()])
GG.add_edge(n,nbr, weight = minvalue)
nx.shortest_path(GG,1,3) ''' | e6566d571e6ebf99808da2e9a9bb132792ee9a35 | [
"Markdown",
"Python"
] | 13 | Python | AstakhovAnton/Road-organization | 120096a6acd220fa0cbf9072cadb263d910bd474 | 8103a64c3eee3ed99bc51cfc33583a44e8b4839a |
refs/heads/master | <repo_name>stanley355/react-node-crud<file_sep>/README.md
# React + Node.js CRUD operation
## How to start
On each folder please do Yarn Install \
You don't need to yarn install on the root folder
## Database
Just use XAMPP for ur mysql
<file_sep>/Server/index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
// Parse URL encoded bodies (as sent by HTML Form)
app.use(express.urlencoded({extended: true}));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
const db = mysql.createPool({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'mydb'
});
app.get('/api/get', (req, res)=>{
const sqlGet = 'SELECT * FROM crud1';
db.query(sqlGet, (err, result)=>{
if (err) console.log(err);
else res.send(result);
})
})
app.delete('/api/delete/:movieName', (req, res)=>{
const name = req.params.movieName;
const sqlDelete = 'DELETE FROM crud1 WHERE movieName = ?';
db.query(sqlDelete, name, (err, result)=>{
if (err) console.log(err);
else console.log('Data deleted');
});
});
app.put('/api/update', (req, res)=>{
const name = req.body.movieName;
const review = req.body.movieReview;
const sqlUpdate = 'UPDATE SET crud1 movieReview = ? WHERE movieName = ?';
db.query(sqlUpdate, [review, name]), (err, result)=>{
if (err) console.log(err);
else console.log('Data deleted');
};
});
app.post('/api/insert', (req, res)=>{
const movieName = req.body.movieName;
const movieReview = req.body.movieReview;
const sqlInsert = 'INSERT INTO crud1 (movieName, movieReview) VALUES (?, ?)';
db.query(sqlInsert, [movieName, movieReview], (err, result)=>{
if (err) console.log(err);
else console.log(result);
});
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log('Running at port 3001');
})
| 34a2cc981331a6c9dd1a47aba7525055ac66ae5f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | stanley355/react-node-crud | abe684b690efc54fdf510bd0f00e6ed43d4d0403 | ec02ffe3d9bb8158d2f2eda1868c3c9864c1abdd |
refs/heads/master | <repo_name>carlganz/AppliedEconometricsWithR<file_sep>/Ch2.R
library(AER)
library(dplyr)
library(KernSmooth)
set.seed(30)
# Chapter 2
## 1
A=diag(1,10)
A[1,1]<-1
A[10,10]<-1
for (i in 2:9) {
A[i,i]<-2
}
for (i in 1:9) {
A[i,i+1]<--1
}
for (i in 2:10) {
A[i,i-1]<--1
}
A
amatrix<-function(n) {
A=diag(1,n)
for (i in 2:(n-1)) {
A[i,i]<-2
}
for (i in 1:(n-1)) {
A[i,i+1]<--1
}
for (i in 2:n) {
A[i,i-1]<--1
}
return(A)
}
all(amatrix(10)==A)
## 2
data("Parade2005")
Parade<-tbl_df(Parade2005)
Parade %>% filter(state=="CA") %>% summarise(CaliMean=mean(earnings))
Parade %>% filter(state=="ID") %>% summarise (IdahoTotal=n())
Parade %>% filter(celebrity=="yes") %>% summarise(CelebMean=mean(earnings),CelebMedian=median(earnings))
plot(log(Parade$earnings)~Parade$celebrity,xlab="Celebrity",ylab="log(Earnings)")
## 3
density(log(Parade$earnings))
density(log(Parade$earnings),bw="SJ")
## 4
# a
data("CPS1988")
plot(log(CPS1988$wage)~CPS1988$experience,xlab="Experience",ylab="log(Wage)")
plot(log(CPS1988$wage)~CPS1988$education,xlab="Education",ylab="log(Wage)")
# b
CPS1988$education<-factor(CPS1988$education,levels = unique(CPS1988$education))
CPS1988$experience<-factor(CPS1988$experience,levels = unique(CPS1988$experience))
plot(log(CPS1988$wage)~CPS1988$experience,xlab="Experience",ylab="log(Wage)")
plot(log(CPS1988$wage)~CPS1988$education,xlab="Education",ylab="log(Wage)")
# c
plot(log(CPS1988$wage)~CPS1988$ethnicity)
plot(log(CPS1988$wage)~CPS1988$smsa)
plot(log(CPS1988$wage)~CPS1988$region)
plot(log(CPS1988$wage)~CPS1988$parttime)
<file_sep>/Ch3.R
library(AER)
library(dplyr)
library(KernSmooth)
set.seed(30)
data("Journals")
lm1<-lm(Journals$price~Journals$citations)
plot(lm1)
logLik(lm1)
AIC(lm1)
deviance(lm1)
vcov(lm1)
library(splines)
data("CPS1988")
cps<-tbl_df(CPS1988)
lm2<-lm(log(wage)~bs(experience,df=5)+education+ethnicity,cps)
lm2
# 1
x<-1:20
y<-x+rnorm(20)
lm3<-lm(y~x)
summary(lm3)
xmat<-cbind(1,x)
beta<-as.vector(t(solve(t(xmat)%*%xmat)%*%t(xmat)%*%y))
names(beta)<-c("beta0","beta1")
beta
lm4<-lm(y~I(x^2))
summary(lm4)
x2mat<-cbind(1,x^2)
beta2<-as.vector(t(solve(t(x2mat)%*%x2mat)%*%t(x2mat)%*%y))
beta2
lm5<-lm(y~I(x^3))
summary(lm5)
x3mat<-cbind(1,x^3)
beta3<-as.vector(t(solve(t(x3mat)%*%x3mat)%*%t(x3mat)%*%y))
beta3
lm6<-lm(y~I(x^6))
summary(lm6)
x4mat<-cbind(1,x^6)
beta4<-as.vector(t(solve(t(x4mat)%*%x4mat)%*%t(x4mat)%*%y))
beta4
lm7<-lm(y~I(x^7))
summary(lm7)
x5mat<-cbind(1,x^7)
# Error generated
beta5<-as.vector(t(solve(t(x5mat)%*%x5mat)%*%t(x5mat)%*%y))
beta5
# 2
## a
data("HousePrices")
hp<-tbl_df(HousePrices)
head(hp)
lm8<-lm(log(price)~.,hp)
summary(lm8)
hp$recreation<-relevel(hp$recreation,ref="yes")
lm9<-lm(log(price)~log(lotsize)+log(bedrooms)+log(bathrooms)+log(stories)+driveway+recreation+fullbase+gasheat+aircon+garage+prefer,hp)
summary(lm9)
#second model gives a slightly higer R^2
## b
newhouse<-predict(lm9,data.frame(lotsize=4700,bedrooms=3,bathrooms=2,stories=2,driveway="yes",recreation="no",fullbase="yes",gasheat="no",aircon="no",garage=2,prefer="no"),interval="prediction")
newhouse
## c
library(MASS)
boxcox(lm9)
# 3
## a
data("PSID1982")
psid<-tbl_df(PSID1982)
lm10<-lm(log(wage)~I(experience^2)+.,psid)
summary(lm10)
## b
lm11<-lm(log(wage)~I(experience^2)+experience:gender+.,psid)
summary(lm11)
lm12<-lm(log(wage)~I(experience^2)+education:gender+.,psid)
summary(lm12)
# No significiant interaction
# 4
data("USMacroG")
library(dynlm)
dynlm1<-dynlm(consumption~dpi+L(dpi),data=USMacroG)
summary(dynlm1)
dynlm2<-dynlm(consumption~dpi+L(consumption),data=USMacroG)
summary(dynlm2)
## a
jtest(dynlm1,dynlm2)
## b
coxtest(dynlm1,dynlm2)
# 5
data("PSID1982")
psid<-tbl_df(PSID1982)
M1<-lm(log(wage)~education+experience+I(experience^2)+weeks+married+gender+ethnicity+union,psid)
M2<-lm(log(wage)~education+experience+I(experience^2)+weeks+occupation+south+smsa+industry,psid)
M1
M2
## a
jtest(M1,M2)<file_sep>/README.md
# AppliedEconometricsWithR
I am going through the Springer textbook `Applied Econometrics with R` by <NAME> and <NAME>
| 28bc43fe2ddd16f4566556898a927caab99f0940 | [
"Markdown",
"R"
] | 3 | R | carlganz/AppliedEconometricsWithR | 78a0b54d53178a68b9608d4e16954afe57f614ea | bd665856da8470751332e0516a4fd99f27ee89e4 |
refs/heads/master | <file_sep># mqttLinux
Control GPIO pins or any other object remotely through MQTT.
A linux Paho mqtt client receives properties and commands to control connected devices
Example :
- Topic: dst/pi3/gpio/29 , Message: 1 => This will set gpio 29 value to HIGH.
- Topic: dst/pi3/gpio/29 , Message: "output" => This will set gpio 29 to output mode.
<file_sep>
#include "mqttLinux.h"
#include <unordered_map>
const char* signalString[] = {"PIPE_ERROR",
"SELECT_ERROR",
"SERIAL_CONNECT",
"SERIAL_DISCONNECT",
"SERIAL_RXD",
"SERIAL_ERROR",
"MQTT_CONNECT_SUCCESS",
"MQTT_CONNECT_FAIL",
"MQTT_SUBSCRIBE_SUCCESS",
"MQTT_SUBSCRIBE_FAIL",
"MQTT_PUBLISH_SUCCESS",
"MQTT_PUBLISH_FAIL",
"MQTT_DISCONNECTED",
"MQTT_MESSAGE_RECEIVED",
"MQTT_ERROR",
"TIMEOUT"
};
template < class T1,class T2> class BiMap {
std::unordered_map<T1,T2> _t1t2;
std::unordered_map<T2,T1> _t2t1;
public :
BiMap() {};
void add(T1 t1,T2 t2) {
_t1t2[t1]=t2;
_t2t1[t2]=t1;
}
T2 get(T1 t1) {
return _t1t2[t1];
}
T1 get(T2 t2) {
return _t2t1[t2];
}
bool inRange(T1 t1) {
return _t1t2.find(t1)!=_t1t2.cend();
}
bool inRange(T2 t2) {
return _t2t1.find(t2)!=_t2t1.cend();
}
};
BiMap<int,std::string> modeTable;
BiMap<int,std::string> pudTable;
#define USB() logger.application(_serialPort.c_str())
MqttLinux::MqttLinux() {
_mqttConnectionState = MS_DISCONNECTED;
modeTable.add(INPUT,"INPUT");
modeTable.add(OUTPUT,"OUTPUT");
modeTable.add(PWM_OUTPUT,"PWM_OUTPUT");
pudTable.add(PUD_OFF,"PUD_OFF");
pudTable.add(PUD_DOWN,"PUD_DOWN");
pudTable.add(PUD_UP,"PUD_UP");
pudTable.get(1);
}
MqttLinux::~MqttLinux() {}
void MqttLinux::setConfig(Config config) {
_config = config;
}
void MqttLinux::setLogFd(FILE* logFd) {
_logFd = logFd;
}
void MqttLinux::init() {
_startTime = Sys::millis();
_config.setNameSpace("mqtt");
_config.get("port", _mqttPort, 1883);
_config.get("host", _mqttHost, "test.mosquitto.org");
_config.get("keepAliveInterval", _mqttKeepAliveInterval, 5);
_config.get("willMessage", _mqttWillMessage, "false");
_mqttWillQos = 0;
_mqttWillRetained = false;
_mqttLinuxDevice = Sys::hostname();
_mqttDevice = _mqttLinuxDevice;
_mqttSubscribedTo = "dst/" + _mqttLinuxDevice + "/#";
_mqttClientId = _mqttDevice + std::to_string(getpid());
std::string willTopicDefault = "src/" + _mqttLinuxDevice + "/system/alive";
_config.get("willTopic", _mqttWillTopic, willTopicDefault.c_str());
if(pipe(_signalFd) < 0) {
INFO("Failed to create pipe: %s (%d)", strerror(errno), errno);
}
if(fcntl(_signalFd[0], F_SETFL, O_NONBLOCK) < 0) {
INFO("Failed to set pipe non-blocking mode: %s (%d)", strerror(errno), errno);
}
wiringPiSetupGpio();
for(int i=0; i<30; i++) {
Gpio *pGpio = new Gpio(i);
// pGpio->mode(INPUT);
_gpios.push_back(*pGpio);
}
// _gpios.at(29).mode(OUTPUT);
JsonObject gpioConfig=_config.root()["gpio"];
for(int i=0; i<30; i++) {
std::string gpioPort=std::to_string(i);
if ( gpioConfig.containsKey(gpioPort) ) {
if ( gpioConfig[gpioPort].containsKey("mode") &&
gpioConfig[gpioPort].containsKey("value") &&
gpioConfig[gpioPort]["mode"].is<std::string>() &&
modeTable.inRange(gpioConfig[gpioPort]["mode"].as<std::string>()) &&
gpioConfig[gpioPort]["value"].is<int>() ) {
std::string mode=gpioConfig[gpioPort]["mode"];
int value=gpioConfig[gpioPort]["value"];
_gpios[i].mode(modeTable.get(mode));
_gpios[i].write(value);
} else {
WARN(" invalid mode or value for gpio %d",i);
}
}
}
}
void MqttLinux::threadFunction(void* pv) {
run();
}
void MqttLinux::run() {
string line;
Timer mqttConnectTimer;
Timer serialConnectTimer;
Timer mqttPublishTimer;
Timer serialTimer;
mqttConnectTimer.atInterval(2000).doThis([this]() {
if(_mqttConnectionState != MS_CONNECTING) {
mqttConnect();
}
});
mqttPublishTimer.atInterval(1000).doThis([this]() {
std::string sUpTime = std::to_string((Sys::millis() - _startTime) / 1000);
mqttPublish("src/" + _mqttLinuxDevice + "/system/alive", "true", 0, 0);
mqttPublish("src/" + _mqttLinuxDevice + "/system/upTime", sUpTime, 0, 0);
mqttPublish("src/" + _mqttLinuxDevice + "/mqttLinux/device", _mqttDevice, 0, 0);
});
mqttPublishTimer.atInterval(2000).doThis([this]() {
for(int i=0; i<30; i++) {
std::string topic = "src/"+_mqttLinuxDevice+"/gpio";
topic+=std::to_string(i);
std::string message;
_jsonOutput.clear();
_jsonOutput = modeTable.get(_gpios[i].mode());
serializeJson(_jsonOutput,message);
mqttPublish(topic+"/mode",message,0,false);
_jsonOutput.clear();
_jsonOutput = _gpios[i].read();
message.clear();
serializeJson(_jsonOutput,message);
mqttPublish(topic+"/value",message,0,false);
}
});
if(_mqttConnectionState != MS_CONNECTING) mqttConnect();
while(true) {
while(true) {
Signal s = waitSignal(1000);
DEBUG("signal = %s", signalString[s]);
mqttConnectTimer.check();
serialTimer.check();
mqttPublishTimer.check();
serialConnectTimer.check();
switch(s) {
case TIMEOUT: {
break;
}
case MQTT_CONNECT_SUCCESS: {
INFO("MQTT_CONNECT_SUCCESS ");
mqttConnectionState(MS_CONNECTED);
mqttSubscribe(_mqttSubscribedTo);
break;
}
case MQTT_CONNECT_FAIL: {
WARN("MQTT_CONNECT_FAIL ");
mqttConnectionState(MS_DISCONNECTED);
break;
}
case MQTT_DISCONNECTED: {
WARN("MQTT_DISCONNECTED ");
mqttConnectionState(MS_DISCONNECTED);
break;
}
case MQTT_SUBSCRIBE_SUCCESS: {
INFO("MQTT_SUBSCRIBE_SUCCESS ");
break;
}
case MQTT_SUBSCRIBE_FAIL: {
WARN("MQTT_SUBSCRIBE_FAIL ");
mqttDisconnect();
break;
}
case MQTT_ERROR: {
WARN("MQTT_ERROR ");
break;
}
case PIPE_ERROR: {
WARN("PIPE_ERROR ");
break;
}
case MQTT_PUBLISH_SUCCESS: {
break;
}
case MQTT_MESSAGE_RECEIVED: {
break;
}
default: {
WARN("received signal [%d] %s ", s,signalString[s]);
}
}
}
}
WARN(" exited run loop !!");
}
void MqttLinux::signal(uint8_t m) {
if(write(_signalFd[1], (void*)&m, 1) < 1) {
INFO("Failed to write pipe: %s (%d)", strerror(errno), errno);
}
// INFO(" signal '%c' ",m);
}
MqttLinux::Signal MqttLinux::waitSignal(uint32_t timeout) {
Signal returnSignal = TIMEOUT;
uint8_t buffer;
fd_set rfds;
fd_set wfds;
fd_set efds;
struct timeval tv;
int retval;
// uint64_t delta=1000;
// Wait up to 1000 msec.
uint64_t delta = timeout;
tv.tv_sec = 1;
tv.tv_usec = (delta * 1000) % 1000000;
// Watch serialFd and tcpFd to see when it has input.
FD_ZERO(&rfds);
FD_ZERO(&wfds);
FD_ZERO(&efds);
if(_signalFd[0]) {
FD_SET(_signalFd[0], &rfds);
FD_SET(_signalFd[0], &efds);
}
int maxFd = _signalFd[0] ;
maxFd += 1;
retval = select(maxFd, &rfds, NULL, &efds, &tv);
if(retval < 0) {
WARN(" select() : error : %s (%d)", strerror(errno), errno);
returnSignal = SELECT_ERROR;
} else if(retval > 0) { // one of the fd was set
if(FD_ISSET(_signalFd[0], &rfds)) {
::read(_signalFd[0], &buffer, 1); // read 1 event
returnSignal = (Signal)buffer;
}
if(FD_ISSET(_signalFd[0], &efds)) {
WARN("pipe error : %s (%d)", strerror(errno), errno);
returnSignal = PIPE_ERROR;
}
} else {
TRACE(" timeout %llu", Sys::millis());
returnSignal = TIMEOUT;
}
return (Signal)returnSignal;
}
/*
*
@ @ @@@@@ @@@@@@@ @@@@@@@
@@ @@ @ @ @ @
@ @ @ @ @ @ @ @
@ @ @ @ @ @ @
@ @ @ @ @ @ @
@ @ @ @ @ @
@ @ @@@@ @ @ @
*
*/
const char* mqttConnectionStates[] = {"MS_CONNECTED", "MS_DISCONNECTED", "MS_CONNECTING", "MS_DISCONNECTING"};
void MqttLinux::mqttConnectionState(MqttConnectionState st) {
INFO(" MQTT connection state %s => %s ", mqttConnectionStates[_mqttConnectionState], mqttConnectionStates[st]);
_mqttConnectionState = st;
}
Erc MqttLinux::mqttConnect() {
string connection;
int rc;
if(_mqttConnectionState == MS_CONNECTING || _mqttConnectionState == MS_CONNECTED) return E_OK;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
connection = "tcp://" + _mqttHost + ":";
connection += std::to_string(_mqttPort);
INFO(" MQTT connecting %s ... for %s ", connection.c_str(), _mqttLinuxDevice.c_str());
mqttConnectionState(MS_CONNECTING);
MQTTAsync_create(&_client, connection.c_str(), _mqttClientId.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
MQTTAsync_setCallbacks(_client, this, onConnectionLost, onMessage, onDeliveryComplete); // TODO add ondelivery
conn_opts.keepAliveInterval = _mqttKeepAliveInterval;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnectSuccess;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = this;
will_opts.message = _mqttWillMessage.c_str();
will_opts.topicName = _mqttWillTopic.c_str();
will_opts.qos = _mqttWillQos;
will_opts.retained = _mqttWillRetained;
conn_opts.will = &will_opts;
if((rc = MQTTAsync_connect(_client, &conn_opts)) != MQTTASYNC_SUCCESS) {
WARN("Failed to start connect, return code %d", rc);
return E_NOT_FOUND;
}
mqttConnectionState(MS_CONNECTING);
return E_OK;
}
void MqttLinux::mqttDisconnect() {
mqttConnectionState(MS_DISCONNECTING);
MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
disc_opts.onSuccess = onDisconnect;
disc_opts.context = this;
int rc = 0;
if((rc = MQTTAsync_disconnect(_client, &disc_opts)) != MQTTASYNC_SUCCESS) {
WARN("Failed to disconnect, return code %d", rc);
return;
}
MQTTAsync_destroy(&_client);
mqttConnectionState(MS_DISCONNECTED);
}
void MqttLinux::mqttSubscribe(string topic) {
int qos = 0;
if(_mqttConnectionState != MS_CONNECTED) return;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
INFO("Subscribing to topic %s for client %s using QoS%d", topic.c_str(), _mqttClientId.c_str(), qos);
opts.onSuccess = onSubscribeSuccess;
opts.onFailure = onSubscribeFailure;
opts.context = this;
int rc = E_OK;
if((rc = MQTTAsync_subscribe(_client, topic.c_str(), qos, &opts)) != MQTTASYNC_SUCCESS) {
ERROR("Failed to start subscribe, return code %d", rc);
signal(MQTT_SUBSCRIBE_FAIL);
} else {
INFO(" subscribe send ");
}
}
void MqttLinux::onConnectionLost(void* context, char* cause) {
MqttLinux* me = (MqttLinux*)context;
// me->mqttDisconnect();
me->signal(MQTT_DISCONNECTED);
}
int MqttLinux::onMessage(void* context, char* topicName, int topicLen, MQTTAsync_message* message) {
MqttLinux* me = (MqttLinux*)context;
std::string topic(topicName, topicLen);
std::string msg((const char*)message->payload,message->payloadlen);
me->onMqttMessage(topic,msg);
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
me->signal(MQTT_MESSAGE_RECEIVED);
return 1;
}
template <typename Out>
void split(const std::string &s, char delim, Out result) {
std::istringstream iss(s);
std::string item;
while (std::getline(iss, item, delim)) {
*result++ = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
void MqttLinux::onMqttMessage(std::string topic,std::string message) {
std::vector<std::string> fields=split(topic,'/');
INFO("%s:%s",topic.c_str(),message.c_str());
if ( fields.size()<4) {
WARN("device topic incorrect :%s",topic.c_str());
return;
}
std::string device=fields.at(1);
std::string object=fields.at(2);
std::string property=fields.at(3);
_jsonDoc.clear();
DeserializationError error = deserializeJson(_jsonDoc,message.c_str());
if ( error ) {
WARN(" JSON deserialization of value failed : %s ",message.c_str());
return;
}
JsonVariant variant = _jsonDoc.as<JsonVariant>();
if ( variant.isNull() ) {
WARN("Json variant is null : '%s'",message.c_str());
return;
}
std::string s;
/* variant.printTo(s);
INFO("%s",s.c_str());*/
if ( object.rfind("gpio",0)==0) {
int pin = std::stoi(object.substr(4,2));
if ( property.compare("value")==0) {
if ( variant.is<int>() ) {
_gpios.at(pin).write(variant.as<int>());
} else if ( variant.is<bool>() ) {
_gpios.at(pin).write(variant.as<bool>()?1:0);
} else {
WARN(" invalid value : %s",message.c_str());
}
} else if(property.compare("mode")==0) {
if ( variant.is<std::string>() && modeTable.inRange(variant.as<std::string>()) ) {
_gpios.at(pin).mode(modeTable.get(variant.as<std::string>()));
} else {
WARN(" invalid mode : %s",message.c_str());
}
} else if(property.compare("pud")==0) {
if ( variant.is<std::string>() && pudTable.inRange(variant.as<std::string>()) ) {
_gpios.at(pin).pud(pudTable.get(variant.as<std::string>()));
} else {
WARN(" invalid pud : %s",message.c_str());
}
} else {
WARN(" unknown property : %s",property.c_str());
}
} else {
WARN(" unknown object : %s",object.c_str());
}
}
void MqttLinux::onDeliveryComplete(void* context, MQTTAsync_token response) {
// MqttLinux* me = (MqttLinux*)context;
}
void MqttLinux::onDisconnect(void* context, MQTTAsync_successData* response) {
MqttLinux* me = (MqttLinux*)context;
me->signal(MQTT_DISCONNECTED);
}
void MqttLinux::onConnectFailure(void* context, MQTTAsync_failureData* response) {
MqttLinux* me = (MqttLinux*)context;
me->signal(MQTT_CONNECT_FAIL);
me->mqttConnectionState(MS_DISCONNECTED);
}
void MqttLinux::onConnectSuccess(void* context, MQTTAsync_successData* response) {
MqttLinux* me = (MqttLinux*)context;
me->signal(MQTT_CONNECT_SUCCESS);
me->mqttConnectionState(MS_CONNECTED);
}
void MqttLinux::onSubscribeSuccess(void* context, MQTTAsync_successData* response) {
MqttLinux* me = (MqttLinux*)context;
me->signal(MQTT_SUBSCRIBE_SUCCESS);
}
void MqttLinux::onSubscribeFailure(void* context, MQTTAsync_failureData* response) {
MqttLinux* me = (MqttLinux*)context;
me->signal(MQTT_SUBSCRIBE_FAIL);
}
void MqttLinux::mqttPublish(string topic, std::string message, int qos, bool retained) {
if(!_mqttConnectionState==MS_CONNECTED) {
return;
}
qos = 1;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
// INFO("mqttPublish %s",topic.c_str());
int rc = E_OK;
opts.onSuccess = onPublishSuccess;
opts.onFailure = onPublishFailure;
opts.context = this;
pubmsg.payload = (void*)message.data();
pubmsg.payloadlen = message.length();
pubmsg.qos = qos;
pubmsg.retained = retained;
if((rc = MQTTAsync_sendMessage(_client, topic.c_str(), &pubmsg, &opts)) != MQTTASYNC_SUCCESS) {
signal(MQTT_DISCONNECTED);
ERROR("MQTTAsync_sendMessage failed.");
}
}
void MqttLinux::onPublishSuccess(void* context, MQTTAsync_successData* response) {
MqttLinux* me = (MqttLinux*)context;
me->signal(MQTT_PUBLISH_SUCCESS);
}
void MqttLinux::onPublishFailure(void* context, MQTTAsync_failureData* response) {
MqttLinux* me = (MqttLinux*)context;
me->signal(MQTT_PUBLISH_FAIL);
}
<file_sep>#include <wiringPi.hpp>
#include <Log.h>
#ifndef __arm__
extern "C" void pinMode(int pin,int mode) {
INFO("gpio %d mode %d",pin,mode);
}
extern "C" void digitalWrite(int pin,int value) {
INFO("gpio %d write %d ",pin,value);
}
#endif
<file_sep>#ifndef SERIAL2MQTT_H
#define SERIAL2MQTT_H
#include "MQTTAsync.h"
// For convenience
#include <Sys.h>
#include <Erc.h>
#include <sstream>
#include <vector>
#include "Config.h"
#include "CircBuf.h"
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <linux/serial.h>
#include <termios.h>
#include <asm-generic/ioctls.h>
#include <sys/ioctl.h>
#include <Timer.h>
#include <wiringPi.hpp>
using namespace std;
class Gpio {
int _pin;
int _pud;
public:
Gpio(int pin):_pin(pin) {
_pud=PUD_OFF;
};
void mode(int m) {
pinMode(_pin,m);
INFO("GPIO mode %d : %d",_pin,m);
};
void write(int x) {
INFO("GPIO write %d : %d",_pin,x==0?0:1);
digitalWrite(_pin,x==0?0:1);
}
int mode() {
return getAlt(_pin);
}
int pud() {
return _pud;
};
void pud(int pudMode) {
_pud = pudMode;
pullUpDnControl(_pin,pudMode);
}
int read() {
return digitalRead(_pin);
}
};
class MqttLinux {
Config _config;
StaticJsonDocument<10000> _jsonDoc;
StaticJsonDocument<100> _jsonOutput;
string _mqttLinuxDevice; // <host>.USBx
MQTTAsync_token _deliveredtoken;
MQTTAsync _client;
int _signalFd[2]; // pipe fd to wakeup in select
std::vector<Gpio> _gpios;
// MQTT
string _mqttHost;
string _mqttClientId;
uint16_t _mqttPort;
uint32_t _mqttKeepAliveInterval;
string _mqttWillMessage;
std::string _mqttWillTopic;
uint16_t _mqttWillQos;
bool _mqttWillRetained;
string _mqttDevice;
string _mqttProgrammerTopic;
uint64_t _startTime;
// bool _mqttConnected=false;
string _mqttSubscribedTo;
FILE* _logFd;
typedef enum {
MS_CONNECTED,
MS_DISCONNECTED,
MS_CONNECTING,
MS_DISCONNECTING
} MqttConnectionState;
MqttConnectionState _mqttConnectionState;
public:
typedef enum {PIPE_ERROR=0,
SELECT_ERROR,
SERIAL_CONNECT,
SERIAL_DISCONNECT,
SERIAL_RXD,
SERIAL_ERROR,
MQTT_CONNECT_SUCCESS,
MQTT_CONNECT_FAIL,
MQTT_SUBSCRIBE_SUCCESS,
MQTT_SUBSCRIBE_FAIL,
MQTT_PUBLISH_SUCCESS,
MQTT_PUBLISH_FAIL,
MQTT_DISCONNECTED,
MQTT_MESSAGE_RECEIVED,
MQTT_ERROR,
TIMEOUT
} Signal;
MqttLinux();
~MqttLinux();
void init();
void run();
void threadFunction(void*);
void signal(uint8_t s);
Signal waitSignal(uint32_t timeout);
void setConfig(Config config);
void setLogFd(FILE*);
// void serialMqttPublish(string topic,Bytes message,int qos,bool retained);
Erc mqttConnect();
void mqttDisconnect();
void mqttPublish(string topic,string message,int qos,bool retained);
void mqttSubscribe(string topic);
static void onConnectionLost(void *context, char *cause);
static int onMessage(void *context, char *topicName, int topicLen, MQTTAsync_message *message);
static void onDisconnect(void* context, MQTTAsync_successData* response);
static void onConnectFailure(void* context, MQTTAsync_failureData* response);
static void onConnectSuccess(void* context, MQTTAsync_successData* response);
static void onSubscribeSuccess(void* context, MQTTAsync_successData* response);
static void onSubscribeFailure(void* context, MQTTAsync_failureData* response);
static void onPublishSuccess(void* context, MQTTAsync_successData* response);
static void onPublishFailure(void* context, MQTTAsync_failureData* response);
static void onDeliveryComplete(void* context, MQTTAsync_token response);
void onMqttMessage(std::string topic,std::string message);
void mqttConnectionState(MqttConnectionState);
};
#endif // SERIAL2MQTT_H
<file_sep>/*
* wiringPi.h:
* Arduino like Wiring library for the Raspberry Pi.
* Copyright (c) 2012-2017 <NAME>
***********************************************************************
* This file is part of wiringPi:
* https://projects.drogon.net/raspberry-pi/wiringpi/
*
* wiringPi is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wiringPi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with wiringPi. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************
*/
#ifndef __WIRING_PI_H__
#define __WIRING_PI_H__
// C doesn't have true/false by default and I can never remember which
// way round they are, so ...
// (and yes, I know about stdbool.h but I like capitals for these and I'm old)
#ifndef TRUE
# define TRUE (1==1)
# define FALSE (!TRUE)
#endif
// GCC warning suppressor
#define UNU __attribute__((unused))
// Mask for the bottom 64 pins which belong to the Raspberry Pi
// The others are available for the other devices
#define PI_GPIO_MASK (0xFFFFFFC0)
// Handy defines
// wiringPi modes
#define WPI_MODE_PINS 0
#define WPI_MODE_GPIO 1
#define WPI_MODE_GPIO_SYS 2
#define WPI_MODE_PHYS 3
#define WPI_MODE_PIFACE 4
#define WPI_MODE_UNINITIALISED -1
// Pin modes
#define INPUT 0
#define OUTPUT 1
#define PWM_OUTPUT 2
#define GPIO_CLOCK 3
#define SOFT_PWM_OUTPUT 4
#define SOFT_TONE_OUTPUT 5
#define PWM_TONE_OUTPUT 6
#define LOW 0
#define HIGH 1
// Pull up/down/none
#define PUD_OFF 0
#define PUD_DOWN 1
#define PUD_UP 2
// PWM
#define PWM_MODE_MS 0
#define PWM_MODE_BAL 1
// Interrupt levels
#define INT_EDGE_SETUP 0
#define INT_EDGE_FALLING 1
#define INT_EDGE_RISING 2
#define INT_EDGE_BOTH 3
// Pi model types and version numbers
// Intended for the GPIO program Use at your own risk.
#define PI_MODEL_A 0
#define PI_MODEL_B 1
#define PI_MODEL_AP 2
#define PI_MODEL_BP 3
#define PI_MODEL_2 4
#define PI_ALPHA 5
#define PI_MODEL_CM 6
#define PI_MODEL_07 7
#define PI_MODEL_3B 8
#define PI_MODEL_ZERO 9
#define PI_MODEL_CM3 10
#define PI_MODEL_ZERO_W 12
#define PI_MODEL_3BP 13
#define PI_MODEL_3AP 14
#define PI_MODEL_CM3P 16
#define PI_MODEL_4B 17
#define PI_VERSION_1 0
#define PI_VERSION_1_1 1
#define PI_VERSION_1_2 2
#define PI_VERSION_2 3
#define PI_MAKER_SONY 0
#define PI_MAKER_EGOMAN 1
#define PI_MAKER_EMBEST 2
#define PI_MAKER_UNKNOWN 3
extern const char *piModelNames [20] ;
extern const char *piRevisionNames [16] ;
extern const char *piMakerNames [16] ;
extern const int piMemorySize [ 8] ;
// Intended for the GPIO program Use at your own risk.
// Threads
#define PI_THREAD(X) void *X (UNU void *dummy)
// Failure modes
#define WPI_FATAL (1==1)
#define WPI_ALMOST (1==2)
// wiringPiNodeStruct:
// This describes additional device nodes in the extended wiringPi
// 2.0 scheme of things.
// It's a simple linked list for now, but will hopefully migrate to
// a binary tree for efficiency reasons - but then again, the chances
// of more than 1 or 2 devices being added are fairly slim, so who
// knows....
struct wiringPiNodeStruct {
int pinBase ;
int pinMax ;
int fd ; // Node specific
unsigned int data0 ; // ditto
unsigned int data1 ; // ditto
unsigned int data2 ; // ditto
unsigned int data3 ; // ditto
void (*pinMode) (struct wiringPiNodeStruct *node, int pin, int mode) ;
void (*pullUpDnControl) (struct wiringPiNodeStruct *node, int pin, int mode) ;
int (*digitalRead) (struct wiringPiNodeStruct *node, int pin) ;
//unsigned int (*digitalRead8) (struct wiringPiNodeStruct *node, int pin) ;
void (*digitalWrite) (struct wiringPiNodeStruct *node, int pin, int value) ;
// void (*digitalWrite8) (struct wiringPiNodeStruct *node, int pin, int value) ;
void (*pwmWrite) (struct wiringPiNodeStruct *node, int pin, int value) ;
int (*analogRead) (struct wiringPiNodeStruct *node, int pin) ;
void (*analogWrite) (struct wiringPiNodeStruct *node, int pin, int value) ;
struct wiringPiNodeStruct *next ;
} ;
extern struct wiringPiNodeStruct *wiringPiNodes ;
// Export variables for the hardware pointers
extern volatile unsigned int *_wiringPiGpio ;
extern volatile unsigned int *_wiringPiPwm ;
extern volatile unsigned int *_wiringPiClk ;
extern volatile unsigned int *_wiringPiPads ;
extern volatile unsigned int *_wiringPiTimer ;
extern volatile unsigned int *_wiringPiTimerIrqRaw ;
// Function prototypes
// c++ wrappers thanks to a comment by <NAME>
// (and others on the Raspberry Pi forums)
#ifdef __cplusplus
extern "C" {
#endif
// Data
// Internal
extern int wiringPiFailure (int fatal, const char *message, ...) ;
// Core wiringPi functions
extern struct wiringPiNodeStruct *wiringPiFindNode (int pin) ;
extern struct wiringPiNodeStruct *wiringPiNewNode (int pinBase, int numPins) ;
extern void wiringPiVersion (int *major, int *minor) ;
extern int wiringPiSetup (void) ;
extern int wiringPiSetupSys (void) ;
extern int wiringPiSetupGpio (void) ;
extern int wiringPiSetupPhys (void) ;
extern void pinModeAlt (int pin, int mode) ;
extern void pinMode (int pin, int mode) ;
extern void pullUpDnControl (int pin, int pud) ;
extern int digitalRead (int pin) ;
extern void digitalWrite (int pin, int value) ;
extern unsigned int digitalRead8 (int pin) ;
extern void digitalWrite8 (int pin, int value) ;
extern void pwmWrite (int pin, int value) ;
extern int analogRead (int pin) ;
extern void analogWrite (int pin, int value) ;
// PiFace specifics
// (Deprecated)
extern int wiringPiSetupPiFace (void) ;
extern int wiringPiSetupPiFaceForGpioProg (void) ; // Don't use this - for gpio program only
// On-Board Raspberry Pi hardware specific stuff
extern int piGpioLayout (void) ;
extern int piBoardRev (void) ; // Deprecated
extern void piBoardId (int *model, int *rev, int *mem, int *maker, int *overVolted) ;
extern int wpiPinToGpio (int wpiPin) ;
extern int physPinToGpio (int physPin) ;
extern void setPadDrive (int group, int value) ;
extern int getAlt (int pin) ;
extern void pwmToneWrite (int pin, int freq) ;
extern void pwmSetMode (int mode) ;
extern void pwmSetRange (unsigned int range) ;
extern void pwmSetClock (int divisor) ;
extern void gpioClockSet (int pin, int freq) ;
extern unsigned int digitalReadByte (void) ;
extern unsigned int digitalReadByte2 (void) ;
extern void digitalWriteByte (int value) ;
extern void digitalWriteByte2 (int value) ;
// Interrupts
// (Also Pi hardware specific)
extern int waitForInterrupt (int pin, int mS) ;
extern int wiringPiISR (int pin, int mode, void (*function)(void)) ;
// Threads
extern int piThreadCreate (void *(*fn)(void *)) ;
extern void piLock (int key) ;
extern void piUnlock (int key) ;
// Schedulling priority
extern int piHiPri (const int pri) ;
// Extras from arduino land
extern void delay (unsigned int howLong) ;
extern void delayMicroseconds (unsigned int howLong) ;
extern unsigned int millis (void) ;
extern unsigned int micros (void) ;
#ifdef __cplusplus
}
#endif
#endif
| 1d10f107f22435d42e9dc53e6ad97b07159fa406 | [
"Markdown",
"C++"
] | 5 | Markdown | vortex314/mqttLinux | 94c94265a0b451e8bee532b6d89666ea1514e060 | 528db0b092ca7108a057c8d14f6bae304a088c6c |
refs/heads/master | <repo_name>facewindu/build-info<file_sep>/build-info-api/src/main/java/org/jfrog/build/api/Issues.java
package org.jfrog.build.api;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang.StringUtils;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* @author <NAME>
*/
public class Issues implements Serializable {
private IssueTracker tracker;
private boolean aggregateBuildIssues;
private String aggregationBuildStatus;
private Set<Issue> affectedIssues;
public Issues() {
}
public Issues(IssueTracker tracker, boolean aggregateBuildIssues, String aggregationBuildStatus, Set<Issue> affectedIssues) {
this.tracker = tracker;
this.aggregateBuildIssues = aggregateBuildIssues;
this.aggregationBuildStatus = aggregationBuildStatus;
this.affectedIssues = affectedIssues;
}
public IssueTracker getTracker() {
return tracker;
}
public void setTracker(IssueTracker tracker) {
this.tracker = tracker;
}
public Set<Issue> getAffectedIssues() {
return affectedIssues;
}
public void addIssue(Issue issue) {
if (affectedIssues == null) {
affectedIssues = new HashSet<>();
}
affectedIssues.add(issue);
}
@JsonIgnore
public boolean isEmpty() {
if (tracker != null && StringUtils.isNotEmpty(aggregationBuildStatus)) {
return false;
}
if (affectedIssues == null) {
return true;
}
return affectedIssues.isEmpty();
}
public void setAffectedIssues(Set<Issue> affectedIssues) {
this.affectedIssues = affectedIssues;
}
public boolean isAggregateBuildIssues() {
return aggregateBuildIssues;
}
public void setAggregateBuildIssues(boolean aggregateBuildIssues) {
this.aggregateBuildIssues = aggregateBuildIssues;
}
public String getAggregationBuildStatus() {
return aggregationBuildStatus;
}
public void setAggregationBuildStatus(String aggregationBuildStatus) {
this.aggregationBuildStatus = aggregationBuildStatus;
}
}
| 7daf97b7116d4ce17eec479d717ce4e3b38dc77d | [
"Java"
] | 1 | Java | facewindu/build-info | de4afa5868a63968d43a003564fe02c2bf4f9c03 | 2a3232ac5e1e5109a0fbef421d1871cf93798e6d |
refs/heads/master | <file_sep>const express = require('express');
const yaml = require('js-yaml');
const { default: axios } = require('axios');
const fs = require('fs');
const app = express();
const { PORT, IP } = process.env;
const baseURL = "https://alar.ink/tl/kn";
const dictionary = yaml.load(fs.readFileSync('./alar.yml', { encoding: 'utf-8' }));
app.get('/', (req, res) => {
res.json({
"Hello World!": "This is an unofficial REST API for Alar.ink",
endPoints: [
{
searchByWord: "/search?q=",
examples: ["/search?q=alar", "/search?q=ಅಲರ್"],
}
],
author: {
name: "<NAME>.",
emailID: "<EMAIL>"
}
});
});
app.get('/search', async (req, res) => {
const query = req.query.q;
const url = new URL(`${baseURL}/${query}`);
const { data } = await axios.get(url.toString());
const words = data.result;
const response = [];
words.forEach(word => {
response.push(...dictionary.filter(item => item.entry === word));
});
res.json({
input: query,
results: response,
success: response.length !== 0,
at: new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' })
});
});
app.listen(PORT || 3000, IP, () => {
console.log(`Server listening on port: ${PORT || 3000}`);
});
| d84beafce49557c15fbe47c17c18b15867107288 | [
"JavaScript"
] | 1 | JavaScript | Aditya-ds-1806/alar-api | a323a798d72c2cc5a3b64e00aa8dccef6ed0203d | c6b91e4387170b3abbcc64d725af6a4778551026 |
refs/heads/main | <file_sep>import xml.etree.ElementTree as ET
import os
missing_subdocs = []
missing_lemmata = []
## IMPORTANT: afterwards, remove "
with open('lemma_lookup.csv', 'w+', encoding='UTF-8') as output:
for xml in os.listdir('parsed_xmls'):
read_xml = ET.parse('parsed_xmls/' + xml)
print(xml)
root = read_xml.getroot()
for sentence in root[:]:
for word in sentence[:]:
if 'id' in word.attrib:
if int(word.attrib['id']) % 10000 == 0:
print(word.attrib['id'])
if 'lemma' in word.attrib and 'subdoc' in sentence.attrib:
if 'line' in word.attrib:
output.write(
sentence.attrib['document_id'] + '\t' + sentence.attrib['subdoc'] + '\t' +
sentence.attrib['id'] + '\t' + word.attrib['line'] + '\t' + word.attrib['id'] + '\t' +
word.attrib['lemma']+ '\t' + word.attrib['form'] + '\n')
else:
output.write(
sentence.attrib['document_id'] + '\t' + sentence.attrib['subdoc'] + '\t' +
sentence.attrib['id'] + '\t' + '' + '\t' + word.attrib['id'] + '\t' +
word.attrib['lemma'] + '\t' + word.attrib['form'] + '\n')
elif 'lemma' in word.attrib:
if 'line' in word.attrib:
output.write(sentence.attrib['document_id'] + '\t' + '' + '\t' + sentence.attrib['id'] +
'\t' + word.attrib['line'] + '\t' + word.attrib['id'] + '\t' +
word.attrib['lemma'] + '\t' + word.attrib['form'] + '\n')
missing_subdocs.append(sentence.attrib['document_id'])
else:
output.write(sentence.attrib['document_id'] + '\t' + '' + '\t' + sentence.attrib['id'] +
'\t' + '' + '\t' + word.attrib['id'] + '\t' + word.attrib['lemma'] + '\t' +
word.attrib['form'] + '\n')
missing_subdocs.append(sentence.attrib['document_id'])
elif 'subdoc' in sentence.attrib:
if 'line' in word.attrib:
output.write(
sentence.attrib['document_id'] + '\t' + sentence.attrib['subdoc'] + '\t' +
sentence.attrib['id'] + '\t' + word.attrib['line'] + '\t' + word.attrib['id'] +
'\t' + '' + '\t' + word.attrib['form'] + '\n')
missing_lemmata.append(word.attrib['id'])
else:
output.write(
sentence.attrib['document_id'] + '\t' + sentence.attrib['subdoc'] + '\t' +
sentence.attrib['id'] + '\t' + '' + '\t' + word.attrib['id'] + '\t' + '' + '\t' +
word.attrib['form'] + '\n')
missing_lemmata.append(word.attrib['id'])
else:
if 'line' in word.attrib:
output.write(sentence.attrib['document_id'] + '\t' + '' + '\t' + sentence.attrib['id'] +
'\t' + word.attrib['line'] + '\t' + word.attrib['id'] + '\t' + '' + '\t' +
word.attrib['form'] + '\n')
else:
output.write(sentence.attrib['document_id'] + '\t' + '' + '\t' + sentence.attrib['id'] +
'\t' + '' + '\t' + word.attrib['id'] + '\t' + '' + '\t' +
word.attrib['form'] + '\n')
with open('missing_subdocs.txt', 'w+', encoding='UTF-8') as output:
for missing in set(missing_subdocs):
output.write(missing + '\n')
with open('missing_lemmata.txt', 'w+', encoding='UTF-8') as output:
for missing in missing_lemmata:
output.write(missing + '\n')
<file_sep>import numpy as np
import pandas as pd
import random
import unicodedata as ucd
chosen_words = ['εἰς', 'λέγω', 'ἄλλος', 'πόλις', 'οὐδείς', 'ὦ', 'λαμβάνω', 'ἔτι', 'παῖς', 'ἀγαθός']
position_in_alphabet = {'α': '1', 'β': '2', 'γ': '3', 'δ': '4', 'ε': '5', 'ζ': '7', 'η': '8', 'θ': '9',
'ι': '10', 'κ': '11', 'λ': '12', 'μ': '13', 'ν': '14', 'ξ': '15', 'ο': '16',
'π': '17', 'ρ': '20', 'σ': '21', 'τ': '22', 'υ': '23', 'φ': '24', 'χ': '25',
'ψ': '26', 'ω': '27'} # watch out for combined accents and accents integrated in the character
def first_letter_without_accents(word: str):
norm_word = ucd.normalize('NFKD', word)
return norm_word[0]
def include_context(word_id: int):
index = word_id - 1
# Need rows with sentence of word_id, doc and subdoc should be equal as well
context = xml[(xml['sentence'] == xml['sentence'][index]) & (xml['doc'] == xml['doc'][index]) & (
xml['subdoc'] == xml['subdoc'][index])]
return ' '.join(context['form'].values) # return a string with the corresponding form values
xml = pd.read_csv('lemma_lookup.csv', sep='\t', encoding='UTF-8',
names=['doc', 'subdoc', 'sentence', 'line', 'word', 'lemma', 'form'],
dtype={'doc': str, 'subdoc': str, 'sentence': int, 'line': str,
'word': int, 'lemma': str, 'form': str})
test_data = []
for chosen_word in chosen_words:
print(chosen_word)
position = position_in_alphabet[first_letter_without_accents(chosen_word)]
lsj = pd.read_csv('LSJ_words/LSJ_{}_words.csv'.format(position), sep='\t', encoding='UTF-8')
chosen_word_lsj = lsj[lsj['lemma'] == chosen_word]
chosen_word_lsj['word'] = chosen_word_lsj['word'].dropna().apply(
lambda x: list(map(int, x.strip('[]\'\'').split(', ')))) # convert string of list to actual list
raw_training_data = chosen_word_lsj['word'].dropna().values # list of occurrences
result = []
for data in raw_training_data:
if len(data) <= 3: # filter out excessively long lists
result.append(data)
training_data_ids = set(np.hstack(result))
# Search for all occurrences of chosen_word in XML
chosen_xml = xml[xml['lemma'] == chosen_word]
# Exclude all in chosen_word_lsj
all_xml_data = chosen_xml['word'].values
possible_test_data = [word for word in all_xml_data if word not in training_data_ids]
training_data = [word for word in all_xml_data if word in training_data_ids]
# Random subset for test
random.seed(42) # set seed to ensure that the test set is random, but every time the same
test_data.append(random.sample(possible_test_data, 20))
flat_test_data = [word for per_word_data in test_data for word in per_word_data] # flatten the list of test data
all_context = [] #Adding context
for index, word in enumerate(sorted(flat_test_data)):
print(index)
all_context.append(include_context(word))
test_data_xml = xml[xml['word'].isin(flat_test_data)]
test_data_xml['context'] = all_context
test_data_xml.to_csv('test_data.csv', sep='\t', encoding='UTF-8')
<file_sep>import pandas as pd
import re
pattern = r".perseus-\w+\d" # to remove .perseus-grc1 etc.
def urn_to_ids(ref: str): # Returns a dictionary containing the doc-id and the subdoc
temp_ref = re.sub(pattern, '', ref)
temp_ref = ''.join(digit for digit in temp_ref if not digit.isalpha()) # removes other non-numerics
temp_ref = temp_ref[3:] # removes initial :
temp_ref = temp_ref.replace(':', '.') # removes remaining :
cleaned_ref = temp_ref.replace('.', ':', 2) # split between author/work/subdoc is : otherwise .
reference_fields = cleaned_ref.split(':')
while len(reference_fields) < 3:
reference_fields.append(None)
return {'doc': reference_fields[0] + '-' + reference_fields[1], 'subdoc': str(reference_fields[2])}
xml = pd.read_csv('lemma_lookup.csv', sep='\t', encoding='UTF-8',
names=['doc', 'subdoc', 'sentence', 'line', 'word', 'lemma', 'form'],
dtype={'doc': str, 'subdoc': str, 'sentence': int, 'line': str,
'word': int, 'lemma': str, 'form':str})
lsj = pd.read_csv('first1000.csv', sep='\t', encoding='UTF-8', names=['id', 'key', 'sense_1', 'sense_2', 'sense_3',
'sense_4', 'translation', 'ref'],
dtype={'id': int, 'key': str, 'sense_1': str, 'sense_2': str, 'sense_3': int, 'sense_4': str,
'translation': str, 'ref': str})
nb_of_direct_results = 0
nb_of_other_line_results = 0
nb_of_strange_subdoc_results = 0
nb_of_whole_doc_results = 0
lsj['word_id'] = ""
doc_not_found = 0
for row in lsj.itertuples():
reference = row.ref
key = row.key
result = []
if row.Index % 10 == 0:
print(row.Index)
if reference.startswith('urn'):
bibliography = urn_to_ids(reference)
if bibliography['subdoc'].isdigit(): # subdoc is only digits
zero_five_line_number = int(bibliography['subdoc']) // 5 * 5
if zero_five_line_number == 0:
zero_five_line_number = 1
mask = ((xml['doc'].values == bibliography['doc']) &
((xml['subdoc'].values == str(bibliography['subdoc'])) |
(xml['subdoc'].values == str(int(bibliography['subdoc']) - 1)) | # for off-by-ones in subdoc
(xml['subdoc'].values == str(int(bibliography['subdoc']) + 1)) |
(xml['subdoc'].values == str(zero_five_line_number))) &
(xml['lemma'].values == key))
doc_subdoc = xml[mask]
for doc_row in doc_subdoc.itertuples():
word_id = doc_row.word
result.append(str(word_id))
nb_of_direct_results += 1
if bibliography['subdoc'].isalnum() and len(result) == 0: # try line number
zero_five_line_number = int(bibliography['subdoc']) // 5 * 5
if zero_five_line_number == 0:
zero_five_line_number = 1
mask = ((xml['doc'].values == bibliography['doc']) &
((xml['line'].values == str(bibliography['subdoc'])) |
(xml['line'].values == str(int(bibliography['subdoc']) - 1)) | # for off-by-ones in line
(xml['line'].values == str(int(bibliography['subdoc']) + 1)) |
(xml['line'].values == str(zero_five_line_number))) &
(xml['lemma'].values == key))
doc_subdoc = xml[mask]
for doc_row in doc_subdoc.itertuples():
word_id = doc_row.word
result.append(str(word_id))
nb_of_other_line_results += 1
if len(result) == 0 and len(bibliography['subdoc']) > 0: # for subdocs like 1.2.3 or others
mask = ((xml['doc'].values == bibliography['doc']) &
((xml['subdoc'].values == str(bibliography['subdoc'])) |
(xml['subdoc'].values == (bibliography['subdoc'][:-1]))) & # e.g. Plato ... 23b
(xml['lemma'].values == key))
doc_subdoc = xml[mask]
for doc_row in doc_subdoc.itertuples():
word_id = doc_row.word
result.append(str(word_id))
nb_of_strange_subdoc_results += 1
elif len(result) == 0: # if nothing found try whole document
mask = ((xml['doc'].values == bibliography['doc']) &
(xml['lemma'].values == key))
doc_subdoc = xml[mask]
for doc_row in doc_subdoc.itertuples():
word_id = doc_row.word
result.append(str(word_id))
nb_of_whole_doc_results += 1
if len(result) == 0:
mask = (xml['doc'].values == bibliography['doc'])
doc_subdoc = xml[mask]
if doc_subdoc.size == 0:
result.append('Document not found')
doc_not_found += 1
else:
pass # TODO handling of non-urn links!!
print(str(row.Index) + ': ' + ','.join(result))
lsj.at[row.Index, 'word_id'] = result
print("Direct results: " + str(nb_of_direct_results))
print('Line results:' + str(nb_of_other_line_results))
print('Strange subdoc results:' + str(nb_of_strange_subdoc_results))
print('Whole document results: ' + str(nb_of_whole_doc_results))
print("Documents not found: " + str(doc_not_found))
lsj.to_csv('tst/LSJ_2_wid.csv', sep='\t', encoding='UTF-8')
<file_sep>import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
#Load data with vectors
train_df = pd.read_csv('training_data_vectors_arxh.csv', sep= '\t', encoding='UTF-8')
test_df = pd.read_csv('test_data_vectors_arxh.csv', sep= '\t', encoding='UTF-8')
#Convert vector strings to proper floats
train_df['vectors'] = train_df['vectors'].apply(lambda y: [float(x) for x in y.split(', ')])
test_df['vectors'] = test_df['vectors'].apply(lambda y: [float(x) for x in y.split(', ')])
#Initialize random forest
forest = RandomForestClassifier(n_estimators = 25)
#Fit forest to training data
forest = forest.fit(train_df['vectors'].to_list(), train_df['sense_2'].to_list())
#Predict results
result = forest.predict(test_df['vectors'].to_list())
#Print out report
print(classification_report(test_df['sense_2'].to_list(), result))<file_sep>import os
import re
import xml.etree.ElementTree as ET
xml_poetry = ET.parse('parsed_xmls/01 - AllPoetry_parsed.xml')
#
xml_prose = ET.parse('parsed_xmls/02 - AllProse_parsed.xml')
final_csv = open('testcsv.csv', 'w+', encoding='UTF-8')
class Bibliographic:
def __init__(self, book_id: str, word: str, author: str, work: str, subdoc=None):
self.book_id = book_id
self.word = word
self.author = author
self.work = work
self.subdoc = subdoc
def __str__(self):
return self.book_id + '\t' + self.author + ',' + self.work
def find_occurences(self, xml: ET.ElementTree):
xml_root = xml.getroot()
doc_id = self.author + '-' + self.work
result = []
if self.subdoc is not None:
if str(self.subdoc).isdigit():
self.subdoc = int(self.subdoc) - 1
for sentence in xml_root.findall( # check sentences with matching author, work, subdoc
".//sentence[@document_id='{}'][@subdoc='{}']".format(doc_id, self.subdoc)):
for word in sentence[:]:
if "lemma" in word.attrib:
if word.attrib["lemma"] == self.word:
return word.attrib["wid"]
if len(result) == 0: # if none found: check all sentence matching author, work
for sentence in xml_root.findall(".//sentence[@document_id='{}']".format(doc_id, self)):
for word in sentence[:]:
if "lemma" in word.attrib:
if word.attrib["lemma"] == self.word:
result.append(word.attrib["wid"])
return ', '.join(result)
for file in os.listdir('tst'):
with open('tst/' + file, 'r', encoding='UTF-8') as csv:
with open('tst/non_urn.txt', 'w', encoding='UTF-8') as output:
for line in csv.readlines():
line = line.split('\t')
urn = line[7]
if urn.startswith('urn'):
pattern = r".perseus-\w+\d" # remove all text, until you get AUTHOR:WORK:su.bd.oc
urn = re.sub(pattern, '', urn)
reference = ''.join(digit for digit in urn if not digit.isalpha())
reference = reference[3:-1]
reference = reference.replace(':', '.')
reference = reference.replace('.', ':', 2)
reference_fields = reference.split(':')
if len(reference_fields) > 3:
print(line[0])
print(reference)
while len(reference_fields) < 3:
reference_fields.append(None)
biblio = Bibliographic(line[0], line[1], reference_fields[0],
reference_fields[1], str(reference_fields[2]))
line.append(biblio.find_occurences(xml_poetry))
line.append(biblio.find_occurences(xml_prose))
final_csv.write('\t'.join(line) + '\n')
print(line[0])
else:
output.write(line[7])
<file_sep>###### Liddell-Scott Jones Data Scraper
This script provides a collection of CSV-files, containing the translations of the different senses associated with the Greek words in the LSJ.
For each translation, several examples are given.<file_sep>import os
import xml.etree.ElementTree as ET
import pandas as pd
# TEI.2 -> (teiHeader) text -> (front) body -> div0 -> (head) entryFree
# Left out Cyr. <NAME>
def create_abbrev_dict(file): # S. OT. => Sophocles, <NAME>
with open(file, "r+") as abbrev:
lines = abbrev.readlines()
authors_abbrev = {}
for line in lines:
line = line[:-1]
line = line.split('\t')
authors_abbrev[line[1]] = line[0]
return authors_abbrev
authors = create_abbrev_dict("abbrev_authors.csv")
works = create_abbrev_dict("abbrev_works.csv")
works = {v: k for k, v in works.items()}
def create_conversion_dicts():
author_conversion = {} # Sophocles, <NAME> => 0011.004
only_works_conversion = {}
work_conversion = {}
tlg = pd.read_csv('tlg_numbers.csv', sep='\t')
# structure tlg: 0: TLG_AUTHOR 1:TLG_WORK 2:AUTHOR 3:TITLE
for i in tlg.iterrows():
author_conversion[i[1][2]] = i[1][0] # i[0] is the index
for i in tlg.iterrows():
only_works_conversion[i[1][3]] = str(i[1][0]) + ',' + i[1][1]
for i in tlg.iterrows():
key = i[1][2] + ',' + i[1][3]
value = str(i[1][0]) + ',' + i[1][1]
value = value.split(',')
work_conversion[key] = value
return author_conversion, only_works_conversion, work_conversion
author_rows, only_works, work_rows = create_conversion_dicts()
def create_bibliographic_link(author, work, loc):
full_author = ""
work_id = ""
if author is not None:
if author in authors:
full_author = authors[author]
full_author_upper = full_author.upper() # UPPER CASE in tlg_numbers
if full_author_upper in author_rows:
author_id = str(author_rows[full_author_upper])
author_id = author_id.rjust(4, "0") # always 4 characters long
elif full_author in only_works: # For errors like Odyssea which is in authors
both_ids = only_works[full_author]
both_ids = both_ids.split(',')
author_id = both_ids[0]
author_id = author_id.rjust(4, "0")
work_id = both_ids[1]
else:
file = open('unknown_authors.txt', 'a')
file.write(full_author + '\n')
file.close()
return full_author
else:
return author
else:
author_id = "0000"
if work is not None:
try:
full_work = works[work]
combined = full_author + ',' + full_work
if combined in work_rows:
work_id = work_rows[combined][1]
else:
work_id = "001"
except KeyError:
work_id = "001"
if work_id == "":
work_id = "001"
if loc is not None:
loc_id = str(loc)
else:
loc_id = ""
return "urn:cts:greekLit:tlg{}.tlg{}.perseus-grc1:{}".format(author_id, work_id, loc_id)
def main():
# authors = create_abbrev_dict("abbrev_authors.csv")
# works = create_abbrev_dict("abbrev_works.csv")
for i, letter in enumerate(os.listdir('LSJ_data')):
title = 'LSJ_{}.csv'.format(i + 1)
with open('LSJ_output/' + title, "w+", encoding='UTF-8') as file:
my_tree = ET.parse("LSJ_data/" + letter)
my_root = my_tree.getroot()
if i == 0:
words = my_root[1][1][0][1:] # TEI.2 -> (teiHeader) text -> (front) body -> div0 -> (head) entryFree
else:
words = my_root[1][0][0][1:] # TEI.2 -> (teiHeader) text -> body -> div0 -> (head) entryFree
for j, word in enumerate(words):
if word.tag != 'entryFree':
continue
else:
if j % 1000 == 0:
print("book {}/{}, word {}/{}".format(i + 1, len((os.listdir("LSJ_data"))), j, len(words)))
previous_sense_levels = ['A', 'I', '1', 'a']
word_id = word.attrib['id']
key = word.attrib['key']
senses = word.findall("sense")
for sense in senses:
default = ['A', 'I', '1', 'a']
name = sense.attrib['n']
level = sense.attrib['level']
sense_levels = previous_sense_levels[:int(level) - 1] + [name] + default[int(level):]
previous_sense_levels = sense_levels
translation = ""
bib_key = ""
translation_counter = 0
for element in sense[:]: # skips the 'etymological' info
if element.tag == 'tr' and translation_counter == 0:
translation = element.text
if bib_key != "":
file.write(
word_id[1:] + '\t' + key + '\t' + "\t".join(
sense_levels) + "\t" + translation + "\t" + bib_key + "\n")
translation_counter += 1
if element.tag == 'bibl': # bibliography without citations
bib_key = ""
if element.text is not None:
if 'n' in element.attrib:
bib_key += element.attrib['n']
else:
link = [None] * 3
for child in element[:]:
if child.text is not None:
if child.text in authors:
link[0] = child.text
elif child.text in works:
link[1] = child.text
elif child.text.isnumeric():
link[2] = child.text
bib_key = create_bibliographic_link(link[0], link[1], link[2])
if translation_counter > 0:
file.write(
word_id[1:] + '\t' + key + '\t' + "\t".join(
sense_levels) + "\t" + translation + "\t" + bib_key + "\n")
if element.tag == 'cit': # bibliography for citations
book = element.find('bibl')
bib_key = ""
if book is not None:
if 'n' in book.attrib:
bib_key += book.attrib['n']
else:
link = [None] * 3
for child in book[:]:
if child.text is not None:
if child.text in authors:
link[0] = child.text
elif child.text in works:
link[1] = child.text
elif child.text.isnumeric():
link[2] = child.text
bib_key = create_bibliographic_link(link[0], link[1], link[2])
if translation_counter > 0:
file.write(
word_id[1:] + '\t' + key + '\t' + "\t".join(
sense_levels) + "\t" + translation + "\t" + bib_key + "\n")
main()
<file_sep>import pandas as pd
import os
import re
pattern = r".perseus-\w+\d" # to remove .perseus-grc1 etc.
def urn_to_ids(ref: str): # Returns a string: doc \t subdoc
temp_ref = re.sub(pattern, '', ref)
temp_ref = ''.join(digit for digit in temp_ref if not digit.isalpha()) # removes other non-numerics
temp_ref = temp_ref[3:] # removes initial :
temp_ref = temp_ref.replace(':', '.') # removes remaining :
cleaned_ref = temp_ref.replace('.', ':', 2) # split between author/work/subdoc is : otherwise .
reference_fields = cleaned_ref.split(':')
while len(reference_fields) < 3:
reference_fields.append(None)
return reference_fields[0] + '-' + str(reference_fields[1]) + '\t' + str(reference_fields[2])
xml = pd.read_csv('lemma_lookup.csv', sep='\t', encoding='UTF-8',
names=['doc', 'subdoc', 'sentence', 'line', 'word', 'lemma', 'form'],
dtype={'doc': str, 'subdoc': str, 'sentence': int, 'line': str,
'word': str, 'lemma': str, 'form':str})
xml['subdocstring'] = xml['subdoc'] # extra column to store non-numeric subdocs
xml['subdoc'] = pd.to_numeric(xml['subdoc'], errors='coerce', downcast='float') # same process as lsj
xml['line'] = pd.to_numeric(xml['line'], errors='coerce', downcast='float') # cf supra
for index in range(len(os.listdir('LSJ_output'))):
print(index + 1)
file = open('LSJ_output/LSJ_{}.csv'.format(index + 1), encoding='UTF-8')
if len(file.readlines()) < 2:
file.close()
continue
else:
file.close()
lsj = pd.read_csv('LSJ_output/LSJ_{}.csv'.format(index + 1), sep='\t', encoding='UTF-8',
names=['id', 'key', 'sense_1', 'sense_2', 'sense_3', 'sense_4', 'translation', 'ref'],
dtype={'id': int, 'key': str, 'sense_1': str, 'sense_2': str, 'sense_3': int, 'sense_4': str,
'translation': str, 'ref': str})
lsj['ref'] = lsj['ref'].apply(urn_to_ids) # removes the unwieldy urn
split = lsj['ref'].str.split('\t', expand=True)
lsj = pd.concat([lsj, split], axis=1) # new reference in dataframe
lsj.rename(columns={'key': 'lemma', 0: 'doc', 1: 'subdoc'}, inplace=True) # rename columns to match with xml
lsj['lemma'] = lsj['lemma'].str.replace('\d+', '') # removing unwanted digits in lemmata
lsj['subdoc'] = pd.to_numeric(lsj['subdoc'], errors='coerce',
downcast='float') # merge_asof needs numbers, bonus: subdocs like 1.3 become floats
lsj.sort_values(by=['subdoc'], inplace=True) # sorting for the merge_asof
# TRY TO MERGE ON SUBDOC
xml.sort_values(by=['subdoc'], inplace=True)
subdoc_merge = pd.merge_asof(lsj[lsj['subdoc'].notna()], xml[xml['subdoc'].notna()],
on=['subdoc'], by=['lemma', 'doc'], tolerance=4)
# merge on subdoc, with tolerance 4 for lines numbered per 5
# TRY TO MERGE ON LINE NUMBER
lsj.rename(columns={'subdoc': 'line'}, inplace=True) # rename columns to match with xml
xml.sort_values(by=['line'], inplace=True)
line_merge = pd.merge_asof(lsj[lsj['line'].notna()], xml[xml['line'].notna()],
on=['line'], by=['lemma', 'doc'], tolerance=4)
# merge on line, with tolerance 4 for lines numbered per 5
# TRY TO MERGE SOLELY ON DOC NUMBER
doc_merge = pd.merge(lsj[lsj['doc'].notna()], xml[xml['doc'].notna()], on=['doc', 'lemma'])
# test = subdoc_merge[subdoc_merge['word'].notnull()]
# test_line = line_merge[line_merge['word'].notnull()]
# COMBINE RESULTS
subdoc_merge.fillna(line_merge, inplace=True) # fills remaining NaN results from lines
# subdoc_merge.fillna(subdoc_merge_docs, inplace=True)
failed_merge = subdoc_merge[subdoc_merge['word'].isnull()] # no words found
words_in_docs = doc_merge.groupby(['id', 'lemma', 'sense_1', 'sense_2', 'sense_3', 'sense_4', 'doc'],
as_index=False).agg({'word': lambda x: str(list(x))})
# Words grouped per document per sense
only_in_docs = failed_merge.drop(columns=['word']).merge(words_in_docs, 'left',
on=['id', 'lemma', 'sense_1', 'sense_2',
'sense_3', 'sense_4', 'doc'])
# Combine failed_merge (words not yet found) with the words found in docs
# CONCATENATE RESULTS
subdoc_line_hits = subdoc_merge[subdoc_merge['word'].notnull()]
# As the words found in docs are taken from failed_merge (which contains the isnull values)
# we should remove them here
combined = pd.concat([subdoc_line_hits, only_in_docs])
# Sorting for better readability
combined.sort_values(by=['id', 'sense_1', 'sense_2', 'sense_3', 'sense_4'], inplace=True)
lsj.sort_values(by=['id', 'sense_1', 'sense_2', 'sense_3', 'sense_4'], inplace=True)
# Merge to return a dataframe like the first lsj, but with the referenced words
result = lsj.rename(columns={'line': 'subdoc'}).merge(combined, how='left',
on=['id', 'lemma', 'sense_1', 'sense_2', 'sense_3', 'sense_4',
'translation', 'ref', 'doc', 'subdoc'])
result.drop(columns=['ref', 'subdocstring'], inplace=True) # remove redundant columns
result['word'] = result['word'].dropna().apply(lambda x: list(map(int, x.strip('[]\'\'').split('\', \''))))
# converting strings to lists of ints, by stripping brackets and quotes, and splitting on "', '"
result.to_csv('LSJ_words/LSJ_{}_words.csv'.format(index + 1), sep='\t', encoding='UTF-8') # write to csv
# TESTING
# test = subdoc_merge[subdoc_merge['word'].notnull()]
# test_line = line_merge[line_merge['word'].notnull()]
# test_only_in_docs = only_in_docs[only_in_docs['word'].notnull()]
# test_result = result[result['word'].notnull()]
<file_sep>import pandas as pd
combined_senses = pd.read_excel('senses_test_data_arxh.xlsx')
combined_senses.drop(columns=['Column1', 'sentence', 'line', 'context'], inplace=True)
test_vector = pd.read_csv('vectors_test_arxh.csv', sep='\t', encoding='UTF-8', header=None)
## Concatenate the 100 vectors into one df.column
concat_test_vector = test_vector.loc[:, 1].astype(str) + ', ' + test_vector.loc[:, 2].astype(str)
for i in range(98): #100 vectors expected
concat_test_vector = concat_test_vector + ', ' + test_vector.loc[:, i + 2].astype(str)
test_vector_df = test_vector.loc[:, 0].to_frame()
test_vector_df['vectors'] = concat_test_vector
test_vector_df.columns = ['word', 'vectors']
test_vector_df['word'] = test_vector_df['word'].apply(lambda x: x - 1)
final_test_data = pd.merge(combined_senses, test_vector_df, on='word')
final_test_data.to_csv('test_data_vectors_arxh.csv', sep='\t', encoding='UTF-8')<file_sep>import pandas as pd
import unicodedata as ucd
# chosen_words = ['εἰς', 'λέγω', 'ἄλλος', 'πόλις', 'οὐδείς', 'ὦ', 'λαμβάνω', 'ἔτι', 'παῖς', 'ἀγαθός']
chosen_words = ['ἀρχή']
position_in_alphabet = {'α': '1', 'β': '2', 'γ': '3', 'δ': '4', 'ε': '5', 'ζ': '7', 'η': '8', 'θ': '9',
'ι': '10', 'κ': '11', 'λ': '12', 'μ': '13', 'ν': '14', 'ξ': '15', 'ο': '16',
'π': '17', 'ρ': '20', 'σ': '21', 'τ': '22', 'υ': '23', 'φ': '24', 'χ': '25',
'ψ': '26', 'ω': '27'} # watch out for combined accents and accents integrated in the character
def first_letter_without_accents(word: str):
norm_word = ucd.normalize('NFKD', word)
return norm_word[0]
training_vector = pd.read_csv('vectors_training_arxh.csv', sep='\t', encoding='UTF-8', header=None)
## Concatenate the 100 vectors into one df.column
concat_training_vector = training_vector.loc[:,1].astype(str) + ', ' + training_vector.loc[:,2].astype(str)
for i in range(98): #100 vectors expected
concat_training_vector = concat_training_vector + ', ' + training_vector.loc[:, i + 2].astype(str)
training_vector_df = training_vector.loc[:, 0].to_frame()
training_vector_df['vectors'] = concat_training_vector
training_vector_df.columns = ['word', 'vectors']
training_vector_df['word'] = training_vector_df['word'].apply(lambda x: x - 1)
all_chosen_word_lsj = []
for chosen_word in chosen_words:
print(chosen_word)
position = position_in_alphabet[first_letter_without_accents(chosen_word)]
lsj = pd.read_csv('LSJ_words/LSJ_{}_words.csv'.format(position), sep='\t', encoding='UTF-8')
chosen_word_lsj = lsj[lsj['lemma'] == chosen_word] #filter on word
chosen_word_lsj['word'] = chosen_word_lsj['word'].dropna().apply(
lambda x: list(map(int, x.strip('[]\'\'').split(', ')))) #convert strings of lists to actual lists
cleaned_word_lsj = chosen_word_lsj[(chosen_word_lsj.word.str.len() <= 3)].explode('word')
#drop excessively long lists and explodes the lists into rows
all_chosen_word_lsj.append(cleaned_word_lsj)
senses_df = pd.concat(all_chosen_word_lsj)
senses_df.drop(columns=['Unnamed: 0', 'id', 'doc', 'subdoc', 'sentence', 'line'], inplace=True)
xml = pd.read_csv('lemma_lookup.csv', sep='\t', encoding='UTF-8',
names=['doc', 'subdoc', 'sentence', 'line', 'word', 'lemma', 'form'],
dtype={'doc': str, 'subdoc': str, 'sentence': int, 'line': str,
'word': int, 'lemma': str, 'form': str})
chosen_xml = xml[xml['lemma'].isin(chosen_words)]
chosen_xml.drop(columns=['sentence', 'line'], inplace=True)
combined_senses = pd.merge(chosen_xml, senses_df, on=['word', 'lemma', 'form'])
final_training_data = pd.merge(combined_senses, training_vector_df, on='word')
final_training_data.to_csv('training_data_vectors_arxh.csv', sep='\t', encoding='UTF-8')
<file_sep>import xml.etree.ElementTree as Et
import re
# TEI.2 -> (teiHeader) text -> front -> (pref) (post) (0) 1 -> (head) p -> list
with open("LSJ_data/grc.lsj.perseus-eng01.xml", encoding='UTF-8') as file:
tree = Et.parse(file)
root = tree.getroot()
authors = root[1][0][3][1][0]
# with open('abbrev_authors.csv', 'w+') as output:
# for author in authors[:]:
# if len(author) > 0:
#
# name = author[0].text
# info = author[0].tail
#
# if '=' not in info and '=' not in name:
#
# m = re.search(r"\[(.*?)]", info)
#
# if m:
# abbrev = m.group(1)
#
# output.write(name + '\t' + abbrev + '\n')
with open('abbrev_works.csv', 'w+') as output:
for author in authors[:]:
if len(author) > 0:
name = author[0].text
tail = author[0].tail
if '=' in name:
name = name.split(" = ")
if len(name) == 2:
output.write(name[0] + '\t' + name[1] + '\n')
if '=' in tail:
tail = tail.split(" = ")
if len(tail) == 2:
output.write(tail[0] + '\t' + tail[1] + '\n')<file_sep>import pandas as pd
import numpy as np
from sklearn.metrics import pairwise_distances
from scipy.spatial.distance import cosine
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import seaborn as sns
def visualize(data, lemma):
df = pd.read_csv('{}_vectors_arxh.csv'.format(data), sep= '\t', encoding='UTF-8')
df = df[df['lemma'] == lemma]
df['vectors'] = df['vectors'].apply(lambda y: [float(x) for x in y.split(', ')])
# cosine_dist = pairwise_distances(np.array(df.vectors.to_list()), metric="cosine")
tsne = TSNE(n_components=2, perplexity=5, n_iter=5000, metric='cosine')
tsne_results = tsne.fit_transform(df.vectors.to_list())
df['tsne-2d-one'] = tsne_results[:,0]
df['tsne-2d-two'] = tsne_results[:,1]
plt.figure(figsize=(16,10))
sns.scatterplot(
x="tsne-2d-one", y="tsne-2d-two",
hue="sense_2",
style="sense_2",
palette=sns.color_palette("hls", df.sense_2.unique().shape[0]),
data=df,
legend="full"
)
visualize('training_data', 'ἀρχή')
| b24e228756aba2a0595d4848a30690f31ea3ca16 | [
"Markdown",
"Python"
] | 12 | Python | mercelisw/Databank_LSJ | 2a14b915dacf1d9014196879317360184e77c48b | d7affc5859c829b621c8e0e3e8c75da9d5347e98 |
refs/heads/master | <file_sep>from django.contrib import admin
from contacts.models import Contacts,UserInfo
admin.site.register(Contacts)
admin.site.register(UserInfo)
<file_sep>from django.db import models
class Contacts(models.Model):
sex_choice = (
("M" , "Male"),
("F" , "Femali"),
("I" , "InterSex"),
)
username = models.CharField(max_length=255, unique=True)
company = models.CharField(max_length=255, verbose_name="Kompaniya")
post = models.CharField(max_length=100, verbose_name="Doljnost" )
linkedin = models.CharField(max_length=255)
sex = models.CharField(max_length=20, choices=sex_choice)
site = models.CharField(max_length=255)
def __str__(self):
return f"{self.username}"
class UserInfo(models.Model):
contact = models.ForeignKey(Contacts, on_delete=models.CASCADE, related_name='contact')
mnumber = models.CharField(max_length=15, unique=True)
email = models.EmailField(max_length=255, unique=True)
# def __str__(self):
# return f"number - {self.mnumber} email - {self.email}"
<file_sep>from django.db import models
from django.db.models.base import Model
from rest_framework import serializers
from contacts.models import Contacts,UserInfo
class GetUserInfoSerializer(serializers.ModelSerializer):
class Meta:
model = UserInfo
fields = ['mnumber', 'email']
class UserInfoCRUDSerializer(serializers.ModelSerializer):
class Meta:
model = UserInfo
fields = '__all__'
class GetContactsSerializer(serializers.ModelSerializer):
contact = GetUserInfoSerializer(many=True)
class Meta:
model = Contacts
fields = '__all__'
<file_sep># Generated by Django 3.1.1 on 2021-07-17 13:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contacts',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('username', models.CharField(max_length=255, unique=True)),
('company', models.CharField(max_length=255, verbose_name='Kompaniya')),
('post', models.CharField(max_length=100, verbose_name='Doljnost')),
('linkedin', models.CharField(max_length=255)),
('sex', models.CharField(choices=[('M', 'Male'), ('F', 'Femali'), ('I', 'InterSex')], max_length=20)),
('site', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='UserInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mnumber', models.CharField(max_length=15, unique=True)),
('email', models.EmailField(max_length=255, unique=True)),
('contact', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.contacts')),
],
),
]
<file_sep>from django.contrib import admin
from django.urls import path,include
from contacts.views import (
index,
ContactInfoView,
ContactDetailView,
ContactPutView,
UserInfoPostView,
UserInfoCRUDView,
ContactSearchView,
ContactSearchView )
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework import permissions
from django.conf.urls import url
schema_view = get_schema_view(
openapi.Info(
title="invests API",
default_version='v1',
description="API for invest applications",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="<EMAIL>"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
path('', index, name='home-page'),
path('list/', ContactInfoView.as_view(), name='list-contacts'),
path('post/', ContactDetailView.as_view(), name='post-contacts'),
path('put/<int:pk>', ContactPutView.as_view(), name='put-contacts'),
path('userinfo/post/', UserInfoPostView.as_view(), name='post-userinfo'),
path('userinfo/put/<int:pk>', UserInfoCRUDView.as_view(), name='put-userinfo'),
path('search/<str:search>', ContactSearchView.as_view(), name='search-api' ),
]
<file_sep>from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView,RetrieveUpdateDestroyAPIView
from rest_framework.permissions import IsAuthenticated,IsAdminUser
from contacts.serializer import GetContactsSerializer,GetUserInfoSerializer,UserInfoCRUDSerializer
from contacts.models import Contacts,UserInfo
from rest_framework.response import Response
from rest_framework.views import APIView
def index(request):
content = Contacts.objects.raw("SELECT * FROM public.contacts_contacts c , public.contacts_userinfo i WHERE c.id = i.contact_id ORDER BY c.username")
return render(request,'contacts/index.html', {'contacts' : content})
class ContactInfoView(ListAPIView):
queryset = Contacts.objects.all()
serializer_class = GetContactsSerializer
class ContactDetailView(CreateAPIView):
queryset = Contacts.objects.all()
serializer_class = GetContactsSerializer
class ContactPutView(RetrieveUpdateDestroyAPIView):
queryset = Contacts.objects.all()
serializer_class = UserInfoCRUDSerializer
class UserInfoPostView(CreateAPIView):
queryset = UserInfo.objects.all()
serializer_class = UserInfoCRUDSerializer
class UserInfoCRUDView(RetrieveUpdateDestroyAPIView):
queryset = UserInfo.objects.all()
serializer_class = UserInfoCRUDSerializer
class ContactSearchView(APIView):
def get_queryset(self):
contact = Contacts.objects.all()
return contact
def get(self, request, search):
queryset = Contacts.objects.filter(username__contains=search)
serializer = GetContactsSerializer(queryset, many=True )
return Response(serializer.data)<file_sep>--
-- PostgreSQL database dump
--
-- Dumped from database version 12.7 (Ubuntu 12.7-0ubuntu0.20.04.1)
-- Dumped by pg_dump version 12.7 (Ubuntu 12.7-0ubuntu0.20.04.1)
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: postgis; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS postgis WITH SCHEMA public;
--
-- Name: EXTENSION postgis; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION postgis IS 'PostGIS geometry, geography, and raster spatial types and functions';
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: auth_group; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.auth_group (
id integer NOT NULL,
name character varying(150) NOT NULL
);
ALTER TABLE public.auth_group OWNER TO akmal;
--
-- Name: auth_group_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.auth_group_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_group_id_seq OWNER TO akmal;
--
-- Name: auth_group_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.auth_group_id_seq OWNED BY public.auth_group.id;
--
-- Name: auth_group_permissions; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.auth_group_permissions (
id integer NOT NULL,
group_id integer NOT NULL,
permission_id integer NOT NULL
);
ALTER TABLE public.auth_group_permissions OWNER TO akmal;
--
-- Name: auth_group_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.auth_group_permissions_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_group_permissions_id_seq OWNER TO akmal;
--
-- Name: auth_group_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.auth_group_permissions_id_seq OWNED BY public.auth_group_permissions.id;
--
-- Name: auth_permission; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.auth_permission (
id integer NOT NULL,
name character varying(255) NOT NULL,
content_type_id integer NOT NULL,
codename character varying(100) NOT NULL
);
ALTER TABLE public.auth_permission OWNER TO akmal;
--
-- Name: auth_permission_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.auth_permission_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_permission_id_seq OWNER TO akmal;
--
-- Name: auth_permission_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.auth_permission_id_seq OWNED BY public.auth_permission.id;
--
-- Name: auth_user; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.auth_user (
id integer NOT NULL,
password character varying(128) NOT NULL,
last_login timestamp with time zone,
is_superuser boolean NOT NULL,
username character varying(150) NOT NULL,
first_name character varying(150) NOT NULL,
last_name character varying(150) NOT NULL,
email character varying(254) NOT NULL,
is_staff boolean NOT NULL,
is_active boolean NOT NULL,
date_joined timestamp with time zone NOT NULL
);
ALTER TABLE public.auth_user OWNER TO akmal;
--
-- Name: auth_user_groups; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.auth_user_groups (
id integer NOT NULL,
user_id integer NOT NULL,
group_id integer NOT NULL
);
ALTER TABLE public.auth_user_groups OWNER TO akmal;
--
-- Name: auth_user_groups_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.auth_user_groups_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_user_groups_id_seq OWNER TO akmal;
--
-- Name: auth_user_groups_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.auth_user_groups_id_seq OWNED BY public.auth_user_groups.id;
--
-- Name: auth_user_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.auth_user_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_user_id_seq OWNER TO akmal;
--
-- Name: auth_user_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.auth_user_id_seq OWNED BY public.auth_user.id;
--
-- Name: auth_user_user_permissions; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.auth_user_user_permissions (
id integer NOT NULL,
user_id integer NOT NULL,
permission_id integer NOT NULL
);
ALTER TABLE public.auth_user_user_permissions OWNER TO akmal;
--
-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.auth_user_user_permissions_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_user_user_permissions_id_seq OWNER TO akmal;
--
-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.auth_user_user_permissions_id_seq OWNED BY public.auth_user_user_permissions.id;
--
-- Name: contacts_contacts; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.contacts_contacts (
id integer NOT NULL,
username character varying(255) NOT NULL,
company character varying(255) NOT NULL,
post character varying(100) NOT NULL,
linkedin character varying(255) NOT NULL,
sex character varying(20) NOT NULL,
site character varying(255) NOT NULL
);
ALTER TABLE public.contacts_contacts OWNER TO akmal;
--
-- Name: contacts_contacts_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.contacts_contacts_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.contacts_contacts_id_seq OWNER TO akmal;
--
-- Name: contacts_contacts_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.contacts_contacts_id_seq OWNED BY public.contacts_contacts.id;
--
-- Name: contacts_userinfo; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.contacts_userinfo (
id integer NOT NULL,
mnumber character varying(15) NOT NULL,
email character varying(255) NOT NULL,
contact_id integer NOT NULL
);
ALTER TABLE public.contacts_userinfo OWNER TO akmal;
--
-- Name: contacts_userinfo_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.contacts_userinfo_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.contacts_userinfo_id_seq OWNER TO akmal;
--
-- Name: contacts_userinfo_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.contacts_userinfo_id_seq OWNED BY public.contacts_userinfo.id;
--
-- Name: django_admin_log; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.django_admin_log (
id integer NOT NULL,
action_time timestamp with time zone NOT NULL,
object_id text,
object_repr character varying(200) NOT NULL,
action_flag smallint NOT NULL,
change_message text NOT NULL,
content_type_id integer,
user_id integer NOT NULL,
CONSTRAINT django_admin_log_action_flag_check CHECK ((action_flag >= 0))
);
ALTER TABLE public.django_admin_log OWNER TO akmal;
--
-- Name: django_admin_log_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.django_admin_log_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.django_admin_log_id_seq OWNER TO akmal;
--
-- Name: django_admin_log_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.django_admin_log_id_seq OWNED BY public.django_admin_log.id;
--
-- Name: django_content_type; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.django_content_type (
id integer NOT NULL,
app_label character varying(100) NOT NULL,
model character varying(100) NOT NULL
);
ALTER TABLE public.django_content_type OWNER TO akmal;
--
-- Name: django_content_type_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.django_content_type_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.django_content_type_id_seq OWNER TO akmal;
--
-- Name: django_content_type_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.django_content_type_id_seq OWNED BY public.django_content_type.id;
--
-- Name: django_migrations; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.django_migrations (
id integer NOT NULL,
app character varying(255) NOT NULL,
name character varying(255) NOT NULL,
applied timestamp with time zone NOT NULL
);
ALTER TABLE public.django_migrations OWNER TO akmal;
--
-- Name: django_migrations_id_seq; Type: SEQUENCE; Schema: public; Owner: akmal
--
CREATE SEQUENCE public.django_migrations_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.django_migrations_id_seq OWNER TO akmal;
--
-- Name: django_migrations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: akmal
--
ALTER SEQUENCE public.django_migrations_id_seq OWNED BY public.django_migrations.id;
--
-- Name: django_session; Type: TABLE; Schema: public; Owner: akmal
--
CREATE TABLE public.django_session (
session_key character varying(40) NOT NULL,
session_data text NOT NULL,
expire_date timestamp with time zone NOT NULL
);
ALTER TABLE public.django_session OWNER TO akmal;
--
-- Name: auth_group id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group ALTER COLUMN id SET DEFAULT nextval('public.auth_group_id_seq'::regclass);
--
-- Name: auth_group_permissions id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group_permissions ALTER COLUMN id SET DEFAULT nextval('public.auth_group_permissions_id_seq'::regclass);
--
-- Name: auth_permission id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_permission ALTER COLUMN id SET DEFAULT nextval('public.auth_permission_id_seq'::regclass);
--
-- Name: auth_user id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user ALTER COLUMN id SET DEFAULT nextval('public.auth_user_id_seq'::regclass);
--
-- Name: auth_user_groups id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_groups ALTER COLUMN id SET DEFAULT nextval('public.auth_user_groups_id_seq'::regclass);
--
-- Name: auth_user_user_permissions id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_user_permissions ALTER COLUMN id SET DEFAULT nextval('public.auth_user_user_permissions_id_seq'::regclass);
--
-- Name: contacts_contacts id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_contacts ALTER COLUMN id SET DEFAULT nextval('public.contacts_contacts_id_seq'::regclass);
--
-- Name: contacts_userinfo id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_userinfo ALTER COLUMN id SET DEFAULT nextval('public.contacts_userinfo_id_seq'::regclass);
--
-- Name: django_admin_log id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_admin_log ALTER COLUMN id SET DEFAULT nextval('public.django_admin_log_id_seq'::regclass);
--
-- Name: django_content_type id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_content_type ALTER COLUMN id SET DEFAULT nextval('public.django_content_type_id_seq'::regclass);
--
-- Name: django_migrations id; Type: DEFAULT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_migrations ALTER COLUMN id SET DEFAULT nextval('public.django_migrations_id_seq'::regclass);
--
-- Data for Name: auth_group; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.auth_group (id, name) FROM stdin;
\.
--
-- Data for Name: auth_group_permissions; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.auth_group_permissions (id, group_id, permission_id) FROM stdin;
\.
--
-- Data for Name: auth_permission; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.auth_permission (id, name, content_type_id, codename) FROM stdin;
1 Can add log entry 1 add_logentry
2 Can change log entry 1 change_logentry
3 Can delete log entry 1 delete_logentry
4 Can view log entry 1 view_logentry
5 Can add permission 2 add_permission
6 Can change permission 2 change_permission
7 Can delete permission 2 delete_permission
8 Can view permission 2 view_permission
9 Can add group 3 add_group
10 Can change group 3 change_group
11 Can delete group 3 delete_group
12 Can view group 3 view_group
13 Can add user 4 add_user
14 Can change user 4 change_user
15 Can delete user 4 delete_user
16 Can view user 4 view_user
17 Can add content type 5 add_contenttype
18 Can change content type 5 change_contenttype
19 Can delete content type 5 delete_contenttype
20 Can view content type 5 view_contenttype
21 Can add session 6 add_session
22 Can change session 6 change_session
23 Can delete session 6 delete_session
24 Can view session 6 view_session
25 Can add contacts 7 add_contacts
26 Can change contacts 7 change_contacts
27 Can delete contacts 7 delete_contacts
28 Can view contacts 7 view_contacts
29 Can add user info 8 add_userinfo
30 Can change user info 8 change_userinfo
31 Can delete user info 8 delete_userinfo
32 Can view user info 8 view_userinfo
\.
--
-- Data for Name: auth_user; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.auth_user (id, <PASSWORD>, last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined) FROM stdin;
1 pbkdf2_sha256$216000$UcPhxbtxHH6Y$ob3I5CKWdgQ4/V61HEh67OOyqoKyKccqquoHIuDktjE= 2021-07-18 01:15:52.922251+05 t admin <EMAIL> t t 2021-07-18 01:15:00.157953+05
\.
--
-- Data for Name: auth_user_groups; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.auth_user_groups (id, user_id, group_id) FROM stdin;
\.
--
-- Data for Name: auth_user_user_permissions; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.auth_user_user_permissions (id, user_id, permission_id) FROM stdin;
\.
--
-- Data for Name: contacts_contacts; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.contacts_contacts (id, username, company, post, linkedin, sex, site) FROM stdin;
1 <NAME> Uzbektelecom Injener programmist None M None
2 <NAME> None Uy bekasi None F None
3 <NAME> Uzbektelecom MM E bo'lim muxandis yuq F uzonline.uz
4 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i yuq M uzonline.uz
5 <NAME> TTR.E bo'limmuhandis uzbektelecom yuq M uzonline.uz
6 <NAME> TTR.E bo'lim muhandis uzbektelecom yuq F uzonline.uz
7 <NAME> TX . P bo'lim boshlig'i uzbektelecom yuq M uzonline.uz
8 <NAME> Billing M bo'limi boshlig'i uzbektelecom yuq M uzonline.uz
9 <NAME> Billing M Bo'lim muhandis uzbektelecom yuq F uzonline.uz
10 <NAME> Billing M Bo'lim muhandis uzbektelecom yuq F uzonline.uz
11 <NAME> Billing M bo'limi boshlig'i uzbektelecom yuq M uzonline.uz
12 <NAME> loyihalshtirish uzbektelecom yuq M uzonline.uz
13 <NAME> Kadastr bo'lim boshlig'i uzbektelecom yuq M uzonline.uz
14 <NAME> Kadastr bo'lim 1-toifali muhandis uzbektelecom yuq M uzonline.uz
15 <NAME> Mijozlar bilan ishlash uzbektelecom yuq M uzonline.uz
16 <NAME> mijozlar bilan ishlash uzbektelecom yuq F uzonline.uz
17 <NAME> Kadastr bo'lim boshlig'i uzbektelecom yuq F uzonline.uz
18 <NAME> loyihalshtirish uzbektelecom yuq F uzonline.uz
19 <NAME> Billing M bo'limi boshlig'i uzbektelecom yuq F uzonline.uz
20 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i None F uzonline.uz
21 <NAME> Uzbektelecom Injener programmist yuq M uzonline.uz
22 <NAME> Uzbektelecom MM E bo'lim muxandis yuq F uzonline.uz
23 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i yuq F uzonline.uz
24 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i yuq F uzonline.uz
25 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i yuq F uzonline.uz
26 <NAME> Billing M bo'limi boshlig'i uzbektelecom yuq F uzonline.uz
27 <NAME> Billing M Bo'lim muhandis uzbektelecom yuq F uzonline.uz
28 <NAME> Billing M Bo'lim muhandis uzbektelecom None F uzonline.uz
29 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i yuq M uzonline.uz
30 Toshpo'latova Feruza Kadastr bo'lim 1-toifali muhandis uzbektelecom yuq F uzonline.uz
31 <NAME> Billing M Bo'lim muhandis uzbektelecom yuq M uzonline.uz
32 <NAME> Billing M Bo'lim muhandis uzbektelecom yuq M uzonline.uz
33 <NAME> loyihalshtirish uzbektelecom None M uzonline.uz
34 <NAME> Billing M Bo'lim muhandis uzbektelecom yuq M uzonline.uz
35 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i yuq F uzonline.uz
36 <NAME> Kadastr bo'lim 1-toifali muhandis uzbektelecom yuq M uzonline.uz
37 <NAME> Kadastr bo'lim boshlig'i uzbektelecom yuq F uzonline.uz
38 <NAME> TTB etakchi mutaxasis uzbektelecom yuq M uzonline.uz
39 <NAME> Kadastr bo'lim boshlig'i uzbektelecom yuq F uzonline.uz
40 <NAME> Uzbektelecom Injener programmist yuq F uzonline.uz
41 <NAME> loyihalshtirish uzbektelecom yuq M uzonline.uz
42 <NAME> Uzbektelecom Injener programmist yuq F uzonline.uz
43 <NAME> Uzbektelecom TTR . E bo'lim boshlig'i yuq F uzonline.uz
44 <NAME> Uzbektelecom Injener programmist None F uzonline.uz
45 <NAME> Uzbektelecom Injener programmist yuq M uzonline.uz
46 <NAME> Uzbektelecom MM E bo'lim muxandis yuq M uzonline.uz
47 <NAME> loyihalshtirish uzbektelecom yuq M uzonline.uz
48 <NAME> Uzbektelecom Uchastka Boshliq yuq F uzonline.uz
49 <NAME> Uzbektelecom Uchastka Boshliq None F uzonline.uz
\.
--
-- Data for Name: contacts_userinfo; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.contacts_userinfo (id, mnumber, email, contact_id) FROM stdin;
1 +998973226755 <EMAIL> 1
2 +998993606237 <EMAIL> 1
3 +998993606238 <EMAIL> 2
4 997509035 <EMAIL> 3
5 997508885 <EMAIL> 4
6 997500758 <EMAIL> 5
7 997517039 <EMAIL> 6
8 997508388 <EMAIL> 7
9 997532121 <EMAIL> 8
10 997503649 <EMAIL> 9
11 997501773 <EMAIL> 10
12 997528142 <EMAIL> 11
13 933006898 <EMAIL> 12
14 997506160 <EMAIL> 13
15 997404035 <EMAIL> 14
16 993610001 <EMAIL> 15
17 997561007 <EMAIL> 16
18 997556557 <EMAIL> 17
19 994554433 <EMAIL> 18
20 997520252 <EMAIL> 19
21 997514508 <EMAIL> 20
22 995745201 <EMAIL> 21
23 990820331 <EMAIL> 22
24 932810091 <EMAIL> 23
25 997556001 <EMAIL> 24
26 997558024 <EMAIL> 25
27 997505662 <EMAIL> 26
28 997582106 <EMAIL> 27
29 997556214 <EMAIL> 28
30 997535577 <EMAIL> 29
31 995757775 <EMAIL> 30
32 995874625 <EMAIL> 31
33 997530306 <EMAIL> 32
34 998337988 <EMAIL> 33
35 997505892 <EMAIL> 34
36 997420949 <EMAIL> 35
37 997576025 <EMAIL> 36
38 995576460 <EMAIL> 37
39 997507767 <EMAIL> 38
40 997575788 <EMAIL> 39
41 997520159 <EMAIL> 40
42 997859691 <EMAIL> 41
43 997537645 <EMAIL> 42
44 997558963 <EMAIL> 43
45 997558412 <EMAIL> 44
46 997524869 <EMAIL> 45
47 997522211 <EMAIL> 46
48 997540555 <EMAIL> 47
49 9975744767 <EMAIL> 48
50 997508086 <EMAIL> 49
\.
--
-- Data for Name: django_admin_log; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.django_admin_log (id, action_time, object_id, object_repr, action_flag, change_message, content_type_id, user_id) FROM stdin;
1 2021-07-18 01:38:56.491914+05 1 <NAME> 1 [{"added": {}}] 7 1
2 2021-07-18 01:39:17.249073+05 1 number - +998973226755 email - <EMAIL> 1 [{"added": {}}] 8 1
3 2021-07-18 01:39:33.82994+05 2 number - +998993606237 email - <EMAIL> 1 [{"added": {}}] 8 1
4 2021-07-18 02:01:21.581178+05 2 <NAME> 1 [{"added": {}}] 7 1
5 2021-07-18 02:02:34.464126+05 3 number - +998993606238 email - <EMAIL> 1 [{"added": {}}] 8 1
6 2021-07-18 02:18:34.871795+05 3 <NAME> 1 [{"added": {}}] 7 1
7 2021-07-18 02:19:45.338772+05 4 number - 997509035 email - <EMAIL> 1 [{"added": {}}] 8 1
8 2021-07-18 02:21:20.974935+05 4 <NAME> 1 [{"added": {}}] 7 1
9 2021-07-18 02:22:11.872734+05 5 number - 997508885 email - <EMAIL> 1 [{"added": {}}] 8 1
10 2021-07-18 02:23:53.998692+05 5 <NAME> 1 [{"added": {}}] 7 1
11 2021-07-18 02:24:30.987362+05 6 number - 997500758 email - <EMAIL> 1 [{"added": {}}] 8 1
12 2021-07-18 02:25:42.813671+05 6 <NAME> 1 [{"added": {}}] 7 1
13 2021-07-18 02:26:21.11036+05 7 number - 997517039 email - <EMAIL> 1 [{"added": {}}] 8 1
14 2021-07-18 02:27:31.114998+05 7 <NAME> 1 [{"added": {}}] 7 1
15 2021-07-18 02:27:36.661245+05 7 <NAME> 2 [] 7 1
16 2021-07-18 02:28:04.983996+05 8 number - 997508388 email - <EMAIL> 1 [{"added": {}}] 8 1
17 2021-07-18 02:28:59.441073+05 8 <NAME> 1 [{"added": {}}] 7 1
18 2021-07-18 02:29:34.947572+05 9 number - 997532121 email - <EMAIL> 1 [{"added": {}}] 8 1
19 2021-07-18 02:30:38.256312+05 9 <NAME> 1 [{"added": {}}] 7 1
20 2021-07-18 02:31:09.63435+05 10 number - 997503649 email - <EMAIL> 1 [{"added": {}}] 8 1
21 2021-07-18 02:31:48.399887+05 10 <NAME> 1 [{"added": {}}] 7 1
22 2021-07-18 02:32:21.027776+05 11 number - 997501773 email - <EMAIL> 1 [{"added": {}}] 8 1
23 2021-07-18 02:33:10.17553+05 11 <NAME> 1 [{"added": {}}] 7 1
24 2021-07-18 02:33:42.296434+05 12 number - 997528142 email - <EMAIL> 1 [{"added": {}}] 8 1
25 2021-07-18 02:35:42.749197+05 12 <NAME> 1 [{"added": {}}] 7 1
26 2021-07-18 02:36:18.170105+05 13 number - 933006898 email - <EMAIL> 1 [{"added": {}}] 8 1
27 2021-07-18 02:37:01.499358+05 13 <NAME> 1 [{"added": {}}] 7 1
28 2021-07-18 02:37:36.730243+05 14 number - 997506160 email - <EMAIL> 1 [{"added": {}}] 8 1
29 2021-07-18 02:38:40.017868+05 14 <NAME> 1 [{"added": {}}] 7 1
30 2021-07-18 02:39:14.651002+05 15 number - 997404035 email - <EMAIL> 1 [{"added": {}}] 8 1
31 2021-07-18 02:39:55.327083+05 15 <NAME>od 1 [{"added": {}}] 7 1
32 2021-07-18 02:40:27.636971+05 16 number - 993610001 email - <EMAIL> 1 [{"added": {}}] 8 1
33 2021-07-18 02:41:24.921313+05 16 <NAME> 1 [{"added": {}}] 7 1
34 2021-07-18 02:41:57.47657+05 17 number - 997561007 email - <EMAIL> 1 [{"added": {}}] 8 1
35 2021-07-18 02:42:33.908848+05 17 <NAME> 1 [{"added": {}}] 7 1
36 2021-07-18 02:43:03.705761+05 18 number - 997556557 email - <EMAIL> 1 [{"added": {}}] 8 1
37 2021-07-18 02:43:41.65516+05 18 <NAME> 1 [{"added": {}}] 7 1
38 2021-07-18 02:44:18.755499+05 19 number - 994554433 email - <EMAIL> 1 [{"added": {}}] 8 1
39 2021-07-18 02:44:48.812829+05 19 <NAME> 1 [{"added": {}}] 7 1
40 2021-07-18 02:45:25.834615+05 20 number - 997520252 email - <EMAIL> 1 [{"added": {}}] 8 1
41 2021-07-18 02:46:09.783386+05 20 <NAME> 1 [{"added": {}}] 7 1
42 2021-07-18 02:46:43.273948+05 21 number - 997514508 email - <EMAIL> 1 [{"added": {}}] 8 1
43 2021-07-18 02:47:11.695583+05 21 <NAME> 1 [{"added": {}}] 7 1
44 2021-07-18 02:47:41.989617+05 22 number - 995745201 email - <EMAIL> 1 [{"added": {}}] 8 1
45 2021-07-18 02:48:10.275412+05 22 <NAME> 1 [{"added": {}}] 7 1
46 2021-07-18 02:48:43.923593+05 23 number - 990820331 email - <EMAIL> 1 [{"added": {}}] 8 1
47 2021-07-18 02:49:22.695234+05 23 <NAME> 1 [{"added": {}}] 7 1
48 2021-07-18 02:49:25.734934+05 23 <NAME> 2 [] 7 1
49 2021-07-18 02:49:57.184194+05 24 number - 932810091 email - <EMAIL> 1 [{"added": {}}] 8 1
50 2021-07-18 02:50:33.789132+05 24 <NAME> 1 [{"added": {}}] 7 1
51 2021-07-18 02:50:57.972781+05 25 number - 997556001 email - <EMAIL> 1 [{"added": {}}] 8 1
52 2021-07-18 02:51:30.302123+05 25 <NAME> 1 [{"added": {}}] 7 1
53 2021-07-18 02:51:56.50863+05 26 number - 997558024 email - <EMAIL> 1 [{"added": {}}] 8 1
54 2021-07-18 02:52:32.251967+05 26 <NAME> 1 [{"added": {}}] 7 1
55 2021-07-18 02:52:59.385872+05 27 number - 997505662 email - <EMAIL> 1 [{"added": {}}] 8 1
56 2021-07-18 02:53:38.861988+05 27 <NAME> 1 [{"added": {}}] 7 1
57 2021-07-18 02:54:13.780178+05 28 number - 997582106 email - <EMAIL> 1 [{"added": {}}] 8 1
58 2021-07-18 02:54:42.903762+05 28 <NAME> 1 [{"added": {}}] 7 1
59 2021-07-18 02:55:13.580499+05 29 number - 997556214 email - <EMAIL> 1 [{"added": {}}] 8 1
60 2021-07-18 02:55:38.395515+05 29 <NAME> 1 [{"added": {}}] 7 1
61 2021-07-18 02:56:02.131183+05 30 number - 997535577 email - <EMAIL> 1 [{"added": {}}] 8 1
62 2021-07-18 02:56:43.392874+05 30 <NAME> 1 [{"added": {}}] 7 1
63 2021-07-18 02:57:12.447185+05 31 number - 995757775 email - <EMAIL> 1 [{"added": {}}] 8 1
64 2021-07-18 02:57:37.458825+05 31 <NAME> 1 [{"added": {}}] 7 1
65 2021-07-18 02:58:12.906021+05 32 number - 995874625 email - <EMAIL> 1 [{"added": {}}] 8 1
66 2021-07-18 02:58:46.275706+05 32 <NAME> 1 [{"added": {}}] 7 1
67 2021-07-18 02:59:22.03346+05 33 number - 997530306 email - <EMAIL> 1 [{"added": {}}] 8 1
68 2021-07-18 03:00:01.042495+05 33 <NAME> 1 [{"added": {}}] 7 1
69 2021-07-18 03:00:32.538884+05 34 number - 998337988 email - <EMAIL> 1 [{"added": {}}] 8 1
70 2021-07-18 03:01:14.479456+05 34 Ibragim<NAME> 1 [{"added": {}}] 7 1
71 2021-07-18 03:01:48.429103+05 35 number - 997505892 email - <EMAIL> 1 [{"added": {}}] 8 1
72 2021-07-18 03:02:11.425927+05 35 <NAME> 1 [{"added": {}}] 7 1
73 2021-07-18 03:02:42.27209+05 36 number - 997420949 email - <EMAIL> 1 [{"added": {}}] 8 1
74 2021-07-18 03:03:07.542139+05 36 <NAME> 1 [{"added": {}}] 7 1
75 2021-07-18 03:03:37.382851+05 37 number - 997576025 email - <EMAIL> 1 [{"added": {}}] 8 1
76 2021-07-18 03:04:06.244495+05 37 <NAME> 1 [{"added": {}}] 7 1
77 2021-07-18 03:04:35.241133+05 38 number - 995576460 email - <EMAIL> 1 [{"added": {}}] 8 1
78 2021-07-18 03:05:10.185751+05 38 <NAME> 1 [{"added": {}}] 7 1
79 2021-07-18 03:05:42.966352+05 39 number - 997507767 email - <EMAIL> 1 [{"added": {}}] 8 1
80 2021-07-18 03:06:11.318018+05 39 <NAME> 1 [{"added": {}}] 7 1
81 2021-07-18 03:06:37.716726+05 40 number - 997575788 email - <EMAIL> 1 [{"added": {}}] 8 1
82 2021-07-18 03:07:03.629146+05 40 <NAME> 1 [{"added": {}}] 7 1
83 2021-07-18 03:07:41.160941+05 41 number - 997520159 email - <EMAIL> 1 [{"added": {}}] 8 1
84 2021-07-18 03:08:05.649507+05 41 <NAME> 1 [{"added": {}}] 7 1
85 2021-07-18 03:08:37.390085+05 42 number - 997859691 email - <EMAIL> 1 [{"added": {}}] 8 1
86 2021-07-18 03:09:11.86045+05 42 <NAME> 1 [{"added": {}}] 7 1
87 2021-07-18 03:09:52.913538+05 43 number - 997537645 email - <EMAIL> 1 [{"added": {}}] 8 1
88 2021-07-18 03:10:13.597919+05 43 <NAME> 1 [{"added": {}}] 7 1
89 2021-07-18 03:10:41.4196+05 44 number - 997558963 email - <EMAIL> 1 [{"added": {}}] 8 1
90 2021-07-18 03:11:03.288923+05 44 <NAME> 1 [{"added": {}}] 7 1
91 2021-07-18 03:11:57.750429+05 45 number - 997558412 email - <EMAIL> 1 [{"added": {}}] 8 1
92 2021-07-18 03:12:35.459661+05 45 <NAME> 1 [{"added": {}}] 7 1
93 2021-07-18 03:13:00.111028+05 46 number - 997524869 email - <EMAIL> 1 [{"added": {}}] 8 1
94 2021-07-18 03:13:27.333524+05 46 <NAME> 1 [{"added": {}}] 7 1
95 2021-07-18 03:13:56.870521+05 47 number - 997522211 email - <EMAIL> 1 [{"added": {}}] 8 1
96 2021-07-18 03:14:24.008809+05 47 <NAME> 1 [{"added": {}}] 7 1
97 2021-07-18 03:14:57.813668+05 48 number - 997540555 email - <EMAIL> 1 [{"added": {}}] 8 1
98 2021-07-18 03:15:35.836998+05 48 <NAME> 1 [{"added": {}}] 7 1
99 2021-07-18 03:16:16.306331+05 49 number - 9975744767 email - <EMAIL> 1 [{"added": {}}] 8 1
100 2021-07-18 03:16:43.11794+05 49 <NAME> 1 [{"added": {}}] 7 1
101 2021-07-18 03:17:10.484239+05 50 number - 997508086 email - <EMAIL> 1 [{"added": {}}] 8 1
\.
--
-- Data for Name: django_content_type; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.django_content_type (id, app_label, model) FROM stdin;
1 admin logentry
2 auth permission
3 auth group
4 auth user
5 contenttypes contenttype
6 sessions session
7 contacts contacts
8 contacts userinfo
\.
--
-- Data for Name: django_migrations; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.django_migrations (id, app, name, applied) FROM stdin;
1 contenttypes 0001_initial 2021-07-18 01:14:32.491267+05
2 auth 0001_initial 2021-07-18 01:14:32.873816+05
3 admin 0001_initial 2021-07-18 01:14:33.465672+05
4 admin 0002_logentry_remove_auto_add 2021-07-18 01:14:33.625749+05
5 admin 0003_logentry_add_action_flag_choices 2021-07-18 01:14:33.651359+05
6 contenttypes 0002_remove_content_type_name 2021-07-18 01:14:33.70733+05
7 auth 0002_alter_permission_name_max_length 2021-07-18 01:14:33.732815+05
8 auth 0003_alter_user_email_max_length 2021-07-18 01:14:33.750177+05
9 auth 0004_alter_user_username_opts 2021-07-18 01:14:33.774353+05
10 auth 0005_alter_user_last_login_null 2021-07-18 01:14:33.800689+05
11 auth 0006_require_contenttypes_0002 2021-07-18 01:14:33.807638+05
12 auth 0007_alter_validators_add_error_messages 2021-07-18 01:14:33.828216+05
13 auth 0008_alter_user_username_max_length 2021-07-18 01:14:33.899126+05
14 auth 0009_alter_user_last_name_max_length 2021-07-18 01:14:33.934499+05
15 auth 0010_alter_group_name_max_length 2021-07-18 01:14:33.958402+05
16 auth 0011_update_proxy_permissions 2021-07-18 01:14:33.985344+05
17 auth 0012_alter_user_first_name_max_length 2021-07-18 01:14:34.010371+05
18 contacts 0001_initial 2021-07-18 01:14:34.245904+05
19 sessions 0001_initial 2021-07-18 01:14:34.515786+05
\.
--
-- Data for Name: django_session; Type: TABLE DATA; Schema: public; Owner: akmal
--
COPY public.django_session (session_key, session_data, expire_date) FROM stdin;
7l4z29t0i2ezuips3qhh6alwk3y6mw89 .<KEY>o:1m4qj2:jbVV72fKyfCanKZ1dtTueab-6hxUOJ-7eKwAfdnY5ZE 2021-08-01 01:15:52.93393+05
\.
--
-- Data for Name: spatial_ref_sys; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) FROM stdin;
\.
--
-- Name: auth_group_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.auth_group_id_seq', 1, false);
--
-- Name: auth_group_permissions_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.auth_group_permissions_id_seq', 1, false);
--
-- Name: auth_permission_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.auth_permission_id_seq', 32, true);
--
-- Name: auth_user_groups_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.auth_user_groups_id_seq', 1, false);
--
-- Name: auth_user_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.auth_user_id_seq', 1, true);
--
-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.auth_user_user_permissions_id_seq', 1, false);
--
-- Name: contacts_contacts_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.contacts_contacts_id_seq', 49, true);
--
-- Name: contacts_userinfo_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.contacts_userinfo_id_seq', 50, true);
--
-- Name: django_admin_log_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.django_admin_log_id_seq', 101, true);
--
-- Name: django_content_type_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.django_content_type_id_seq', 8, true);
--
-- Name: django_migrations_id_seq; Type: SEQUENCE SET; Schema: public; Owner: akmal
--
SELECT pg_catalog.setval('public.django_migrations_id_seq', 19, true);
--
-- Name: auth_group auth_group_name_key; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group
ADD CONSTRAINT auth_group_name_key UNIQUE (name);
--
-- Name: auth_group_permissions auth_group_permissions_group_id_permission_id_0cd325b0_uniq; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group_permissions
ADD CONSTRAINT auth_group_permissions_group_id_permission_id_0cd325b0_uniq UNIQUE (group_id, permission_id);
--
-- Name: auth_group_permissions auth_group_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group_permissions
ADD CONSTRAINT auth_group_permissions_pkey PRIMARY KEY (id);
--
-- Name: auth_group auth_group_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group
ADD CONSTRAINT auth_group_pkey PRIMARY KEY (id);
--
-- Name: auth_permission auth_permission_content_type_id_codename_01ab375a_uniq; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_permission
ADD CONSTRAINT auth_permission_content_type_id_codename_01ab375a_uniq UNIQUE (content_type_id, codename);
--
-- Name: auth_permission auth_permission_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_permission
ADD CONSTRAINT auth_permission_pkey PRIMARY KEY (id);
--
-- Name: auth_user_groups auth_user_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_groups
ADD CONSTRAINT auth_user_groups_pkey PRIMARY KEY (id);
--
-- Name: auth_user_groups auth_user_groups_user_id_group_id_94350c0c_uniq; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_groups
ADD CONSTRAINT auth_user_groups_user_id_group_id_94350c0c_uniq UNIQUE (user_id, group_id);
--
-- Name: auth_user auth_user_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user
ADD CONSTRAINT auth_user_pkey PRIMARY KEY (id);
--
-- Name: auth_user_user_permissions auth_user_user_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_user_permissions
ADD CONSTRAINT auth_user_user_permissions_pkey PRIMARY KEY (id);
--
-- Name: auth_user_user_permissions auth_user_user_permissions_user_id_permission_id_14a6b632_uniq; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_user_permissions
ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_14a6b632_uniq UNIQUE (user_id, permission_id);
--
-- Name: auth_user auth_user_username_key; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user
ADD CONSTRAINT auth_user_username_key UNIQUE (username);
--
-- Name: contacts_contacts contacts_contacts_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_contacts
ADD CONSTRAINT contacts_contacts_pkey PRIMARY KEY (id);
--
-- Name: contacts_contacts contacts_contacts_username_key; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_contacts
ADD CONSTRAINT contacts_contacts_username_key UNIQUE (username);
--
-- Name: contacts_userinfo contacts_userinfo_email_key; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_userinfo
ADD CONSTRAINT contacts_userinfo_email_key UNIQUE (email);
--
-- Name: contacts_userinfo contacts_userinfo_mnumber_key; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_userinfo
ADD CONSTRAINT contacts_userinfo_mnumber_key UNIQUE (mnumber);
--
-- Name: contacts_userinfo contacts_userinfo_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_userinfo
ADD CONSTRAINT contacts_userinfo_pkey PRIMARY KEY (id);
--
-- Name: django_admin_log django_admin_log_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_admin_log
ADD CONSTRAINT django_admin_log_pkey PRIMARY KEY (id);
--
-- Name: django_content_type django_content_type_app_label_model_76bd3d3b_uniq; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_content_type
ADD CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (app_label, model);
--
-- Name: django_content_type django_content_type_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_content_type
ADD CONSTRAINT django_content_type_pkey PRIMARY KEY (id);
--
-- Name: django_migrations django_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_migrations
ADD CONSTRAINT django_migrations_pkey PRIMARY KEY (id);
--
-- Name: django_session django_session_pkey; Type: CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_session
ADD CONSTRAINT django_session_pkey PRIMARY KEY (session_key);
--
-- Name: auth_group_name_a6ea08ec_like; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_group_name_a6ea08ec_like ON public.auth_group USING btree (name varchar_pattern_ops);
--
-- Name: auth_group_permissions_group_id_b120cbf9; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_group_permissions_group_id_b120cbf9 ON public.auth_group_permissions USING btree (group_id);
--
-- Name: auth_group_permissions_permission_id_84c5c92e; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_group_permissions_permission_id_84c5c92e ON public.auth_group_permissions USING btree (permission_id);
--
-- Name: auth_permission_content_type_id_2f476e4b; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_permission_content_type_id_2f476e4b ON public.auth_permission USING btree (content_type_id);
--
-- Name: auth_user_groups_group_id_97559544; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_user_groups_group_id_97559544 ON public.auth_user_groups USING btree (group_id);
--
-- Name: auth_user_groups_user_id_6a12ed8b; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_user_groups_user_id_6a12ed8b ON public.auth_user_groups USING btree (user_id);
--
-- Name: auth_user_user_permissions_permission_id_1fbb5f2c; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_user_user_permissions_permission_id_1fbb5f2c ON public.auth_user_user_permissions USING btree (permission_id);
--
-- Name: auth_user_user_permissions_user_id_a95ead1b; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_user_user_permissions_user_id_a95ead1b ON public.auth_user_user_permissions USING btree (user_id);
--
-- Name: auth_user_username_6821ab7c_like; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX auth_user_username_6821ab7c_like ON public.auth_user USING btree (username varchar_pattern_ops);
--
-- Name: contacts_contacts_username_82b5bbe1_like; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX contacts_contacts_username_82b5bbe1_like ON public.contacts_contacts USING btree (username varchar_pattern_ops);
--
-- Name: contacts_userinfo_contact_id_6a823277; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX contacts_userinfo_contact_id_6a823277 ON public.contacts_userinfo USING btree (contact_id);
--
-- Name: contacts_userinfo_email_a1450e62_like; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX contacts_userinfo_email_a1450e62_like ON public.contacts_userinfo USING btree (email varchar_pattern_ops);
--
-- Name: contacts_userinfo_mnumber_7ccdcacb_like; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX contacts_userinfo_mnumber_7ccdcacb_like ON public.contacts_userinfo USING btree (mnumber varchar_pattern_ops);
--
-- Name: django_admin_log_content_type_id_c4bce8eb; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX django_admin_log_content_type_id_c4bce8eb ON public.django_admin_log USING btree (content_type_id);
--
-- Name: django_admin_log_user_id_c564eba6; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX django_admin_log_user_id_c564eba6 ON public.django_admin_log USING btree (user_id);
--
-- Name: django_session_expire_date_a5c62663; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX django_session_expire_date_a5c62663 ON public.django_session USING btree (expire_date);
--
-- Name: django_session_session_key_c0390e0f_like; Type: INDEX; Schema: public; Owner: akmal
--
CREATE INDEX django_session_session_key_c0390e0f_like ON public.django_session USING btree (session_key varchar_pattern_ops);
--
-- Name: auth_group_permissions auth_group_permissio_permission_id_84c5c92e_fk_auth_perm; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group_permissions
ADD CONSTRAINT auth_group_permissio_permission_id_84c5c92e_fk_auth_perm FOREIGN KEY (permission_id) REFERENCES public.auth_permission(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_group_permissions auth_group_permissions_group_id_b120cbf9_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_group_permissions
ADD CONSTRAINT auth_group_permissions_group_id_b120cbf9_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES public.auth_group(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_permission auth_permission_content_type_id_2f476e4b_fk_django_co; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_permission
ADD CONSTRAINT auth_permission_content_type_id_2f476e4b_fk_django_co FOREIGN KEY (content_type_id) REFERENCES public.django_content_type(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_groups auth_user_groups_group_id_97559544_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_groups
ADD CONSTRAINT auth_user_groups_group_id_97559544_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES public.auth_group(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_groups auth_user_groups_user_id_6a12ed8b_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_groups
ADD CONSTRAINT auth_user_groups_user_id_6a12ed8b_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES public.auth_user(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_user_permissions auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_user_permissions
ADD CONSTRAINT auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm FOREIGN KEY (permission_id) REFERENCES public.auth_permission(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_user_permissions auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.auth_user_user_permissions
ADD CONSTRAINT auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES public.auth_user(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: contacts_userinfo contacts_userinfo_contact_id_6a823277_fk_contacts_contacts_id; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.contacts_userinfo
ADD CONSTRAINT contacts_userinfo_contact_id_6a823277_fk_contacts_contacts_id FOREIGN KEY (contact_id) REFERENCES public.contacts_contacts(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: django_admin_log django_admin_log_content_type_id_c4bce8eb_fk_django_co; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_admin_log
ADD CONSTRAINT django_admin_log_content_type_id_c4bce8eb_fk_django_co FOREIGN KEY (content_type_id) REFERENCES public.django_content_type(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: django_admin_log django_admin_log_user_id_c564eba6_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: akmal
--
ALTER TABLE ONLY public.django_admin_log
ADD CONSTRAINT django_admin_log_user_id_c564eba6_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES public.auth_user(id) DEFERRABLE INITIALLY DEFERRED;
--
-- PostgreSQL database dump complete
--
<file_sep># aliftech
Project Django, restframework, postgresql
linux
install python3
sudo apt update
sudo apt install python3.8
python --version
windows
https://www.python.org/downloads/
install
linux
pip3 install -r req.txt
windows
python -m pip install -r req.txt
documentations
contact/swagger/
| 5094b9fb7e841169a8aec72021cb239b915ae488 | [
"Markdown",
"SQL",
"Python"
] | 8 | Python | Qurbonov-AA/aliftech | ec44dfe3174920ebbde370f6e46adbfad495815a | 5d4eea6ae86f81ce11a3a0a312424a85d98dd9ce |
refs/heads/master | <file_sep>const R = require('ramda')
module.exports = function () {
const roster = {}
const addToRoster = (name, grade) => roster[grade] ? roster[grade].push(name) : roster[grade] = [name]
const sortedRoster = (roster) => R.map((students) => students.sort(), roster)
return {
roster: () => sortedRoster(roster),
add: (name, grade) => addToRoster(name, grade),
grade: (grade) => { try { return roster[grade].sort() } catch (e) { return [] } }
}
}
<file_sep>module.exports = function () {
return {
hey: (message) => {
if (!message.replace(/ /g, '')) { return 'Fine. Be that way!' }
if (message.toUpperCase() === message && message.toLowerCase() !== message) { return 'Whoa, chill out!' }
return message[message.length - 1] === '?' ? 'Sure.' : 'Whatever.'
}
}
}
<file_sep>module.exports = function () {
return {
hello: (name) => name ? `Hello, ${name}!` : 'Hello, World!'
}
}
<file_sep>const R = require('ramda')
module.exports = function () {
const formatWord = (word) => word.replace(/\s/g, ' ').toLowerCase().split(' ')
const countWords = (words) => {
const obj = {}
for (let i = 0; i < words.length; i++) {
// TODO: Hack fix for multiple spaces
if (!words[i]) continue
obj.hasOwnProperty(words[i]) ? obj[words[i]] += 1 : obj[words[i]] = 1
}
return obj
}
return {
count: (word) => R.compose(countWords, formatWord)(word)
}
}
<file_sep>const R = require('ramda')
module.exports = function (number) {
const normaliseNumber = (number) => number.replace(/\s|-|\(|\)|\./g, '')
const removeOne = (number) => number.length > 10 && number.charAt(0) === '1' ? number.slice(1) : number
const invalid = (number) => number.length !== 10 ? '0000000000' : number
const getAreaCode = (number) => number.slice(0, 3)
const toString = (number) => `(${number.slice(0, 3)}) ${number.slice(3, 6)}-${number.slice(6)}`
return {
number: () => R.compose(invalid, removeOne, normaliseNumber)(number),
areaCode: () => getAreaCode(number),
toString: () => toString(number)
}
}
<file_sep>module.exports = function (date) {
return {
date: () => new Date(Date.parse(date) + 1000000000000)
}
}
<file_sep># exercism-js
Solutions to the JavaScript problems on exercism.io
| 2355e1142e36a0cf1fb793e7b94ecfd78e30ae5f | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | AlexChesters/exercism-js | 0e78b2ee2303066d04835790b4b230e51bc9a03f | 093dafabf7972035c5d388f4a240ad42232b0aed |
refs/heads/master | <repo_name>CodingDreamteam/RestauranTO<file_sep>/RestauranTO/src/main/java/RestauranTO/Database/Datamodel/TblSugestions.java
package RestauranTO.Database.Datamodel;
import java.io.Serializable;
public class TblSugestions implements Serializable {
private static final long serialVersionUID = 4437712241408431567L;
protected String strID;
protected String strName;
protected String strDirection;
protected String strEmail;
protected String strPhoneNumber;
protected String strImage;
public TblSugestions( String strID, String strName, String strDirection, String strEmail, String strPhoneNumber ,String strImage ) {
super();
this.strID = strID;
this.strName = strName;
this.strDirection = strDirection;
this.strEmail = strEmail;
this.strPhoneNumber = strPhoneNumber;
this.strImage = strImage;
}
public TblSugestions() {
super();
}
public String getStrID() {
return strID;
}
public void setStrID( String strID ) {
this.strID = strID;
}
public String getStrName() {
return strName;
}
public void setStrName( String strName ) {
this.strName = strName;
}
public String getStrDirection() {
return strDirection;
}
public void setStrDirection( String strDirection ) {
this.strDirection = strDirection;
}
public String getStrEmail() {
return strEmail;
}
public void setStrEmail( String strEmail ) {
this.strEmail = strEmail;
}
public String getStrPhoneNumber() {
return strPhoneNumber;
}
public void setStrPhoneNumber( String strPhoneNumber ) {
this.strPhoneNumber = strPhoneNumber;
}
public String getStrImage() {
return strImage;
}
public void setStrImage( String strImage ) {
this.strImage = strImage;
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/Database/Datamodel/TblReservation.java
package RestauranTO.Database.Datamodel;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
public class TblReservation implements Serializable {
private static final long serialVersionUID = 6118355009360334069L;
protected String strUserID;
protected String strRestaurantID;
protected int intCapacity;
protected String strEmail;
protected LocalDate SelectedDate;
protected LocalTime SelectedTime;
public TblReservation( String strUserID, String strRestaurantID, int intCapacity, String strEmail, LocalDate selectedDate, LocalTime selectedTime ) {
super();
this.strUserID = strUserID;
this.strRestaurantID = strRestaurantID;
this.intCapacity = intCapacity;
this.strEmail = strEmail;
this.SelectedDate = selectedDate;
this.SelectedTime = selectedTime;
}
public TblReservation() {
super();
}
public String getStrUserID() {
return strUserID;
}
public void setStrUserID( String strUserID ) {
this.strUserID = strUserID;
}
public String getStrRestaurantID() {
return strRestaurantID;
}
public void setStrRestaurantID( String strRestaurantID ) {
this.strRestaurantID = strRestaurantID;
}
public int getIntCapacity() {
return intCapacity;
}
public void setIntCapacity( int intCapacity ) {
this.intCapacity = intCapacity;
}
public String getStrEmail() {
return strEmail;
}
public void setStrEmail( String strEmail ) {
this.strEmail = strEmail;
}
public LocalDate getSelectedDate() {
return SelectedDate;
}
public void setSelectedDate( LocalDate selectedDate ) {
this.SelectedDate = selectedDate;
}
public LocalTime getSelectedTime() {
return SelectedTime;
}
public void setSelectedTime( LocalTime selectedTime ) {
this.SelectedTime = selectedTime;
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/Database/CDatabaseConnection.java
package RestauranTO.Database;
import java.sql.Connection;
import java.sql.DriverManager;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.SelectorComposer;
public class CDatabaseConnection extends SelectorComposer<Component> {
private static final long serialVersionUID = 4225343907390582232L;
protected Connection DatabaseConnection;
protected CDatabaseConnectionConfig DatabaseConnectionConfig;
public CDatabaseConnection() {
DatabaseConnection = null;
DatabaseConnectionConfig = null;
}
public Connection getDatabaseConnection() {
return DatabaseConnection;
}
public CDatabaseConnectionConfig getDatabaseConnectionConfig() {
return DatabaseConnectionConfig;
}
public void setDatabaseConnection( Connection DatabaseConnection ) {
this.DatabaseConnection = DatabaseConnection;
}
public void setDatabaseConnectionConfig( CDatabaseConnectionConfig DatabaseConnectionConfig ) {
this.DatabaseConnectionConfig = DatabaseConnectionConfig;
}
public boolean makeConnectionToDatabase( CDatabaseConnectionConfig localDBConnectionConfig ) {
boolean bResult = false;
try {
if ( this.DatabaseConnection == null ) {
Class.forName( localDBConnectionConfig.Driver );
String strDatabaseURL = localDBConnectionConfig.Prefix + localDBConnectionConfig.Host + ":" + localDBConnectionConfig.Port + "/" + localDBConnectionConfig.Database;
Connection localDBConnection = DriverManager.getConnection( strDatabaseURL, localDBConnectionConfig.User, localDBConnectionConfig.Password );
localDBConnection.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED );
bResult = localDBConnection != null && localDBConnection.isValid( 5 );
if ( bResult ) {
localDBConnection.setAutoCommit( false );
this.DatabaseConnection = localDBConnection;
this.DatabaseConnectionConfig = localDBConnectionConfig;
}
else {
localDBConnection.close();
localDBConnection = null;
}
}
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
return bResult;
}
public boolean closeConnectionToDB( ) {
boolean bResult = false;
try {
if ( DatabaseConnection != null ) {
DatabaseConnection.close();//cerramos
}
DatabaseConnection = null;
DatabaseConnectionConfig = null;
bResult = true;
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
return bResult;
}
public boolean isValid( ) {
boolean bResult = false;
try {
bResult = DatabaseConnection.isValid( 5 );
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
return bResult;
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/controller/list/CListController.java
package RestauranTO.controller.list;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Button;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Window;
import RestauranTO.Constants.SystemConstants;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.CDatabaseConnectionConfig;
import RestauranTO.Database.Dao.RestaurantDAO;
import RestauranTO.Database.Datamodel.TblRestaurant;
import RestauranTO.Database.Datamodel.TblUser;
import RestauranTO.Database.Datamodel.TblZone;
public class CListController extends SelectorComposer<Component>{
private static final long serialVersionUID = -1426709078820259442L;
@Wire
Listbox listboxRestaurantes;
@Wire
Button buttonShowAll;
protected TblUser tblUser = null;
protected Session sesion = Sessions.getCurrent();
protected final Execution execution = Executions.getCurrent();
protected ListModelList<TblRestaurant> datamodelRestaurant = null;
public class MyRenderer implements ListitemRenderer<TblRestaurant> {
public void render( Listitem listitem, TblRestaurant Restaurant, int arg2 ) throws Exception {
try {
Listcell cell = new Listcell();
cell.setLabel( Restaurant.getStrName() );
listitem.appendChild( cell );
cell = new Listcell();
cell.setLabel( Restaurant.getStrDescription() );
listitem.appendChild( cell );
cell = new Listcell();
cell.setLabel( Restaurant.getStrDirection());
listitem.appendChild( cell );
}
catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
@Listen( "onSelect=#listboxZone" )
public void onSelect ( Event event ) {
Set<TblRestaurant> selecteditems = datamodelRestaurant.getSelection();
if ( listboxRestaurantes.getSelectedIndex() >= 0 ) {
if ( selecteditems != null && datamodelRestaurant.getSelection().size() > 0 ) {
TblRestaurant tblRestaurant = selecteditems.iterator().next();
Map<String, Object> arg = new HashMap<String, Object>();
arg.put("tblRestaurant", tblRestaurant);
Window win = ( Window ) Executions.createComponents( "/views/restaurantinfo/restaurantinfo.zul", null, arg );
win.doModal();
}
}
}
@SuppressWarnings( "unchecked" )
public void doAfterCompose( Component comp ) {
try {
super.doAfterCompose( comp );
if ( sesion.getAttribute( "listboxRestaurant" ) != null ) {
List<TblRestaurant> listData = ( List<TblRestaurant> ) sesion.getAttribute( "listboxRestaurant" );
datamodelRestaurant = new ListModelList<TblRestaurant>( listData );
listboxRestaurantes.setModel( datamodelRestaurant );
listboxRestaurantes.setItemRenderer( ( new MyRenderer() ) );
}
else {
Events.echoEvent("onClick", buttonShowAll, null );
}
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
}
@Listen( "onClick=#buttonShowAll" )
public void onClickbuttonShowAll( Event event ) {
CDatabaseConnection databaseConnection = new CDatabaseConnection();
CDatabaseConnectionConfig databaseConnectionConfig = new CDatabaseConnectionConfig();
String strRunningPath = Sessions.getCurrent().getWebApp().getRealPath( SystemConstants._Web_Inf_Dir ) + File.separator;
if ( databaseConnectionConfig.loadConfig( strRunningPath + SystemConstants._Config_Dir + SystemConstants._Database_Config_File ) ) {
if ( databaseConnection.makeConnectionToDatabase( databaseConnectionConfig ) ) {
List<TblRestaurant> listData = RestaurantDAO.SearchAllRestaurants( databaseConnection );
datamodelRestaurant = new ListModelList<TblRestaurant>( listData );
listboxRestaurantes.setModel( datamodelRestaurant );
listboxRestaurantes.setItemRenderer( ( new MyRenderer() ) );
databaseConnection.closeConnectionToDB();
}
}
}
@Listen( "onClick=#buttonZoneSearch" )
public void onClicklabellogin( Event event ) {
Map<String, Object> arg = new HashMap<String, Object>();
arg.put( "listboxRestaurantes", listboxRestaurantes );
Window win = ( Window ) Executions.createComponents( "/views/zoneselector/zoneselector.zul", null, arg );
win.doModal();
}
@Listen( "onZoneClose=#listboxRestaurantes" )
public void onZoneClose( Event event ) {
TblZone tblzone = ( TblZone ) event.getData();
CDatabaseConnection databaseConnection = new CDatabaseConnection();
CDatabaseConnectionConfig databaseConnectionConfig = new CDatabaseConnectionConfig();
String strRunningPath = Sessions.getCurrent().getWebApp().getRealPath( SystemConstants._Web_Inf_Dir ) + File.separator;
if ( databaseConnectionConfig.loadConfig( strRunningPath + SystemConstants._Config_Dir + SystemConstants._Database_Config_File ) ) {
if ( databaseConnection.makeConnectionToDatabase( databaseConnectionConfig ) ) {
List<TblRestaurant> listData = RestaurantDAO.SearchRestaurantsZones( databaseConnection, tblzone.getStrName() );
datamodelRestaurant = new ListModelList<TblRestaurant>( listData );
listboxRestaurantes.setModel( datamodelRestaurant );
listboxRestaurantes.setItemRenderer( ( new MyRenderer() ) );
databaseConnection.closeConnectionToDB();
}
}
}
}
<file_sep>/RestauranTO/src/main/java/RestauraTO/controller/Ratinglist/CRatinglistController.java
package RestauraTO.controller.Ratinglist;
import java.io.File;
import java.util.List;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import RestauranTO.Constants.SystemConstants;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.CDatabaseConnectionConfig;
import RestauranTO.Database.Dao.RestaurantDAO;
import RestauranTO.Database.Dao.UserDAO;
import RestauranTO.Database.Datamodel.TblUser;
import RestauranTO.Database.Datamodel.TblZone;
import RestauranTO.Database.Datamodel.TblRating;
import RestauranTO.controller.Zone.CZoneController.MyRenderer;
public class CRatinglistController extends SelectorComposer<Component> {
private static final long serialVersionUID = 8558890108543087068L;
@Wire
Listbox listboxRating;
protected TblUser tblUser = null;
protected Session sesion = Sessions.getCurrent();
protected final Execution execution = Executions.getCurrent();
protected ListModelList<TblRating> datamodelRating = null;
protected String RestaurantID = null;
public class MyRenderer implements ListitemRenderer<TblRating> {
@SuppressWarnings( "static-access" )
public void render( Listitem listitem, TblRating Rating, int arg2 ) throws Exception {
try {
Listcell cell = new Listcell();
cell.setLabel( Rating.getUserName() );
listitem.appendChild( cell );
cell = new Listcell();
cell.setLabel( Rating.getStrComment() );
listitem.appendChild( cell );
cell = new Listcell();
String Ratingnumber = null;
Ratingnumber.valueOf( Rating.getIntRating() );
cell.setLabel( Ratingnumber );
listitem.appendChild( cell );
}
catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
@SuppressWarnings( "unchecked" )
public void doAfterCompose( Component comp ) {
try {
super.doAfterCompose( comp );
RestaurantID = ( String ) execution.getArg().get( "RestaurantID" );
CDatabaseConnection databaseConnection = new CDatabaseConnection();
CDatabaseConnectionConfig databaseConnectionConfig = new CDatabaseConnectionConfig();
String strRunningPath = Sessions.getCurrent().getWebApp().getRealPath( SystemConstants._Web_Inf_Dir ) + File.separator;
if ( databaseConnectionConfig.loadConfig( strRunningPath + SystemConstants._Config_Dir + SystemConstants._Database_Config_File ) ) {
if ( databaseConnection.makeConnectionToDatabase( databaseConnectionConfig ) ) {
List<TblRating> listData = UserDAO.SearchRatings( databaseConnection, RestaurantID );
datamodelRating = new ListModelList<TblRating>( listData );
listboxRating.setModel( datamodelRating );
listboxRating.setItemRenderer( ( new MyRenderer() ) );
databaseConnection.closeConnectionToDB();
}
}
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/controller/sugestions/CSugestionsController.java
package RestauranTO.controller.sugestions;
import org.zkoss.image.Image;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import RestauranTO.Constants.SystemConstants;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.Dao.RestaurantDAO;
import RestauranTO.Database.Datamodel.TblSugestions;
import RestauranTO.Database.Datamodel.TblUser;
public class CSugestionsController extends SelectorComposer<Component> {
private static final long serialVersionUID = 6107638621463893607L;
@Wire
Textbox textboxName;
@Wire
Textbox textboxDirection;
@Wire
Textbox textboxPhoneNumber;
@Wire
Textbox textboxEmail;
@Wire
Image Picture;
protected TblUser tblUser = null;
protected Session sesion = Sessions.getCurrent();
protected final Execution execution = Executions.getCurrent();
public void doAfterCompose( Component comp ) {
try {
super.doAfterCompose( comp );
tblUser = ( TblUser ) sesion.getAttribute( SystemConstants._Operator_Credential_Session_Key );
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
}
@Listen( "onClick=#buttonSubmit" )
public void onClickbuttonSubmit( Event event ) {
if ( textboxEmail.getValue().isEmpty() || textboxDirection.getValue().isEmpty() || textboxName.getValue().isEmpty() ) {
Messagebox.show( "debe colocar nombre, direccion y correo para realizar una sugerencia" );
}
else {
TblSugestions tblSugestions = new TblSugestions();
tblSugestions.setStrDirection( textboxDirection.getValue() );
tblSugestions.setStrName( textboxName.getValue() );
tblSugestions.setStrEmail(textboxEmail.getValue() );
if ( textboxPhoneNumber.getValue().isEmpty() != true )
tblSugestions.setStrPhoneNumber( textboxPhoneNumber.getValue() );
if ( Picture != null )
tblSugestions.setStrImage( Picture.getName() );
CDatabaseConnection dbConnection = ( CDatabaseConnection ) sesion.getAttribute( SystemConstants._DB_Connection_Session_Key );
if ( RestaurantDAO.AddSugestion(dbConnection, tblSugestions) ) {
Messagebox.show( "sugerencia agregada" );
}
}
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/controller/register/CRegisterController.java
package RestauranTO.controller.register;
import java.io.File;
import org.zkoss.image.AImage;
import org.zkoss.image.Image;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import RestauranTO.Constants.SystemConstants;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.CDatabaseConnectionConfig;
import RestauranTO.Database.Dao.UserDAO;
import RestauranTO.Database.Datamodel.TblUser;
public class CRegisterController extends SelectorComposer<Component> {
private static final long serialVersionUID = 1677662886424670594L;
@Wire
Button buttonPicture;
@Wire
Button buttonOperatorSave;
@Wire
Textbox textboxEmail;
@Wire
Textbox textboxName;
@Wire
Textbox textboxPassword;
@Wire
Textbox textboxRepeatPassword;
@Wire
Textbox textboxPhoneNumber;
@Wire
Window windowRegister;
protected Image Picture = null;
protected Label labelregister = null;
protected final Execution execution = Executions.getCurrent();
public void doAfterCompose( Component comp ) {
try {
super.doAfterCompose( comp );
buttonPicture.setUpload( "true" );
labelregister = ( Label ) execution.getArg().get( "labelregister" );
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
}
@Listen ("onClick=#buttonPicture")
public void onClickbuttonimportGroupContact ( Event event ) {
buttonPicture.addEventListener( "onUpload", new EventListener<UploadEvent> () {
public void onEvent(UploadEvent event) throws Exception {
try {
Media media = event.getMedia();
if ( media.getName().contains( ".png" ) || media.getName().contains( ".jpg" )) {
AImage image = ( AImage ) media;
//Image image2 = ( Image ) media;
//File file = new File( media.getName());
//file.renameTo( new File (SystemConstants._Web_Inf_Dir + File.separator + SystemConstants._Picture_Folder + File.separator + file.getName() ) );
Messagebox.show( "the file was succesufully submited" );
}
else {
Messagebox.show( "you must import a image file (.png or .jpg)" );
}
}
catch (Exception e) {
e.printStackTrace();
Messagebox.show("Upload failed");
}
}
});
}
@Listen( "onClick=#buttonCancel" )
public void onClickbuttonCancel( Event event ) {
windowRegister.detach();
}
@Listen( "onClick=#buttonSave" )
public void onClickbuttonAddcontact( Event event ) {
if ( textboxEmail.getValue().isEmpty() || textboxName.getValue().isEmpty() || textboxPassword.getValue().isEmpty() || textboxRepeatPassword.getValue().isEmpty() ) {
Messagebox.show( "Debe llenar almenos el correo, la contraseņa y el nombre de usuario" );
}
else {
if ( textboxPassword.getValue() == textboxRepeatPassword.getValue() ) {
Messagebox.show( "las contraseņas no concuerdan" );
}
else {
TblUser tbluser = new TblUser();
tbluser.setStrName( textboxName.getValue() );
tbluser.setStrPassword( textboxPassword.getValue() );
tbluser.setStrEmail( textboxEmail.getValue() );
if ( Picture != null )
tbluser.setStrPicture( Picture.getName() );
if ( textboxPhoneNumber.getValue().isEmpty() != true )
tbluser.setStrPhoneNumber( textboxPhoneNumber.getValue() );
CDatabaseConnection databaseConnection = new CDatabaseConnection();
CDatabaseConnectionConfig databaseConnectionConfig = new CDatabaseConnectionConfig();
String strRunningPath = Sessions.getCurrent().getWebApp().getRealPath( SystemConstants._Web_Inf_Dir ) + File.separator;
if ( databaseConnectionConfig.loadConfig( strRunningPath + SystemConstants._Config_Dir + SystemConstants._Database_Config_File ) ) {
if ( databaseConnection.makeConnectionToDatabase( databaseConnectionConfig ) ) {
if ( UserDAO.AddUser( databaseConnection, tbluser ) ) {
Messagebox.show( "Registro exitoso" );
}
else {
Messagebox.show( "Error con el registro" );
}
}
databaseConnection.closeConnectionToDB();
windowRegister.detach();
}
}
}
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/Database/Dao/UserDAO.java
package RestauranTO.Database.Dao;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.Datamodel.TblRating;
import RestauranTO.Database.Datamodel.TblRestaurant;
import RestauranTO.Database.Datamodel.TblUser;
import RestauranTO.crypt.BCrypt;
public class UserDAO {
public static TblUser checkData( final CDatabaseConnection dbConnection, final String strName, final String strPassword ) {
TblUser result = null;
try {
if ( dbConnection != null && dbConnection.getDatabaseConnection() != null ) {
Statement statement = dbConnection.getDatabaseConnection().createStatement();
ResultSet resultSet = statement.executeQuery( "SELECT * FROM tblUser WHERE Name = '" + strName + "' AND DisabledAtDate <=> null" );
if ( resultSet.next() ) {
String strDBPassword = resultSet.getString( "password" );
String strDBPasswordKey = strDBPassword;
strDBPasswordKey = strDBPasswordKey.substring( 0, 29 );
strDBPasswordKey = strDBPasswordKey.replace( "$2y$10$", "$2a$10$" );
String strPasswordHashed = BCrypt.hashpw( strPassword, strDBPasswordKey );
strPasswordHashed = strPasswordHashed.replace( "$2a$10$", "$2y$10$" );
if ( strPasswordHashed.equals( strDBPassword ) ) {
result = new TblUser();
result.setStrID( resultSet.getString( "ID" ) );
result.setStrName( resultSet.getString( "Name" ) );
result.setStrEmail( resultSet.getString( "Email" ) );
result.setStrRole( resultSet.getString( "Role" ) );
result.setStrPicture( resultSet.getString( "Picture" ) );
result.setStrPassword( resultSet.getString( "Password" ) );
result.setCreatedAtDate( resultSet.getDate( "CreatedAtDate" ).toLocalDate() );
result.setStrRole( resultSet.getString( "Role" ) );
result.setDisabledAtDate( resultSet.getDate( "DisabledAtDate" ) != null ? resultSet.getDate( "DisabledAtDate" ).toLocalDate() : null );
}
}
resultSet.close();
statement.close();
}
}
catch ( Exception ex ) {
ex.printStackTrace();
}
return result;
}
public static boolean AddUser( final CDatabaseConnection dbConnection, TblUser tblUser) {
boolean result = false;
try {
if ( dbConnection != null && dbConnection.getDatabaseConnection() != null ) {
Statement statement = dbConnection.getDatabaseConnection().createStatement();
String ID = UUID.randomUUID().toString();
final String strSQL = "INSERT INTO tbluser (ID, Name, Password, Email, Role, CreatedAtDate) VALUES ('" + ID + "', '" + tblUser.getStrName() + "', '" + tblUser.getStrPassword() + "', '" + tblUser.getStrEmail() + "', 'Regular User', '" + LocalDate.now().toString() + "')";
statement.executeUpdate( strSQL );
dbConnection.getDatabaseConnection().commit();
if ( tblUser.getStrPhoneNumber() != null) {
String strSQL2 = "INSERT INTO tbluser_phonenumber VALUES ( '" + ID + "', '" + tblUser.getStrPhoneNumber() + "')";
statement.executeUpdate( strSQL2 );
dbConnection.getDatabaseConnection().commit();
}
statement.close();
result = true;
}
}
catch ( Exception ex ) {
ex.printStackTrace();
}
return result;
}
public static List<TblRating> SearchRatings ( final CDatabaseConnection dbConnection, String RestaurantID ) {
List<TblRating> result = new ArrayList<TblRating>();
try {
if ( dbConnection != null && dbConnection.getDatabaseConnection() != null ) {
Statement statement = dbConnection.getDatabaseConnection().createStatement();
String strSQL = "SELECT * FROM tblratings JOIN tbluser ON tblratings.User_ID = tbluser.ID WHERE tblratings.Restaurant_ID = '" + RestaurantID + "'";
ResultSet resultSet = statement.executeQuery( strSQL );
while ( resultSet.next() ) {
TblRating tblRating = new TblRating();
tblRating.setStrID( resultSet.getString( "tblratings.ID" ) );
tblRating.setStrComment( resultSet.getString("tblratings.Comment"));
tblRating.setIntRating( resultSet.getInt("tblratings.Rating"));
tblRating.setUserName( resultSet.getString( "tbluser.Name" ) );
result.add( tblRating );
}
resultSet.close();
statement.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public static boolean AddRating( final CDatabaseConnection dbConnection, String Comment, int Rating, String UserID, String RestaurantID) {
boolean result = false;
try {
if ( dbConnection != null && dbConnection.getDatabaseConnection() != null ) {
Statement statement = dbConnection.getDatabaseConnection().createStatement();
final String strSQL = "INSERT INTO tbluser (ID, User_ID, Restaurant_ID, Comment, Rating) VALUES ('" + UUID.randomUUID().toString() + "', '" + UserID + "', '" + RestaurantID + "', '" + Comment + "', '" + Rating + "')";
statement.executeUpdate( strSQL );
dbConnection.getDatabaseConnection().commit();
statement.close();
result = true;
}
}
catch ( Exception ex ) {
ex.getStackTrace();
}
return result;
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/controller/rating/CRatingController.java
package RestauranTO.controller.rating;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Image;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import RestauranTO.Constants.SystemConstants;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.Dao.UserDAO;
import RestauranTO.Database.Datamodel.TblUser;
public class CRatingController extends SelectorComposer<Component> {
private static final long serialVersionUID = -5900924798947899904L;
@Wire
Image star1;
@Wire
Image star2;
@Wire
Image star3;
@Wire
Image star4;
@Wire
Image star5;
@Wire
Textbox textboxComment;
protected TblUser tblUser = null;
protected String RestaurantID = null;
protected Session sesion = Sessions.getCurrent();
protected final Execution execution = Executions.getCurrent();
public void doAfterCompose( Component comp ) {
try {
super.doAfterCompose( comp );
tblUser = ( TblUser ) sesion.getAttribute( SystemConstants._Operator_Credential_Session_Key );
RestaurantID = ( String ) execution.getArg().get( "RestaurantID" );
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
}
@Listen( "onClick=#buttonSubmit" )
public void onClickbuttonSubmit( Event event ) {
if ( textboxComment.getValue().isEmpty() == false ) {
int Rating = 0;
String Comment = null;
if ( star1.getSrc() == "/resources/yellow star.png" )
Rating = 1;
if ( star2.getSrc() == "/resources/yellow star.png" )
Rating = 2;
if ( star3.getSrc() == "/resources/yellow star.png" )
Rating = 3;
if ( star4.getSrc() == "/resources/yellow star.png" )
Rating = 4;
if ( star5.getSrc() == "/resources/yellow star.png" )
Rating = 5;
Comment = textboxComment.getValue();
CDatabaseConnection dbConnection = ( CDatabaseConnection ) sesion.getAttribute( SystemConstants._DB_Connection_Session_Key );
UserDAO.AddRating( dbConnection, Comment, Rating, tblUser.getStrID(), RestaurantID );
Messagebox.show( "Rating enviado" );
}
else {
Messagebox.show( "Debe colocar un comentario" );
}
}
@Listen( "onClick=#star1" )
public void onClickstar1( Event event ) {
star1.setSrc( "/resources/yellow star.png" );
if ( star2.getSrc() == "/resources/yellow star.png") {
star2.setSrc( "/resources/blank star.png" );
star3.setSrc( "/resources/blank star.png" );
star4.setSrc( "/resources/blank star.png" );
star5.setSrc( "/resources/blank star.png" );
}
}
@Listen( "onClick=#star2" )
public void onClickstar2( Event event ) {
star1.setSrc( "/resources/yellow star.png" );
star2.setSrc( "/resources/yellow star.png" );
if ( star3.getSrc() == "/resources/yellow star.png" ) {
star3.setSrc( "/resources/blank star.png" );
star4.setSrc( "/resources/blank star.png" );
star5.setSrc( "/resources/blank star.png" );
}
}
@Listen( "onClick=#star3" )
public void onClickstar3( Event event ) {
star1.setSrc( "/resources/yellow star.png" );
star2.setSrc( "/resources/yellow star.png" );
star3.setSrc( "/resources/yellow star.png" );
if ( star4.getSrc() == "/resources/yellow star.png" ) {
star4.setSrc( "/resources/blank star.png" );
star5.setSrc( "/resources/blank star.png" );
}
}
@Listen( "onClick=#star4" )
public void onClickstar4( Event event ) {
star1.setSrc( "/resources/yellow star.png" );
star2.setSrc( "/resources/yellow star.png" );
star3.setSrc( "/resources/yellow star.png" );
star4.setSrc( "/resources/yellow star.png" );
if ( star5.getSrc() == "/resources/yellow star.png" ) {
star5.setSrc( "/resources/blank star.png" );
}
}
@Listen( "onClick=#star5" )
public void onClickstar5( Event event ) {
star1.setSrc( "/resources/yellow star.png" );
star2.setSrc( "/resources/yellow star.png" );
star3.setSrc( "/resources/yellow star.png" );
star4.setSrc( "/resources/yellow star.png" );
star5.setSrc( "/resources/yellow star.png" );
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/Database/Datamodel/TblUser.java
package RestauranTO.Database.Datamodel;
import java.io.Serializable;
import java.time.LocalDate;
import RestauranTO.crypt.BCrypt;
public class TblUser implements Serializable {
private static final long serialVersionUID = -5001151189415958989L;
protected String strID;
protected String strName;
protected String strPassword;
protected String strEmail;
protected String strPicture;
protected String strRole;
protected String strPhoneNumber;
protected LocalDate CreatedAtDate;
protected LocalDate DisabledAtDate;
public TblUser( String strID, String strName, String strPassword, String strEmail, String strPicture, String strRole, String strPhoneNumber, LocalDate createdAtDate, LocalDate DisabledAtDate) {
super();
this.strID = strID;
this.strName = strEmail;
this.strPassword = <PASSWORD>;
this.strEmail = strEmail;
this.strPicture = strPicture;
this.strRole = strRole;
this.strPhoneNumber = strPhoneNumber;
this.CreatedAtDate = createdAtDate;
this.DisabledAtDate = DisabledAtDate;
}
public TblUser( ) {
super();
}
public String getStrID() {
return strID;
}
public void setStrID( String strID ) {
this.strID = strID;
}
public String getStrName() {
return strName;
}
public void setStrName( String strName ) {
this.strName = strName;
}
public String getStrPassword() {
return strPassword;
}
public void setStrPassword( String strPassword ) {
if (strPassword.startsWith( <PASSWORD>" ) == false) {
String strPasswordKey = BCrypt.gensalt( 10 );
strPassword = BCrypt.hashpw( strPassword, strPasswordKey );
strPassword = strPassword.replace( <PASSWORD>", <PASSWORD>" );
}
this.strPassword = strPassword;
}
public String getStrEmail() {
return strEmail;
}
public void setStrEmail( String strEmail ) {
this.strEmail = strEmail;
}
public String getStrPicture() {
return strPicture;
}
public void setStrPicture( String strPicture ) {
this.strPicture = strPicture;
}
public String getStrRole() {
return strRole;
}
public void setStrRole( String strRole ) {
this.strRole = strRole;
}
public String getStrPhoneNumber() {
return strPhoneNumber;
}
public void setStrPhoneNumber( String strPhoneNumber ) {
this.strPhoneNumber = strPhoneNumber;
}
public LocalDate getCreatedAtDate() {
return CreatedAtDate;
}
public void setCreatedAtDate( LocalDate createdAtDate ) {
this.CreatedAtDate = createdAtDate;
}
public LocalDate getDisabledAtDate() {
return DisabledAtDate;
}
public void setDisabledAtDate( LocalDate disabledAtDate ) {
this.DisabledAtDate = disabledAtDate;
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/controller/Zone/CZoneController.java
package RestauranTO.controller.Zone;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Window;
import RestauranTO.Constants.SystemConstants;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.CDatabaseConnectionConfig;
import RestauranTO.Database.Dao.RestaurantDAO;
import RestauranTO.Database.Datamodel.TblUser;
import RestauranTO.Database.Datamodel.TblZone;
public class CZoneController extends SelectorComposer<Component> {
private static final long serialVersionUID = -6423649102807553745L;
@Wire
Listbox listboxZone;
@Wire
Window windowZoneSelector;
protected TblUser tblUser = null;
protected Session sesion = Sessions.getCurrent();
protected final Execution execution = Executions.getCurrent();
protected ListModelList<TblZone> datamodelZone = null;
protected Listbox listboxRestaurantes = null;
public class MyRenderer implements ListitemRenderer<TblZone> {
public void render( Listitem listitem, TblZone Zone, int arg2 ) throws Exception {
try {
Listcell cell = new Listcell();
cell.setLabel( Zone.getStrName() );
listitem.appendChild( cell );
}
catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
@SuppressWarnings( "unchecked" )
public void doAfterCompose( Component comp ) {
try {
super.doAfterCompose( comp );
listboxRestaurantes = ( Listbox ) execution.getArg().get( "listboxRestaurantes" );
CDatabaseConnection databaseConnection = new CDatabaseConnection();
CDatabaseConnectionConfig databaseConnectionConfig = new CDatabaseConnectionConfig();
String strRunningPath = Sessions.getCurrent().getWebApp().getRealPath( SystemConstants._Web_Inf_Dir ) + File.separator;
if ( databaseConnectionConfig.loadConfig( strRunningPath + SystemConstants._Config_Dir + SystemConstants._Database_Config_File ) ) {
if ( databaseConnection.makeConnectionToDatabase( databaseConnectionConfig ) ) {
List<TblZone> listData = RestaurantDAO.SearchAllZones( databaseConnection );
datamodelZone = new ListModelList<TblZone>( listData );
listboxZone.setModel( datamodelZone );
listboxZone.setItemRenderer( ( new MyRenderer() ) );
databaseConnection.closeConnectionToDB();
}
}
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
}
@Listen( "onSelect=#listboxZone" )
public void onSelect ( Event event ) {
Set<TblZone> selecteditems = datamodelZone.getSelection();
if ( listboxZone.getSelectedIndex() >= 0 ) {
if ( selecteditems != null && datamodelZone.getSelection().size() > 0 ) {
TblZone tblZone = selecteditems.iterator().next();
Events.echoEvent( new Event( "onZoneClose", listboxRestaurantes, tblZone ) );
windowZoneSelector.detach();
}
}
}
}
<file_sep>/RestauranTO/src/main/java/RestauranTO/controller/Selector/CRestaurantSelectorController.java
package RestauranTO.controller.Selector;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Window;
import RestauranTO.Constants.SystemConstants;
import RestauranTO.Database.CDatabaseConnection;
import RestauranTO.Database.CDatabaseConnectionConfig;
import RestauranTO.Database.Dao.RestaurantDAO;
import RestauranTO.Database.Datamodel.TblRestaurant;
import RestauranTO.Database.Datamodel.TblUser;
public class CRestaurantSelectorController extends SelectorComposer<Component> {
private static final long serialVersionUID = -2878542862853962669L;
@Wire
Label labelName;
@Wire
Label labelDirection;
@Wire
Label labelDescription;
@Wire
Label labelEmail;
@Wire
Label labelZona;
@Wire
Window windowRestaurantSelector;
@Wire
Button buttonAddRating;
protected TblUser tblUser = null;
protected Session sesion = Sessions.getCurrent();
protected final Execution execution = Executions.getCurrent();
protected TblRestaurant SelectedRestaurant = null;
public void doAfterCompose( Component comp ) {
try {
super.doAfterCompose( comp );
TblRestaurant tblrestaurant = ( TblRestaurant ) execution.getArg().get( "tblRestaurant" );
tblUser = ( TblUser ) sesion.getAttribute( SystemConstants._Operator_Credential_Session_Key );
if ( tblUser != null)
buttonAddRating.setVisible( true );
if (tblrestaurant != null) {
CDatabaseConnection databaseConnection = new CDatabaseConnection();
CDatabaseConnectionConfig databaseConnectionConfig = new CDatabaseConnectionConfig();
String strRunningPath = Sessions.getCurrent().getWebApp().getRealPath( SystemConstants._Web_Inf_Dir ) + File.separator;
if ( databaseConnectionConfig.loadConfig( strRunningPath + SystemConstants._Config_Dir + SystemConstants._Database_Config_File ) ) {
if ( databaseConnection.makeConnectionToDatabase( databaseConnectionConfig ) ) {
SelectedRestaurant = ( TblRestaurant ) RestaurantDAO.SearchOneRestaurant( databaseConnection, tblrestaurant.getStrID() );
databaseConnection.closeConnectionToDB();
}
}
}
if ( SelectedRestaurant != null ) {
labelName.setValue( SelectedRestaurant.getStrName() );
labelDescription.setValue( SelectedRestaurant.getStrDescription() );
labelDirection.setValue( SelectedRestaurant.getStrDirection() );
labelEmail.setValue( SelectedRestaurant.getStrEmail() );
labelZona.setValue( SelectedRestaurant.getZone() );
}
}
catch ( Exception Ex ) {
Ex.printStackTrace();
}
}
@Listen( "onClick=#buttonAddRating" )
public void onClickbuttonAddRating( Event event ) {
Map<String, Object> arg = new HashMap<String, Object>();
arg.put("RestaurantID", SelectedRestaurant.getStrID());
Window win = ( Window ) Executions.createComponents( "/views/rating/rating.zul", null, arg );
win.doModal();
}
@Listen( "onClick=#buttonRatingList" )
public void onClickbuttonRatingList( Event event ) {
Map<String, Object> arg = new HashMap<String, Object>();
arg.put("RestaurantID", SelectedRestaurant.getStrID());
Window win = ( Window ) Executions.createComponents( "/views/rating/rating.zul", null, arg );
win.doModal();
}
}
| 2eff47935644c48340a39342f0b653da7458d440 | [
"Java"
] | 12 | Java | CodingDreamteam/RestauranTO | ed14d142315d088f1c3fabd311e313941be58749 | 70b558a42c65d67a15024b9282700045ce89222c |
refs/heads/master | <repo_name>ArtWDrahn/Projects<file_sep>/StringUnitTests/StringTests.cs
//-----------------------------------------------------------------------
// <copyright file="StringTests.cs" company="<NAME>">
// Copyright (c), <NAME>. All rights reserved.
// </copyright>
// <summary>
// Testing for all of the string methods.
// </summary>
// <author>
// <NAME> (<EMAIL>)
// </author>
//-----------------------------------------------------------------------
namespace StringUnitTests
{
using CustomString;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// The string tests.
/// </summary>
[TestClass]
public class StringTests
{
/// <summary>
/// The reverse a string unit test.
/// </summary>
[TestMethod]
public void ReverseAStringUnitTest()
{
const string TestString = "This is a test.";
const string ExpectedOutput = ".tset a si sihT";
Assert.AreEqual(Manipulate.Reverse(TestString), ExpectedOutput);
}
}
}
<file_sep>/Program.cs
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="<NAME>">
// Copyright (c), <NAME>. All rights reserved.
// </copyright>
// <summary>
// Base Program
// </summary>
// <author>
// <NAME> (<EMAIL>)
// </author>
//-----------------------------------------------------------------------
namespace MegaProjectList
{
/// <summary>
/// The program.
/// </summary>
public class Program
{
/// <summary>
/// The main.
/// </summary>
/// <param name="args">
/// The args.
/// </param>
public static void Main(string[] args)
{
// string input = "this is a string";
}
}
}
| ff893ae59bed528cd525dd2dcfcfc6941faa45e4 | [
"C#"
] | 2 | C# | ArtWDrahn/Projects | b04236e70f99971651b2cd5eadf3d092f813ab46 | 5852ce522e4c9aa7c03b7532ded4305891c1528a |
refs/heads/master | <file_sep>import React from 'react';
import TranPhu from '../../component/place/tranPhu';
const ComponentCenter = () => {
return (
<>
<TranPhu />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import ElectronicBill from '../../component/serviceOrther/ElectronicBill';
const ComponentCenter = () => {
return (
<>
<ElectronicBill />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {Controller, useFormContext} from 'react-hook-form';
import TextFieldInput from '../../../../common/TextFieldInput';
const DetailInfo = () => {
const methods = useFormContext();
const {formState: {errors}, control} = methods;
return (
<>
<div>
<Controller
name={ 'codeTypeRoom' }
control={ control }
rules={ {required: true} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Mã loại phòng" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.code_type_room?.type === 'required' ? 'Mã loại không được bỏ trống!' : null }/> }/>
<Controller
name={ 'name' }
control={ control }
rules={ {required: true} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Tên loại phòng" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.name_type_room?.type === 'required' ? 'Tên tiện ích không được bỏ trống!' : null }/> }/>
<Controller
name={ 'priceTypeRoom' }
control={ control }
rules={ {} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Giá dịch vụ/giờ" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null }/> }/>
{/*<div className="pt-4 pb-2">*/}
{/* <DateSingle title="Ngày tạo" classNameTitle="w-1/4"*/}
{/* onChange={ setForm }*/}
{/* value={ form } keySearch="date_created"*/}
{/* />*/}
{/*</div>*/}
<Controller
name={ 'description' }
control={ control }
rules={ {} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Ghi chú" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null }/> }/>
</div>
</>
);
};
DetailInfo.propTypes = {
setForm: PropTypes.func,
form: PropTypes.object
};
export default DetailInfo;<file_sep>import React from 'react';
const Introduce = () => {
return (
<>
<h1>{ 'Viết code cho trang "Giới thiệu" tại đây' }</h1>
</>
);
};
export default Introduce;<file_sep>// import React from 'react';
// const Permission = () => {
// return (
// <>
// </>
// );
// };
// export default Permission;<file_sep>import React from 'react';
import LeDucTho from '../../component/place/leDucTho';
const ComponentCenter = () => {
return (
<>
<LeDucTho />
</>
);
};
export default ComponentCenter;<file_sep>import React, {useEffect, useRef, useState} from 'react';
import Button from '@material-ui/core/Button';
import Checkbox from '@material-ui/core/Checkbox';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from '@material-ui/core/FormGroup';
// import FormLabel from '@material-ui/core/FormLabel';
import IconButton from '@material-ui/core/IconButton';
import {withStyles} from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import CloseIcon from '@material-ui/icons/Close';
import PropTypes from 'prop-types';
import {useQuery} from 'react-query';
import {getListBook} from '../../../../service/bookAnOffices/bookAnOffices';
const styles = (theme) => ({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
const DialogTitle = withStyles(styles)((props) => {
const {children, classes, onClose, ...other} = props;
return (
<MuiDialogTitle disableTypography className={ classes.root } { ...other }>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton aria-label="close" className={ classes.closeButton } onClick={ onClose }>
<CloseIcon/>
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogService = ({
setOpenDialog,
openDialog,
setListDate,
listDate,
dataItem,
indexs,
color = 'primary',
...other
}) => {
const ref = useRef(null);
const handleEntering = () => {
if (ref.current != null) {
ref.current.focus();
}
};
const handleCancel = () => {
setOpenDialog(!openDialog);
};
const {data} = useQuery(
['LIST_SERVICE_12'],
() => getListBook().getListService(),
{
keepPreviousData: true, staleTime: 5000,
}
);
const [dataNew, setDataNew] = useState(dataItem.length > 0 ? dataItem : data);
useEffect(() => {
if (dataItem.length > 0) {
setDataNew(dataItem);
} else {
setDataNew(data);
}
}, [data, dataItem]);
const [stateAll, setStateAll] = useState(false);
const handleChange = (e) => {
setDataNew(
dataNew.map((item) => {
return {
...item,
checked: item.id.toString() === e.target.id ? e.target.checked : item.checked
};
})
);
};
useEffect(() => {
setListDate(listDate.map((item, index) => {
return {
...item,
// listService: index === index ? dataNew.filter(i => i.checked).map(j => j.id.toString()) : item.listShift
listService: indexs === index ? dataNew : item.listService
};
}));
}, [dataNew]);
useEffect(() => {
setStateAll(
dataNew.filter(item => item.checked).length === data.length
);
}, [dataNew]);
const handleChangeAll = () => {
setStateAll(!stateAll);
setDataNew(
dataNew.map((item) => {
return {
...item,
checked: !stateAll
};
})
);
};
return (
<Dialog
disableBackdropClick
disableEscapeKeyDown
fullWidth={ true }
maxWidth={ 'md' }
onEntering={ handleEntering }
aria-labelledby="confirmation-dialog-title"
open={ openDialog }
{ ...other }
height={ '180px' }
>
<DialogTitle id="confirmation-dialog-title" onClose={ handleCancel }>Lựa chọn tiện ích đi kèm</DialogTitle>
<DialogContent dividers>
<div>
<FormControl component="fieldset" className={ 'w-full' }>
{/*<FormLabel component="legend">Chọn tất cả</FormLabel>*/}
<FormGroup>
<div className='grid grid-cols-4 gap-2 w-full'>{
dataNew.map((item, index) => {
return (
<FormControlLabel key={ index }
control={ <Checkbox checked={ item.checked }
onChange={ e => handleChange(e) } id={ item.id.toString() }
color={ color }/> }
label={ item.value }
/>
);
})
}
<FormControlLabel control={ <Checkbox checked={ stateAll } onChange={ handleChangeAll } color={ color }/> }
label={ 'Tất cả' }/>
</div>
</FormGroup>
</FormControl>
</div>
</DialogContent>
<DialogActions>
<Button color="primary" variant="contained" onClick={ handleCancel }>
Đóng
</Button>
</DialogActions>
</Dialog>
);
};
DialogService.propTypes = {
setOpenDialog: PropTypes.func,
openDialog: PropTypes.bool,
setListDate: PropTypes.func,
listDate: PropTypes.array,
indexs: PropTypes.number,
dataItem: PropTypes.array,
color: PropTypes.string
};
export default DialogService;<file_sep>import React from 'react';
const KhuatDuyTien = () => {
return (
<>
<h1>{ 'Viết code cho màn hình "địa điểm <NAME>" tại đây' }</h1>
</>
);
};
export default KhuatDuyTien;<file_sep>import { atom } from 'recoil';
const today = new Date();
export const branchFilterParamsState = atom({
key: 'branchFilterParamsState',
default: {
strSearch: '',
codeSearch: '',
debitSearch: 99,
from_date: today,
to_date: today,
}
});
export const branchPageLimitState = atom({
key: 'branchPageLimitState',
default: 15
});
export const branchPageState = atom({
key: 'branchPageState',
default: 1
});<file_sep>import React, {useState} from 'react';
import {DataGrid, GridToolbarColumnsButton, GridToolbarContainer} from '@material-ui/data-grid';
import PropTypes from 'prop-types';
import {useQueryClient} from 'react-query';
import CustomNoRowsOverlay from './tableDetail/CustomNoRowsOverlay';
const CustomToolbar = () => {
return (
<GridToolbarContainer>
<GridToolbarColumnsButton/>
<div className="px-4"/>
</GridToolbarContainer>
);
};
const DataGridDemo = ({
columns, datas, queryKey,
keyId, detailFunction, setId,
setOpenDialog, idDetail,
heightTable = 690,
pageLimit
}) => {
const [dataTable, setDataTable] = useState(datas);
React.useEffect(() => {
setDataTable(datas.data);
}, [datas]);
const queryClient = useQueryClient();
// eslint-disable-next-line no-unused-vars
const expandChange = async (event) => {
await queryClient.prefetchQuery(
[queryKey, event.dataItem[keyId]],
() => detailFunction(event.dataItem[keyId]),
{staleTime: 5000}
);
};
const getDemo = async (event) => {
if (event.field === idDetail) {
// let is_expanded = dataTable.findIndex(item => item[ keyId ] === event.id);
await queryClient.prefetchQuery(
[queryKey, event.id],
() => detailFunction(event.id),
{staleTime: 5000}
);
setId(event.id);
setOpenDialog(true);
}
};
return (
<div style={ {height: heightTable, width: '100%'} }>
<DataGrid
checkboxSelection={ true }// hộp kiểm thử
disableSelectionOnClick={ true }// click trên cả thanh
components={ {
NoRowsOverlay: CustomNoRowsOverlay,
Toolbar: CustomToolbar,
} }
disableColumnMenu={ true }// menu từng cột (dấu 3 chấm)
disableColumnFilter={ true }// bộ lọc tổng
rows={ dataTable }
columns={ columns }
pageSize={ pageLimit }// số lượng hàng trong bảng
onCellClick={ getDemo }
/>
</div>
);
};
DataGridDemo.propTypes = {
columns: PropTypes.array,// mảng cột
datas: PropTypes.object,//object dữ liệu
queryKey: PropTypes.string,// key nạp trước dữ liệu
keyId: PropTypes.string, // key lọc
detailFunction: PropTypes.func,//hàm nạp trước dữ liệu
openDialog: PropTypes.bool,
setOpenDialog: PropTypes.func,
idDetail: PropTypes.string,// khóa được chọn khi click vào bảng
heightTable: PropTypes.number,
setId: PropTypes.func,
pageLimit: PropTypes.number
};
export default DataGridDemo;
<file_sep>import React from 'react';
import BranchRevenueChart from './chart/BranchRevenueChart';
import CompareRevenueChart from './chart/CompareRevenueChart';
import DebtPriceChart from './chart/DebtPriceChart';
import RatioBranchRevenueChart from './chart/RatioBranchRevenueChart';
import RoomRevenueChart from './chart/RoomRevenueChart';
import { data, data1, data2, data3 } from './data';
const Overview = () => {
return (
<>
<div className="grid md:grid-cols-3 gap-4 grid-cols-1">
<div className="col-span-2 grid grid-rows-5 grid-flow-col gap-4">
<div className="row-span-2">
<CompareRevenueChart data={ data } />
</div>
<div className="row-span-3">
<BranchRevenueChart data={ data1 } />
</div>
</div>
<div className="grid grid-rows-3 grid-flow-col gap-4">
<RatioBranchRevenueChart data={ data2 } />
<RoomRevenueChart data={ data3 } />
<DebtPriceChart data={ data3 } />
</div>
</div>
</>
);
};
export default Overview;<file_sep>const getYearMonthDay = (date, type = 'yyyy-MM-dd') => {
// type = yyyy-MM-dd
// type = dd-MM-yyyy
const d = new Date(date);
const day = `0${d.getDate()}`.slice(-2);
const month = `0${d.getMonth() + 1}`.slice(-2);
const year = d.getFullYear();
if (type === 'dd-MM-yyyy') {
return day + '-' + month + '-' + year;
} else {
return year + '-' + month + '-' + day;
}
};
const formatCurrency = (number) => {
return number.toLocaleString('it-IT', {style: 'currency', currency: 'VND'});
};
const toThousandFilter = (num, precision) => {
precision = [undefined, null].includes(precision) ? 3 : precision;
let roundLevel = 1;
while (precision > 0) {
precision--;
roundLevel *= 10;
}
const temp = (Math.round((+num || 0) * roundLevel) / roundLevel).toString().replace('.', ',');
return temp.replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, '.'));
};
export {
getYearMonthDay, formatCurrency, toThousandFilter
};<file_sep>import React from 'react';
const Telecommunication = () => {
return (
<>
<h1>{ 'Viết code cho trang "Dịch vụ viễn thông" ở đây' }</h1>
</>
);
};
export default Telecommunication;<file_sep>import React, {useCallback, useEffect, useState} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import {useQuery} from 'react-query';
import {useRecoilValue} from 'recoil';
import {LIST_ORDER_PLACEHOLDER_DATA} from '../../../../fixedData/dataEmployee';
import {getListAppointment} from '../../../../service/book/listBook/appointment';
import {
listBookColumnTableState,
listBookFilterParamsState,
listBookPageLimitState,
listBookPageState
} from '../../../../store/atoms/book/appointment';
import TableV7 from '../../../common/table/TableV7';
import DialogDetail from './Dialog/DialogDetail';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
paper: {
width: '80%',
maxHeight: 1835,
},
}));
const ListBook = () => {
const classes = useStyles();
const columnTable = useRecoilValue(listBookColumnTableState);
const filterParams = useRecoilValue(listBookFilterParamsState);
const pageLimit = useRecoilValue(listBookPageLimitState);
const page = useRecoilValue(listBookPageState);
const getData = useCallback(async (page, pageLimit) => {
const {
strSearch
} = filterParams;
return await getListAppointment().getList({
page, pageLimit, strSearch
});
}, [pageLimit, filterParams, page.skip]);
const {data, refetch} = useQuery(
['PRODUCT_LIST_KEY_LIST_BOOK', page.skip, JSON.stringify(filterParams)],
() => getData(page.skip, pageLimit),
{
keepPreviousData: true, staleTime: 5000,
placeholderData: LIST_ORDER_PLACEHOLDER_DATA
}
);
useEffect(() => {
refetch();
}, [pageLimit, filterParams, page]);
const [openDialog, setOpenDialog] = useState(false);
const [id, setId] = useState(0);
return (
<>
<TableV7 columns={ columnTable } datas={ data }
queryKey='PRODUCT_LIST_KEY_LIST_BOOK_DETAIL' idDetail='detail'
keyId="id" detailFunction={ getListAppointment().getDetail }
// openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
pageState={ listBookPageState }
setId={ setId }
pageLimitState={ listBookPageLimitState }/>
{openDialog &&
<DialogDetail
classes={ {
paper: classes.paper,
} }
id={ id }
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
queryKey='PRODUCT_LIST_KEY_LIST_BOOK_DETAIL'
detailFunction={ getListAppointment().getDetail }
/>
}
</>
);
};
export default ListBook;<file_sep>// import React from 'react';
// import Button from '@material-ui/core/Button';
// import Dialog from '@material-ui/core/Dialog';
// import DialogActions from '@material-ui/core/DialogActions';
// import DialogContent from '@material-ui/core/DialogContent';
// import DialogTitle from '@material-ui/core/DialogTitle';
// import FormControlLabel from '@material-ui/core/FormControlLabel';
// // import List from '@material-ui/core/List';
// import ListItem from '@material-ui/core/ListItem';
// import ListItemText from '@material-ui/core/ListItemText';
// import Radio from '@material-ui/core/Radio';
// import RadioGroup from '@material-ui/core/RadioGroup';
// import { makeStyles } from '@material-ui/core/styles';
// import PropTypes from 'prop-types';
// const options = [
// 'None',
// 'Atria',
// 'Callisto',
// 'Dione',
// 'Ganymede',
// '<NAME>',
// 'Luna',
// 'Oberon',
// 'Phobos',
// 'Pyxis',
// 'Sedna',
// 'Titania',
// 'Triton',
// 'Umbriel',
// ];
// const ConfirmationDialogRaw = (props) => {
// const { onClose, value: valueProp, open, ...other } = props;
// const [ value, setValue ] = React.useState(valueProp);
// const radioGroupRef = React.useRef(null);
// React.useEffect(() => {
// if (!open) {
// setValue(valueProp);
// }
// }, [ valueProp, open ]);
// const handleEntering = () => {
// if (radioGroupRef.current != null) {
// radioGroupRef.current.focus();
// }
// };
// const handleCancel = () => {
// onClose();
// };
// const handleOk = () => {
// onClose(value);
// };
// const handleChange = (event) => {
// setValue(event.target.value);
// };
// return (
// <Dialog
// disableBackdropClick
// disableEscapeKeyDown
// // maxWidth="md"
// fullWidth={ true }
// onEntering={ handleEntering }
// aria-labelledby="confirmation-dialog-title"
// open={ open }
// { ...other }
// height={ '180px' }
// // maxHeight={ true }
// >
// <DialogTitle id="confirmation-dialog-title">Phone Ringtone</DialogTitle>
// <DialogContent dividers>
// <RadioGroup
// ref={ radioGroupRef }
// aria-label="ringtone"
// name="ringtone"
// value={ value }
// onChange={ handleChange }
// >
// { options.map((option) => (
// <FormControlLabel value={ option } key={ option } control={ <Radio /> } label={ option } />
// )) }
// </RadioGroup>
// </DialogContent>
// <DialogActions>
// <Button autoFocus onClick={ handleCancel } color="primary">
// Cancel
// </Button>
// <Button onClick={ handleOk } color="primary">
// Ok
// </Button>
// </DialogActions>
// </Dialog>
// );
// };
// ConfirmationDialogRaw.propTypes = {
// onClose: PropTypes.func.isRequired,
// open: PropTypes.bool.isRequired,
// value: PropTypes.string.isRequired,
// };
// const useStyles = makeStyles((theme) => ({
// root: {
// width: '100%',
// maxWidth: 360,
// backgroundColor: theme.palette.background.paper,
// },
// paper: {
// width: '80%',
// maxHeight: 485,
// },
// }));
// const ConfirmationDialog = () => {
// const classes = useStyles();
// const [ open, setOpen ] = React.useState(false);
// const [ value, setValue ] = React.useState('Dione');
// const handleClickListItem = () => {
// setOpen(true);
// };
// const handleClose = (newValue) => {
// setOpen(false);
// if (newValue) {
// setValue(newValue);
// }
// };
// return (
// <div className={ classes.root }>
// <ListItem
// button
// divider
// aria-controls="ringtone-menu"
// aria-label="phone ringtone"
// onClick={ handleClickListItem }
// role="listitem" >
// <ListItemText primary="Phone ringtone" secondary={ value } />
// </ListItem>
// <ConfirmationDialogRaw
// classes={ {
// paper: classes.paper,
// } }
// id="ringtone-menu"
// keepMounted
// open={ open }
// onClose={ handleClose }
// value={ value }
// />
// </div>
// );
// };
// export default ConfirmationDialog;
<file_sep>import React from 'react';
// import { branchFilterParamsState } from '../../../store/actom/branch/branch';
// import CardBranch from '../../common/filters/CardBranch';
import PropTypes from 'prop-types';
import SelectedInput from '../../common/SelectedInput';
import ItemCard from './ItemCard';
const arrBranch = [
{ id: '1', text: 'Chi nhánh Thanh Xuân' },
{ id: '2', text: 'Chi nhánh Nam Từ Liêm' },
{ id: '3', text: 'Chi nhánh Hà Đông' },
{ id: '4', text: 'Chinh nhánh Đống Đa' }
];
const pyteRoom = [
{ id: '1', text: 'Phòng họp' },
{ id: '2', text: 'Văn phòng làm việc' },
{ id: '3', text: 'Văn phòng ảo' },
{ id: '4', text: 'Chỗ ngồi làm việc' }
];
const people_max = [
{ id: '1', text: '5 người' },
{ id: '2', text: '10 người' },
{ id: '3', text: '20 người' },
{ id: '4', text: '20 người' }
];
const dataArr = [
{},
{},
{},
{},
{}
];
const SelectedBranch = ({ setState }) => {
const [ value, setValue ] = React.useState('');
const onChange = (value) => {
setValue(value);
};
const [ room, setRoom ] = React.useState('');
const onChangeRoom = (value) => {
setRoom(value);
};
const [ people, setPeople ] = React.useState('');
const onChangePeople = (value) => {
setPeople(value);
};
return (
<>
<div className="grid grid-cols-4 gap-4 mt-8">
<div className="border">
<div className="p-4">
<p className="mb-4 font-bold">Tìm kiếm theo yêu cầu</p>
{/* <CardBranch filterParams={ branchFilterParamsState } widthTitle='w-1/4' /> */ }
<SelectedInput title={ 'Chi nhánh' } dataArr={ arrBranch } value={ value } onChange={ e => onChange(e.target.value) } />
<SelectedInput title={ 'Loại phòng' } dataArr={ pyteRoom } value={ room } onChange={ e => onChangeRoom(e.target.value) } />
<SelectedInput title={ 'Số người tối đa' } dataArr={ people_max } value={ people } onChange={ e => onChangePeople(e.target.value) } />
</div>
</div>
<div className="col-span-3 border">
<h4 className="pb-2 p-4 font-bold">Danh sách kết quả tìm kiếm theo yêu cầu (<span className="text-blue-600">{ ' 5/40 ' }</span>)</h4>
<div className="border-t-2 mx-8">
<div className="my-4 grid grid-cols-4 gap-8">
{
dataArr.map((item, index) => {
return (
<ItemCard key={ index } dataItem={ item } setState={ setState } />
);
})
}
</div>
</div>
</div>
</div>
</>
);
};
SelectedBranch.propTypes = {
setState: PropTypes.func
};
export default SelectedBranch;<file_sep>// Constant query key
//Auth
export const AUTH_LOGIN_KEY = 'auth_login_key';
export const AUTH_USER_INFO_KEY = 'auth_user_info_key';
export const USER_INFO = 'user_info';
export const CURRENT_BRANCH = 'branch';
export const ACCESS_TOKEN = 'csoffice_accessToken';
// Contract
export const CONTRACR_LIST_KEY = 'contract_list_key';
export const CONTRACT_LIST_DETAIL_KEY = 'contract_list_detail_key';<file_sep>import React from 'react';
import TableDetail from './tableDetail';
const data = [
{id: 1, name: '304', numberRoom: 14, time: 'Ca 1', branch: 'Chi nhánh thanh xuân'},
{id: 2, name: '305', numberRoom: 11, time: 'Ca 3', branch: 'Chi nhánh thanh xuân'},
{id: 3, name: '404', numberRoom: 10, time: 'Ca 4', branch: 'Chi nhánh thanh xuân'}
];
const TableSearch = () => {
return (
<>
<div className='mt-3'>
<TableDetail text_center={ 'text-center' }/>
{
data.map((item, index) => {
return (
<TableDetail data={ item } key={ index } buttonDelete={ true }/>
);
})
}
</div>
</>
);
};
export default TableSearch;<file_sep>// import React from 'react';
// import Maintenance from '../../components/room/maintenance';
// import Breadcrumbs from '../../components/room/maintenance/Breadcrumbs';
// import LayoutLink from '../../layoutLink';
// const Room = () => {
// return (
// <>
// <LayoutLink title="Bảo trì" titleLink={ Breadcrumbs }>
// <Maintenance />
// </LayoutLink>
// </>
// );
// };
// export default Room;
<file_sep>import {atom} from 'recoil';
const today = new Date();
export const listBranchFilterParamsState = atom({
key: 'listBranchFilterParamsState',
default: {
strSearch: '',
codeSearch: '',
// nameSearch: '',
// orderType: 99,
// branchSearch: [],
// statusSearch: 99,
// Branchale: [],
// employeePT: [],
// tablePriceSearch: [],
// promotionSearch: [],
debitSearch: 99,
from_date: today,
to_date: today,
// from_date_expire: '',
// to_date_expire: '',
// status_expire: 99
}
});
export const listBranchPageLimitState = atom({
key: 'listBranchPageLimitState',
default: 15
});
export const listBranchPageState = atom({
key: 'listBranchPageState',
default: 1
});
export const listBranchColumnTableState = atom({
key: 'listBranchColumnTableState',
default: [
{
field: 'detail',
headerName: 'Chi tiết',
width: 80,
sortable: false,
description: 'Chi tiết',
cellClassName: 'cursor-pointer'
},
{field: 'codeBranch', headerName: 'Mã chi nhánh', width: 150, sortable: false, description: 'Mã chi nhánh'},
{field: 'name', headerName: 'Tên chi nhánh', width: 200, sortable: false, description: 'Tên chi nhánh'},
{field: 'address', headerName: 'Địa chỉ', width: 300, sortable: false, description: 'Địa chỉ'},
{
field: 'phoneNumber',
headerName: 'SĐT chi nhánh',
width: 150,
sortable: false,
description: 'Số điện thoại chi nhánh'
},
{
field: 'branchManager',
headerName: 'Tên quản lý',
width: 150,
sortable: false,
description: 'Quản lý của chi nhánh'
},
{
field: 'phoneNumberManager',
headerName: 'SĐT của quản lý',
width: 150,
sortable: false,
description: 'Số điện thoại của quản lý'
},
{field: 'createDate', headerName: 'Ngày tạo', width: 170, sortable: false, description: 'Ngày tạo chi nhánh'},
{
field: 'status',
headerName: 'Trạng thái',
width: 170,
sortable: false,
description: 'Trạng thái hoạt động của chi nhánh'
},
{field: 'description', headerName: 'Ghi chú', width: 290, sortable: false, description: 'Ghi chú'},
]
});<file_sep>import React from 'react';
import KhuatDuyTien from '../../component/place/khuatDuyTien';
const ComponentCenter = () => {
return (
<>
<KhuatDuyTien />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import PropTypes from 'prop-types';
const RadioSex = ({ value, onChange }) => {
// const [ value, setValue ] = React.useState(values);
// const handleChange = (event) => {
// setValue(event.target.value);
// };
return (
<>
<div className="flex items-center flex-full">
<span className='pr-6 font-medium text-sm'>Giới tính</span>
<FormControl component="fieldset">
<RadioGroup row aria-label="position" defaultValue={ '0' } name="position" onChange={ onChange }>
<FormControlLabel
value={ '0' }
control={ <Radio color="primary" size="small" /> }
label="Nam"
labelPlacement="end"
onChange={ onChange }
checked={ value === '0' }
/>
<FormControlLabel
value={ '1' }
control={ <Radio color="primary" size="small" /> }
label="Nữ"
labelPlacement="end"
onChange={ onChange }
checked={ value === '1' }
/>
</RadioGroup>
</FormControl>
</div>
</>
);
};
RadioSex.propTypes = {
value: PropTypes.string,
filterParams: PropTypes.object,
onChange: PropTypes.func
};
export default RadioSex;
<file_sep>import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Menu from '@material-ui/core/Menu';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import DateRange from '@material-ui/icons/DateRange';
import PropTypes from 'prop-types';
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
const defaultDate = [
{
id: 'day',
name: 'Ngày',
item: [
{ id: '11', name: 'Hôm nay' },
{ id: '12', name: 'Hôm qua' }
]
},
{
id: 'week',
name: 'Tuần',
item: [
{ id: 21, name: 'Tuần này' },
{ id: 22, name: 'Tuần trước' }
]
},
{
id: 'month',
name: 'Tháng',
item: [
{ id: 31, name: 'Tháng này' },
{ id: 32, name: 'Tháng trước' }
]
},
{
id: 'periodic',
name: 'Quý',
item: [
{ id: 41, name: 'Quý này' },
{ id: 42, name: 'Quý trước' }
]
},
{
id: 'year',
name: 'Năm',
item: [
{ id: 51, name: 'Năm này' },
{ id: 52, name: 'Năm trước' },
{ id: 53, name: 'Toàn thời gian' }
]
}
];
const DateSelection = ({ title }) => {
// const [ paramDate, setParamDate ] = React.useState({ fromDate: '', toDate: '' });
const [ anchorEl, setAnchorEl ] = useState(null);
const [ openDefault, setOpenDefault ] = useState('0');
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(!anchorEl);
};
const handleDefaultDate = (event) => {
setOpenDefault(event.target.value);
};
const handleSearch = () => {
};
const [ fromDay, setFromDay ] = useState(new Date());
const handleFromDayClick = (day, { selected }) => {
setFromDay(selected ? undefined : day);
};
const [ toDay, setToDay ] = useState(new Date());
const handleToDayClick = (day, { selected }) => {
setToDay(selected ? undefined : day);
};
return (
<>
<div className="shadow-md bg-white">
<div className="flex items-center h-full">
<span className='pr-6 pl-4 font-medium'>{ title }</span>
<div className="flex mr-3" aria-controls="simple-menu" aria-haspopup="true" onClick={ handleClick }>
<p className='border-b-1 px-10 border-gray-500 cursor-pointer'>
20-24/03/2021
</p>
<DateRange className="cursor-pointer" />
</div>
</div>
<Menu
id="simple-menu"
anchorEl={ anchorEl }
keepMounted
open={ Boolean(anchorEl) }
onClose={ handleClose }
>
<div className="px-4">
<div style={ { borderBottom: '1px solid gray' } }>
<RadioGroup row aria-label="position" defaultValue={ '0' } name="position" onChange={ handleDefaultDate }>
<FormControlLabel
value={ '0' }
control={ <Radio color="primary" /> }
label="Có sẵn"
labelPlacement="end"
onChange={ handleDefaultDate }
checked={ openDefault === '0' }
/>
<FormControlLabel
value={ '1' }
control={ <Radio color="primary" /> }
label="Tự chọn"
labelPlacement="end"
onChange={ handleDefaultDate }
checked={ openDefault === '1' }
/>
</RadioGroup>
</div>
<div>
{
openDefault === '0' &&
<div className="flex pt-4">
{
defaultDate.map((item, index) => {
return (
<div key={ index } className="px-1">
<p>{ item.name }</p>
{
item.item.map((i, x) => {
return (
<p key={ x } className="cursor-pointer p-2 hover:text-blue-800 text-blue-500">{ i.name }</p>
);
})
}
</div>
);
})
}
</div>
}
{
openDefault === '1' &&
<div className="">
<div className="grid grid-cols-2">
<div className="mt-4">
<span>Ngày bắt đầu</span>
<span className="border-b-1 px-10 text-blue-500">{ fromDay ? fromDay.toLocaleDateString() : null }</span>
</div>
<div className="mt-4">
<span>Ngày kết thúc</span>
<span className="border-b-1 px-10 text-blue-500">{ toDay ? toDay.toLocaleDateString() : null }</span>
</div>
</div>
<div className="flex items-start">
<DayPicker
selectedDays={ fromDay }
onDayClick={ handleFromDayClick }
todayButton="Tháng này"
// modifiers={ {
// foo: new Date(),
// } }
/>
<DayPicker
selectedDays={ toDay }
onDayClick={ handleToDayClick }
todayButton="Tháng này"
// month={ new Date() }
// todayButton="Go to Today"
// modifiers={ {
// foo: new Date(),
// } }
// onTodayButtonClick={ (day, modifiers) => console.log(day, modifiers) }
/>
</div>
<div className="flex justify-end">
<Button autoFocus onClick={ handleSearch } color="primary">
Tìm kiếm
</Button>
</div>
</div>
}
</div>
</div>
</Menu>
</div>
</>
);
};
DateSelection.propTypes = {
filterParams: PropTypes.object,
title: PropTypes.string
};
export default DateSelection;<file_sep>// import React from 'react';
//
// import {useQuery} from 'react-query';
//
// import {getListBook} from './bookAnOffices/bookAnOffices';
//
// const DataBranch =() => {
// const {data} = useQuery(
// ['DATA_BRANCH'],
// () => getListBook().getList(),
// {
// keepPreviousData: true, staleTime: 5000,
// }
// );
// return data;
// };
// export default DataBranch;<file_sep>import React from 'react';
const CreativeContent = () => {
return (
<>
<h1>{ 'Viết code cho trang "Creative Content" ở đây' }</h1>
</>
);
};
export default CreativeContent;
<file_sep>import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from '@material-ui/core/FormGroup';
import { makeStyles } from '@material-ui/core/styles';
import DateSingle from '../../../base/dateTime/DateSingle';
import UseDate from './useDate';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
},
formControl: {
margin: theme.spacing(3),
},
}));
const listUtilities = [
{ id: 1, text: 'Má<NAME>', status: false, name: 'mayin' },
{ id: 2, text: 'Má<NAME>', status: false, name: 'mayfax' },
{ id: 3, text: 'Má<NAME>́u', status: false, name: 'maychieu' },
{ id: 4, text: 'Lễ tân', status: false, name: 'letan' },
{ id: 5, text: 'Bảo vệ 24/7', status: false, name: 'baove24/7' },
{ id: 6, text: 'Chỗ đỗ xe', status: false, name: 'chodoxe' },
{ id: 7, text: 'Luậ<NAME> <NAME>', status: false, name: 'luatsurieng' },
];
const RoomInfo = () => {
const classes = useStyles();
const [ state, setState ] = React.useState(listUtilities);
const [ form, setForm ] = React.useState({});
const handleChange = (event) => {
setState(state.map((item) => {
return {
...item,
status: event.target.name !== item.name ? !event.target.checked : event.target.checked
};
}));
};
return (
<>
<div className="w-full">
<div className="border-2 mx-48">
<h1 className='text-center font-bold text-xl text-blue-800'>Thông tin chi tiết phòng phòng</h1>
<div className="grid grid-cols-3 gap-4 p-4">
<div className="col-span-2 grid grid-rows-2 gap-4">
<div className="row-span-2 border-2 bg-gray-100 px-4 py-2">
<h3 className="text-blue-800 font-bold">Thông tin phòng đặt</h3>
<p>Địa điểm: <span className="font-semibold">Lê Văn Lương - Thanh Xuân - Hà Nội</span></p>
<div className="grid grid-cols-2 gap-4">
<div>
<p >Loại phòng:<span className="font-semibold"> Phòng họp</span></p>
<p>Tên phòng: <span className="font-semibold">Phòng 304</span></p>
</div>
<div>
<p>Số ghế tối đa: <span className="font-semibold">10 ghế</span></p>
</div>
</div>
<p className='pt-3 font-bold pl-10 pb-1'>Các tiện ích lựa chọn</p>
<div className={ classes.root + ' border-2 bg-white' }>
<FormControl component="fieldset" className={ classes.formControl }>
<FormGroup row>
{
state.map((item, index) => {
return (
<FormControlLabel key={ index }
control={ <Checkbox checked={ item.status } onChange={ handleChange } name={ item.name } color="primary" /> }
label={ item.text }
/>
);
})
}
</FormGroup>
</FormControl>
</div>
</div>
<div className="border-2 bg-gray-100 px-4 py-2">
<h3 className="text-blue-800 font-bold">Chọn thời gian sử dụng</h3>
<p className={ 'font-medium' }>Số buổi sử dụng: 10</p>
<div className="flex items-end pb-3 w-full">
<DateSingle title="Ngày bắt đầu sử dụng" classNameTitle="w-1/3" keySearch="start_day" onChange={ setForm } value={ form }/>
</div>
<UseDate />
</div>
</div>
<div className="border-2 bg-gray-100">
<h3 className='text-center text-blue-800 font-bold'>Giá thành thanh toán</h3>
</div>
</div>
</div>
</div>
</>
);
};
export default RoomInfo;<file_sep>import React from 'react';
import DigitalSignatures from '../../component/serviceOrther/DigitalSignatures';
const ComponentCenter = () => {
return (
<>
<DigitalSignatures />
</>
);
};
export default ComponentCenter;<file_sep>import {axiosInstance} from '../../../config/axios';
import {getYearMonthDay} from '../../../helpers/helper';
export const getListService = () => {
// const getList = async (value) => {
// const {
// page = '1', pageLimit = '15', strSearch = '', codeSearch = ''
// } = value;
// const {data} = await axiosInstance.get('/service/find_all');
// return dataProcesing(setDataNew(data), page, pageLimit, [strSearch, codeSearch]);
// };
const getList = async (value) => {
const {
page = '1', pageLimit = '15', strSearch = '', nameRoom = '',
numberPeople = '', branchRoom = [], kindOfRoom = []
} = value;
const {data} = await axiosInstance.get('/service/find_all');
return dataProcesing(setDataNew(data), page, pageLimit, [strSearch, nameRoom, numberPeople], kindOfRoom, branchRoom);
};
const getDetail = async () => {
const {data} = await axiosInstance.get('/employees-employees-employees');
return data;
};
return {getList, getDetail};
};
const dataProcesing = (data, page, limit, filter) => {
if (data.length > 0) {
const dataId = data.filter(i => (filter[0] !== '' ? i.codeService === filter[0] : true)
&& (filter[1] !== '' ? i.name === filter[1] : true));
const startLimit = (page - 1) * limit;
const endLimit = page * limit > data.length ? data.length : page * limit;
const dataNew = dataId.slice(startLimit, endLimit);
return {
data: data,
meta: {
total_data: data.length,
total_dataNew: dataNew.length,
total_dataPage: dataId.length
}
};
} else {
return {
data: [],
meta: {
total_data: 0
}
};
}
};
const setDataNew = (data) => {
return data.map(i => {
return {
...i,
id: i.id,
detail: 'Xem',
createDate: getYearMonthDay(i.createDate, 'dd-MM-yyy'),
statusService: i.status
};
});
};<file_sep>import React from 'react';
import Overview from '../../components/customer/customerBad';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Danh sách báo xấu' ];
const Customer = () => {
return (
<>
<LayoutLink title='Báo xấu' listLink={ listLink }>
<Overview />
</LayoutLink>
</>
);
};
export default Customer;<file_sep>import React from 'react';
import EmployeeList from '../../components/report/revenue';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Báo cáo doanh thu' ];
const Employee = () => {
return (
<>
<LayoutLink title="Báo cáo doanh thu" listLink={ listLink }>
<EmployeeList />
</LayoutLink>
</>
);
};
export default Employee;
<file_sep>import { makeStyles } from '@material-ui/core/styles';
export const a11yProps = (index) => {
return {
id: `full-width-tab-${index}`,
'aria-controls': `full-width-tabpanel-${index}`,
};
};
export const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
width: '100%',
backgroundColor: theme.palette.background.paper,
},
}));
<file_sep>import React, { useCallback, useEffect, useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { useQuery } from 'react-query';
import {
useRecoilValue,
// useRecoilState
} from 'recoil';
import { LIST_ORDER_PLACEHOLDER_DATA } from '../../../../fixedData/dataEmployee';
import { getListEmployees } from '../../../../service/employess/employeeList/listEmployee';
import {
listEmployeesColumnTableState,
listEmployeesFilterParamsState,
listEmployeesPageState,
listEmployeesPageLimitState
} from '../../../../store/atoms/employee/employeeList/listEmployee';
import TableV7 from '../../../common/table/TableV7';
import DialogDetail from '../listEmployee/Dialog/DialogDetail';
import DetailInfo from '../listEmployee/DialogAdd/DialogAddInfo';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
paper: {
width: '80%',
maxHeight: 1835,
},
}));
const ListEmployees = () => {
const classes = useStyles();
const columnTable = useRecoilValue(listEmployeesColumnTableState);
const filterParams = useRecoilValue(listEmployeesFilterParamsState);
const pageLimit = useRecoilValue(listEmployeesPageLimitState);
const page = useRecoilValue(listEmployeesPageState);
// console.log(columnTable);
const getData = useCallback(async (page, pageLimit) => {
const {
strSearch
} = filterParams;
return await getListEmployees().getList({
page, pageLimit, strSearch
});
}, [ pageLimit, filterParams, page.skip ]);
const { data, refetch } = useQuery(
[ 'PRODUCT_LIST_KEY', page.skip, JSON.stringify(filterParams) ],
() => getData(page.skip, pageLimit),
{
keepPreviousData: true, staleTime: 5000,
placeholderData: LIST_ORDER_PLACEHOLDER_DATA
}
);
console.log(data);
useEffect(() => {
refetch();
}, [ pageLimit, filterParams, page ]);
const [ openDialog, setOpenDialog ] = useState({ open: false, id: null });
return (
<>
<TableV7 columns={ columnTable } datas={ data }
queryKey='queryKey' idDetai='detail'
keyId="id_employee" detailFunction={ getListEmployees().getDetail }
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
pageState={ listEmployeesPageState }
pageLimitState={ listEmployeesPageLimitState }
/>
{ openDialog.open &&
<DialogDetail
classes={ {
paper: classes.paper,
} }
id="ringtone-menu"
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
detail={ DetailInfo } />
}
</>
);
};
export default ListEmployees;<file_sep>import React from 'react';
const DigitalSignatures = () => {
return (
<>
<h1>{ 'Viết code cho trang "Chữ ký số" ở đây' }</h1>
</>
);
};
export default DigitalSignatures;
<file_sep>import React from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import PropTypes from 'prop-types';
import {useQuery} from 'react-query';
import {getListBook} from '../../../../service/bookAnOffices/bookAnOffices';
import Filter from '../filter';
// import ServiceBook from '../serviceBook';
import ContinuousUse from './continuousUse';
import IntermittentUse from './intermittentUse';
const SendRequire = ({value, onChange}) => {
const {data} = useQuery(
['LIST_TIME'],
() => getListBook().getListTime(),
{
keepPreviousData: true, staleTime: 5000,
}
);
return (
<>
<div>
<Filter/>
</div>
<FormControl component="fieldset">
<RadioGroup aria-label="gender" name="gender1" value={ value } onChange={ onChange }>
<FormControlLabel value={ 'lien_tuc' } control={ <Radio color={ 'primary' }/> } label="Sử dụng liên tục"/>
<FormControlLabel value={ 'ngat_quang' } control={ <Radio color={ 'primary' }/> } label="Sử dụng theo số buổi"/>
</RadioGroup>
</FormControl>
{value === 'lien_tuc' && <ContinuousUse data={ data }/>}
{value === 'ngat_quang' && <IntermittentUse data={ data }/>}
</>
);
};
SendRequire.propTypes = {
onChange: PropTypes.func,
value: PropTypes.string
};
export default SendRequire;<file_sep>import { axiosInstance } from '../../../config/axios';
export const getListRoom = () => {
const getList1 = async (value) => {
const {page = '1', pageLimit = '15', strSearch ='', nameRoom='',
numberPeople='', branchRoom=[], kindOfRoom=[]}= value;
const { data } = await axiosInstance.get('/room/find_all');
return dataProcesing(setDataNew(data), page, pageLimit, [strSearch, nameRoom, numberPeople],kindOfRoom, branchRoom);
};
const addRoom = async (param) => {
const { data } = await axiosInstance.get('/customers-customers-customers?param=' + param);
return data;
};
const updateRoom = async (id) => {
const { data } = await axiosInstance.put('/customers-customers-customers?param=' + id);
return data;
};
const deleteRoom = async (id) => {
const { data } = await axiosInstance.delete('/customers-customers-customers?param=' + id);
return data;
};
return { addRoom, updateRoom, deleteRoom, getList1 };
};
const dataProcesing = (data, page, limit, filter, kindOfRoom, branchRoom) => {
if(data.length > 0) {
const dataId = data.filter(i => (filter[0] !== '' ? i.codeRoom === filter[0] : true)
&& (filter[1] !== '' ? i.name === filter[1] : true)
&& (filter[2] !== '' ? i.soChoNgoi.toString() === filter[2] : true)
&& (branchRoom.length > 0 ? branchRoom.includes(i.idBranch) : true)
&& (kindOfRoom.length > 0 ? kindOfRoom.includes(i.idTypeRoom) : true));
const startLimit = (page - 1)*limit;
const endLimit = page*limit > data.length ? data.length : page*limit;
const dataNew = dataId.slice(startLimit, endLimit);
return {
data: dataNew,
meta: {
total_data: data.length,
total_dataNew: dataNew.length,
total_dataPage: dataId.length
}
};
} else {
return {
data: [],
meta: {
total_data: 0
}
};
}
};
const setDataNew = (data) => {
return data.map(i => {
return {
...i,
id: i.id,
detail: 'Xem',
idTypeRoom: i.typeRoom.id,
nameTypeRoom: i.typeRoom.name,
idBranch: i.branch1.id,
nameBranch: i.branch1.name,
address: i.branch1.address,
};
});
};<file_sep>import React from 'react';
import ExchangeOffice from '../../component/service/ExchangeOffice';
const ComponentCenter = () => {
return (
<>
<ExchangeOffice />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import TableV7 from '../../common/table/TableV7';
const Decentralization = () => {
return (
<>
<div className="my-1 sticky top-4 responsive-mt-0">
<TableV7 />
</div>
</>
);
};
export default Decentralization;<file_sep>import React, { useState } from 'react';
import Collapse from '@material-ui/core/Collapse';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import { makeStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import { NavLink, useLocation } from 'react-router-dom';
import { useSetRecoilState } from 'recoil';
import { onCloseOpenDrawer } from '../../store/atoms/header/header';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
nested: {
paddingLeft: theme.spacing(4),
},
}));
const MenuBarItem = ({ item }) => {
const setStateMenu = useSetRecoilState(onCloseOpenDrawer);
const classes = useStyles();
const [ open, setOpen ] = useState(false);
const handleClick = () => {
setOpen(!open);
};
const location = useLocation();
return (
<>
<NavLink to={ item.subMenu.length === 0 ? item.path : '#' } >
<ListItem button onClick={ () => handleClick() } >
<ListItemIcon>
{ item.icon }
</ListItemIcon>
<ListItemText primary={ item.title } className={ 'text-blue-900' } />
</ListItem>
</NavLink>
{
<Collapse in={ open } timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{
item.subMenu.map((i, index) => (
<NavLink to={ i.subPath || '#' } key={ index } onClick={ () => setStateMenu(false) }>
<ListItem button className={ classes.nested } selected={ location.pathname === i.subPath } key={ index }>
<ListItemIcon>
{ i.subIcon }
</ListItemIcon>
<ListItemText primary={ i.subTitle } className={ 'text-blue-700' } />
</ListItem>
</NavLink>
))
}
</List>
</Collapse>
}
</>
);
};
MenuBarItem.propTypes = {
item: PropTypes.object,
};
export default MenuBarItem;<file_sep>import React from 'react';
import Payment from './payment';
import SendRequire from './sendRequire';
const BookAnOffice = () => {
const [value, setValue] = React.useState('lien_tuc');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<>
<div className="md:container md:mx-auto">
<h1 className='flex justify-center py-4 mt-8 text-lg font-bold bg-gray-100 mx-48'>ĐĂNG KÝ SỬ DỤNG PHÒNG</h1>
<div className='grid grid-cols-3 gap-2'>
<div className='col-span-2 bg-gray-100 ml-48 mt-2'>
<div>
</div>
<div className='mx-20'>
<SendRequire value={ value } onChange={ handleChange }/>
</div>
</div>
<div className='bg-gray-100 mt-2 mr-48'>
<Payment value={ value }/>
</div>
</div>
</div>
</>
);
};
export default BookAnOffice;<file_sep>import React from 'react';
const BranchHistory = () => {
return (
<>
</>
);
};
export default BranchHistory;<file_sep>import React, {useCallback, useEffect, useState} from 'react';
import {useQuery} from 'react-query';
import {useRecoilState, useRecoilValue} from 'recoil';
import {getListBook} from '../../../../service/bookAnOffices/bookAnOffices';
import {
orderBookFilterParams,
orderBookFilterParamsContinuous,
orderBookFilterParamsState
} from '../../../../store/actom/orderBook/orderBook';
import SelectInput from '../../../base/input/SelectInput';
const MaxPeople = () => {
const [filterState, setFilterState] = useRecoilState(orderBookFilterParamsContinuous);
const filterParams = useRecoilValue(orderBookFilterParamsState);
const [params, setParams] = useRecoilState(orderBookFilterParams);
const getData = useCallback(async () => {
const {branch, typeRoom} = filterParams;
return await getListBook().getListNumberPeoPle({
branch, typeRoom
});
}, [filterParams]);
const {data, refetch} = useQuery(
['LIST_PEOPLE_TYPEROOM_BRANCH', JSON.stringify(filterParams)],
() => getData(),
{
keepPreviousData: true, staleTime: 5000
}
);
useEffect(() => {
refetch();
}, [filterParams]);
const [value, setValue] = useState(data[0].id);
useEffect(() => {
setValue(data[0].id);
}, [data]);
useEffect(() => {
setParams({
...params,
idRoom: value
});
setFilterState({
...filterState,
idRoom: value
});
}, [value]);
const onChage = (e) => {
setValue(e.target.value);
};
return (
<>
<SelectInput title='Số người tối đa' dataArr={ data } className='w-full' value={ value }
onChange={ e => onChage(e) }/>
</>
);
};
export default MaxPeople;<file_sep>import { atom } from 'recoil';
export const employeeFilterParamsState = atom({
key: 'employeeFilterParamsState',
default: {
strSearch: '',
codeSearch: '',
emailSearch: '',
telSearch: '',
branchSearch: [],
sex: 99,
department: [],
position: []
},
});
<file_sep>import React, {useRef, useState} from 'react';
import Button from '@material-ui/core/Button';
import Checkbox from '@material-ui/core/Checkbox';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from '@material-ui/core/FormGroup';
import IconButton from '@material-ui/core/IconButton';
import {withStyles} from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import CloseIcon from '@material-ui/icons/Close';
import PropTypes from 'prop-types';
import {useMutation} from 'react-query';
import {useRecoilValue} from 'recoil';
import {getYearMonthDay} from '../../../../helpers/helper';
import {getListBook} from '../../../../service/bookAnOffices/bookAnOffices';
import {orderBookFilterParams, orderBookFilterParamsContinuous} from '../../../../store/actom/orderBook/orderBook';
const styles = (theme) => ({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
const DialogTitle = withStyles(styles)((props) => {
const {children, classes, onClose, ...other} = props;
return (
<MuiDialogTitle disableTypography className={ classes.root } { ...other }>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton aria-label="close" className={ classes.closeButton } onClick={ onClose }>
<CloseIcon/>
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const BookOrder = ({openDialog, setOpenDialog, value, ...other}) => {
const ref = useRef(null);
const handleEntering = () => {
if (ref.current != null) {
ref.current.focus();
}
};
const filterStateLT = useRecoilValue(orderBookFilterParams);
const filterStateKLT = useRecoilValue(orderBookFilterParamsContinuous);
const editMutationLT = useMutation(value => getListBook().orderBookLT(value));
const editMutationKLT = useMutation(value => getListBook().orderBookKLT(value));
const onChageClick = () => {
if (value === 'lien_tuc') {
const values = {
idCustomer: '1',
idRoom: filterStateLT.idRoom.toString(),
startDate: filterStateLT.startDate,
endDate: filterStateLT.endDate,
listIdServiceSelected: filterStateLT.listService.filter(i => i.checked).map(j => j.id.toString()),
listIdScheduleDetail: filterStateLT.listTime.filter(i => i.checked).map(j => j.id.toString())
};
editMutationLT.mutate(values, {
onSuccess: async (e) => {
console.log(e);
await setOpenDialog(false);
},
onError: async () => {
await setOpenDialog(true);
}
});
} else if (value === 'ngat_quang') {
const values = {
idCustomer: '1',
idRoom: filterStateKLT.idRoom.toString(),
schedules: filterStateKLT.schdules.length > 0 ? filterStateKLT.schdules.map(item => {
return {
startDate: getYearMonthDay(item.startDate),
listService: item.listService.length > 0 ? item.listService.filter(i => i.checked).map(j => j.id.toString()) : [],
listShift: item.listShift.length > 0 ? (item.listShift.filter(k => k.checked).length === item.listShift.length ?
[filterStateKLT.idAll] : item.listShift.filter(h => h.checked).map(t => t.id.toString())) : []
};
}) : []
};
console.log(values);
editMutationKLT.mutate(values, {
onSuccess: async (e) => {
console.log(e);
await setOpenDialog(false);
},
onError: async (e) => {
console.log(e);
await setOpenDialog(true);
}
});
}
};
const handleCancel = () => {
setOpenDialog(!openDialog);
};
const [checked, setChecked] = useState(false);
return (
<>
<Dialog
scroll={ 'paper' }
disableBackdropClick
disableEscapeKeyDown
fullWidth={ true }
maxWidth={ 'sm' }
onEntering={ handleEntering }
aria-labelledby="confirmation-dialog-title"
open={ openDialog }
{ ...other }
height={ '400px' }
>
<DialogTitle id="confirmation-dialog-title" onClose={ handleCancel }>Điều khoản và quy định</DialogTitle>
<DialogContent dividers>
<div>
<FormControl component="fieldset" className={ 'w-full' }>
{/*<FormLabel component="legend">Chọn tất cả</FormLabel>*/}
<FormGroup>
<div className='w-full'>
<h3 className='text-center font-bold'>Điều khoản yêu cầu</h3>
<p className='text-justify mb-4'>
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
</p>
</div>
<div className='w-full'>
<h3 className='text-center font-bold'>Quy định chấp hành</h3>
<p className='text-justify mb-4'>
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
Xây dựng nền móng cho doanh nghiệp của bạn trong một nền kinh tế đang mở rộng và dịch chuyển nhanh
với không gian văn phòng sẵn sàng sử dụng của chúng tôi tại Hà Nội. Tùy chỉnh cách bố trí để phù hợp
với giao diện của thương hiệu và mở rộng hoặc thu nhỏ không gian dễ dàng khi doanh nghiệp của bạn
phát triển. Nhân viên tiếp tân của chúng tôi sẽ chào đón các vị khách của bạn một cách chuyên
nghiệp. Và tận hưởng đồ nội thất tiện dụng chất lượng cao cũng như thư giãn trong khu vực bếp và
tiền sảnh riêng của chúng tôi.
</p>
</div>
</FormGroup>
</FormControl>
</div>
</DialogContent>
<DialogActions>
<FormControlLabel
control={ <Checkbox
checked={ checked }
onChange={ () => setChecked(!checked) }
name="checkedB"
color="primary"
/> }
label="Tôi đồng ý với các điều khoản bên trên!"
/>
<Button color="primary" variant="contained" onClick={ onChageClick } disabled={ !checked }>
Xác nhận
</Button>
<Button color="secondary" variant="contained" onClick={ handleCancel }>
Quay lại
</Button>
</DialogActions>
</Dialog>
</>
);
};
BookOrder.propTypes = {
setOpenDialog: PropTypes.func,
openDialog: PropTypes.bool,
value: PropTypes.string
};
export default BookOrder;<file_sep>import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import {useQuery} from 'react-query';
import { useSetRecoilState } from 'recoil';
import {getListTypeRoom} from '../../../../../service/room/typeRoom/listTypeRoom';
import MultipleSelect from '../../../../base/input/MultipleSelect';
const CardBranch = ({ filterParams, title }) => {
const [ branch, setBranch ] = useState([]);
const branchSearch = useSetRecoilState(filterParams);
const getData = async () => {
return await getListTypeRoom().getListArr();
};
const { data } = useQuery(
[ 'PRODUCT_LIST_KEY_TYPE_ROOM_1' ],
() => getData(),
{
keepPreviousData: true, staleTime: 5000,
placeholderData: []
}
);
useEffect(() => {
branchSearch(search => {
return {
...search,
kindOfRoom: branch
};
});
}, [ branch ]);
return (
<>
<div className="flex items-center w-full">
<span className="w-1/5">{ title }</span>
<MultipleSelect data={ data } personName={ branch } setPersonName={ setBranch } minWidth='90%' oneChip={ true } />
</div>
</>
);
};
CardBranch.propTypes = {
filterParams: PropTypes.object,
// dataArr: PropTypes.array,
title: PropTypes.string
};
export default CardBranch;<file_sep>import React from 'react';
import EconomicNews from '../../component/news/economicNews';
const ComponentCenter = () => {
return (
<>
<EconomicNews />
</>
);
};
export default ComponentCenter;<file_sep>import React, {useState} from 'react';
import Button from '@material-ui/core/Button';
import PropTypes from 'prop-types';
import {useRecoilValue} from 'recoil';
import {formatCurrency, totalNumberDate} from '../../../../helpers/helper';
import {orderBookFilterParams, orderBookFilterParamsContinuous} from '../../../../store/actom/orderBook/orderBook';
import BookOrder from '../bookOrder';
import PaymentContinuous from './paymentContinuous';
import PaymentIntermittent from './paymentIntermittent';
const Payment = ({value}) => {
const filterData = useRecoilValue(orderBookFilterParamsContinuous);
const valueType = filterData.valueType ? filterData.valueType[0] : {};
const schdules = filterData.schdules;
const totalAll = () => {
let totalItem = 0;
for (let i = 0; i < schdules.length; i++) {
totalItem += (Number(schdules[i].listShift.filter(i => i.checked).length * (valueType ? valueType.priceTypeRoom : 0))) +
(schdules[i].listShift.filter(i => i.checked).length > 0 ? (schdules[i].listService.reduce((total, i) => {
return total += i.priceService;
}, 0)) : 0);
}
return totalItem;
};
// tổng giá đặt lịch liên tục
const filter = useRecoilValue(orderBookFilterParams);
console.log(filter);
const listService = filter.listService;
const total = () => {
if (filter.startDate && filter.endDate && filter.listTime.length > 0) {
return (valueType ? valueType.priceTypeRoom : 0) * totalNumberDate(filter.startDate, filter.endDate) * filter.listTime.length +
totalNumberDate(filter.startDate, filter.endDate) * (listService.filter(i => i.checked).length > 0 ? (listService.reduce((total, i) => {
return total += i.priceService;
}, 0)) : 0);
}
return 0;
};
const [openDialog, setOpentDialog] = useState(false);
return (
<>
<h2 className='text-center font-bold my-2'>ĐƠN GIÁ</h2>
<div className='mx-2 test-xs flex justify-between font-medium mt-6'>
<h3 className=''>Tổng cộng:</h3>
<p className='text-xl'>{value === 'ngat_quang' ? formatCurrency(totalAll()) : formatCurrency(total())}</p>
</div>
<div className='flex justify-center mt-5 mx-6 border-b-1 pb-5'>
<Button color="primary" variant="contained" onClick={ () => setOpentDialog(!openDialog) }>
Tiến hành đặt lịch
</Button>
{
openDialog && <BookOrder openDialog={ openDialog } setOpenDialog={ setOpentDialog } value={ value }/>
}
</div>
{value === 'lien_tuc' && <PaymentContinuous/>}
{value === 'ngat_quang' && <PaymentIntermittent/>}
</>
);
};
Payment.propTypes = {
onChange: PropTypes.func,
value: PropTypes.string
};
export default Payment;<file_sep>import React from 'react';
import ContractList from '../../components/contract/contractList';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Danh sách hợp đồng' ];
const Contract = () => {
return (
<>
<LayoutLink title="Danh sách hợp đồng" listLink={ listLink }>
<ContractList />
</LayoutLink>
</>
);
};
export default Contract;
<file_sep>import React from 'react';
import EmployeeList from '../../components/employees/EmployeeList';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Danh sách nhân viên' ];
const Employee = () => {
return (
<>
<LayoutLink title="Danh sách hợp đồng" listLink={ listLink }>
<EmployeeList />
</LayoutLink>
</>
);
};
export default Employee;
<file_sep>import React, { Suspense } from 'react';
import {
Switch,
Route,
// Redirect,
// useLocation
} from 'react-router-dom';
import LoadingSpinner from '../component/common/LoadingSpinner';
import Footer from '../component/footers';
import Header from '../component/headers';
import {
VirtualOffice, Home,
AllInclusiveOffice,
WorkingSeat, ExchangeOffice,
MeetingRoom, OnlineMeetingRoom,
CreativeContent, ZoomConference,
DigitalSignatures, ElectronicBill,
ElectronicSocialInsurance, SetUpABusiness,
Telecommunication, Translate,
EconomicNews, LegalNews,
Document, Recruitment,
DuyTan, KhuatDuyTien, LeDucTho,
LeVanLuong, NguyenThaiHoc, TamChinh,
ToHieu, TranPhu, Contact, Quotation,
BookAnOffice
} from './Lazy';
const Body = () => {
return (
<>
<Suspense fallback={ <LoadingSpinner /> }>
<Switch>
{/* home */ }
<Route exact path="/" component={ Home } />
{/* service */ }
<Route exact path="/van-phong-ao" component={ VirtualOffice } />
<Route exact path="/van-phong-tron-goi" component={ AllInclusiveOffice } />
<Route exact path="/cho-ngoi-lam-viec" component={ WorkingSeat } />
<Route exact path="/van-phong-luu-dong" component={ ExchangeOffice } />
<Route exact path="/phong-hop" component={ MeetingRoom } />
<Route exact path="/phong-hop-truc-tuyen" component={ OnlineMeetingRoom } />
{/* serviceOrther */ }
<Route exact path="/zoom-conference" component={ ZoomConference } />
<Route exact path="/chu-ky-so" component={ DigitalSignatures } />
<Route exact path="/hoa-don-dien-tu" component={ ElectronicBill } />
<Route exact path="/bhxh-dien-tu" component={ ElectronicSocialInsurance } />
<Route exact path="/cac-dich-vu-vien-thong" component={ Telecommunication } />
<Route exact path="/thanh-lap-doanh-nghiep" component={ SetUpABusiness } />
<Route exact path="/bien-phien-dich" component={ Translate } />
<Route exact path="/creative-content" component={ CreativeContent } />
{/* place: Địa điểm */ }
<Route exact path="/le-van-luong-thanh-xuan" component={ LeVanLuong } />
<Route exact path="/khuat-duy-tien-thanh-xuan" component={ KhuatDuyTien } />
<Route exact path="/tam-chinh-hoang-mai" component={ TamChinh } />
<Route exact path="/tran-phu-ha-dong" component={ TranPhu } />
<Route exact path="/nguyen-thai-hoc-ba-dinh" component={ NguyenThaiHoc } />
<Route exact path="/duy-tan-cau-giay" component={ DuyTan } />
<Route exact path="/to-hieu-ha-dong" component={ ToHieu } />
<Route exact path="/le-duc-tho-nam-tu-liem" component={ LeDucTho } />
{/* news */ }
<Route exact path="/ban-tin-kinh-te" component={ EconomicNews } />
<Route exact path="/ban-tin-phap-luat" component={ LegalNews } />
<Route exact path="/tai-lieu" component={ Document } />
<Route exact path="/tuyen-dung" component={ Recruitment } />
{/* introduce: Giới thiệu */ }
<Route exact path="/gioi-thieu" component={ OnlineMeetingRoom } />
{/* contact: Liên hệ */ }
<Route exact path="/lien-he" component={ Contact } />
{/* quotation: Bảng báo giá */ }
<Route exact path="/bang-bao-gia" component={ Quotation } />
{/* book_an_office: Đăng ký phòng */ }
<Route exact path="/dang-ky-phong" component={ BookAnOffice } />
</Switch>
</Suspense>
</>
);
};
const Router = () => {
return (
<>
<Header />
<Body />
<Footer />
</>
);
};
export default Router;<file_sep>import React from 'react';
import { ResponsiveLine } from '@nivo/line';
import PropTypes from 'prop-types';
import DateYear from '../../../base/dateTime/DateYear';
const CompareRevenueChart = ({ data }) => {
return (
<>
<div className="w-full bg-white shadow-lg rounded-lg">
<div className="flex justify-between">
<p className="text-xl font-medium antialiased px-3 pt-3">Doanh thu so với cùng kỳ năm trước</p>
<div className="mx-3"><DateYear /></div>
</div>
<div className="h-237 w-full">
<ResponsiveLine
data={ data }
margin={ { top: 15, right: 110, bottom: 50, left: 60 } }
xScale={ { type: 'point' } }
yScale={ { type: 'linear', min: 'auto', max: 'auto', stacked: true, reverse: false } }
yFormat=" >-.2f"
axisTop={ null }
axisRight={ null }
axisBottom={ {
orient: 'bottom',
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'Tháng',
legendOffset: 36,
legendPosition: 'middle'
} }
axisLeft={ {
orient: 'left',
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'Triệu đồng',
legendOffset: -40,
legendPosition: 'middle'
} }
pointSize={ 10 }
pointColor={ { theme: 'background' } }
pointBorderWidth={ 2 }
pointBorderColor={ { from: 'serieColor' } }
pointLabelYOffset={ -12 }
useMesh={ true }
legends={ [
{
anchor: 'bottom-right',
direction: 'column',
justify: false,
translateX: 100,
translateY: 0,
itemsSpacing: 0,
itemDirection: 'left-to-right',
itemWidth: 80,
itemHeight: 20,
itemOpacity: 0.75,
symbolSize: 12,
symbolShape: 'circle',
symbolBorderColor: 'rgba(0, 0, 0, .5)',
effects: [
{
on: 'hover',
style: {
itemBackground: 'rgba(0, 0, 0, .03)',
itemOpacity: 1
}
}
]
}
] }
/>
</div>
<div className="pb-3 px-4 flex justify-start">
<p className="hover:text-blue-700 cursor-pointer">Xem chi tiết</p>
</div>
</div>
</>
);
};
CompareRevenueChart.propTypes = {
title: PropTypes.string,
data: PropTypes.array
};
export default CompareRevenueChart;<file_sep>import React from 'react';
import Button from '@material-ui/core/Button';
import { useForm, Controller } from 'react-hook-form';
import TextFieldInput from '../../common/TextFieldInput';
import TextPassword from '../../common/TextPassword';
const LoginBook = () => {
const defaultValues = {
user_customer: '',
pass_customer: ''
};
const methods = useForm({ defaultValues });
const { formState: { errors }, control } = methods;
const onSubmitForm = (value) => {
console.log(value);
};
return (
<>
<div className="flex justify-center gap-16 mt-10">
<div className="w-1/4 mt-20">
<form >
<h4 className="text-center font-bold text-xl">Đăng nhập</h4>
<div>
<Controller
name={ 'user_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Tài khoản" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.user_customer?.type === 'required' ? 'Tài khoản đăng nhập không được bỏ trống!' : null } /> } />
<Controller
name={ 'pass_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextPassword className="w-full" multiline rows={ 3 } id="standard-multiline-static"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.pass_customer?.type === 'required' ? 'Mật khẩu không được bỏ trống!' : null } /> } />
<div className="flex justify-between">
<p className="hover:text-blue-700 cursor-pointer">Quên mật khẩu?</p>
<p className="hover:text-blue-700 cursor-pointer">Đăng ký</p>
</div>
</div>
<div className="mt-4">
<Button color="primary" variant="contained" onClick={ () => methods.handleSubmit(onSubmitForm)() }>
Đăng nhập
</Button>
</div>
</form>
</div>
<div className="w-1/3">
<img src="https://hanoioffice.vn/wp-content/uploads/2020/09/cho-ngoi-lam-viec-n1.jpg" alt="Hà Nội Office" align="center" />
</div>
</div>
</>
);
};
export default LoginBook;<file_sep>import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import PropTypes from 'prop-types';
import ReactTooltip from 'react-tooltip';
const IconHelpTooltip = ({ label, tooltip }) => {
return (
<span className="ml-2 cursor-pointer">
<FontAwesomeIcon
data-tip={ tooltip }
data-for={ label }
icon={ 'info-circle' }
className="hover:text-gray-600"
size={ 'lg' }
color={ '#999' }
/>
<ReactTooltip
id={ label }
className="customeTheme"
effect={ 'solid' }
delayShow={ 200 }
place={ 'right' }
border
borderColor={ '#4bac4d' }
arrowColor={ '#fff' }
/>
</span>
);
};
IconHelpTooltip.propTypes = {
label: PropTypes.string.isRequired,
tooltip: PropTypes.string,
};
export default IconHelpTooltip;<file_sep>import React, { useState } from 'react';
import {
listCustomerFilterParamsState
} from '../../../../../store/atoms/customer/customerList/listCustomer';
import ButtonBase from '../../../../base/button/ButtonBase';
import DateSelection from '../../../../base/dateTime/DateSelection';
import CardBranch from '../../../../common/filter/CardBranch';
import CardSex from '../../../../common/filter/CardSex';
import DialogAdd from '../Dialog/DialogAdd';
import CardIngredient from '../Filters/CardIngredient';
import CardStatus from '../Filters/CardStatus';
import SearchBar from '../Filters/SearchBar';
const Filters = () => {
const [ openAdd, setOpenAdd ] = useState(false);
return (
<>
<div className="rounded w-full bg-gray-100 my-2">
<div className="m-2">
<div className='flex grid grid-cols-3 gap-4'>
<SearchBar />
<CardBranch filterParams={ listCustomerFilterParamsState } />
<CardIngredient filterParams={ listCustomerFilterParamsState } />
</div>
<div className='flex gap-4'>
<CardSex filterParams={ listCustomerFilterParamsState } />
<DateSelection title="Ngày tạo" />
<CardStatus filterParams={ listCustomerFilterParamsState } />
</div>
<div className="flex justify-end ">
<ButtonBase title={ 'Thêm khách hàng' } color={ 'primary' } className='m-3' onClick={ () => setOpenAdd(!openAdd) } />
{
<DialogAdd setOpenDialog={ setOpenAdd } openDialog={ openAdd } />
}
</div>
</div>
</div>
</>
);
};
export default Filters;<file_sep>import React from 'react';
import BranchHistory from '../../components/branch/branchHistory';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Lịch sử địa điểm' ];
const Branch = () => {
return (
<>
<LayoutLink title='Lịch sử' listLink={ listLink }>
<BranchHistory />
</LayoutLink>
</>
);
};
export default Branch;<file_sep>import React, { useState } from 'react';
import FormControl from '@material-ui/core/FormControl';
// import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import { makeStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
const useStyles = makeStyles((theme) => ({
button: {
display: 'block',
marginTop: theme.spacing(2),
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
}));
const day = new Date();
const thisYear = Number(day.getFullYear());
const thisMonth = Number(day.getMonth()) + 1;
const listYears = () => {
const listArr = [];
for (let i = thisYear - 6; i <= thisYear; i++) {
listArr.push(i);
}
return listArr;
};
const listMonth = () => {
const listArrMonth = [];
for (let i = 1; i < 13; i++) {
listArrMonth.push(i);
}
return listArrMonth;
};
const DateMonthYear = () => {
const classes = useStyles();
const [ year, setYear ] = useState(thisYear);
const [ open, setOpen ] = useState(false);
const [ month, setMonth ] = useState(thisMonth);
const [ openMonth, setOpenMonth ] = useState(false);
const handleChange = (event) => {
setYear(event.target.value);
};
const handleChangeMonth = (event) => {
setMonth(event.target.value);
};
const handleOpen = () => {
setOpen(!open);
};
const handleOpenMonth = () => {
setOpenMonth(!openMonth);
};
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 4;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
width: 150,
},
},
};
return (
<>
<div className="flex">
<div className="flex items-center">
<p>Tháng: </p>
<FormControl className={ classes.formControl }>
<Select
labelId="demo-controlled-open-select-label"
id="demo-controlled-open-select"
open={ openMonth }
onClose={ handleOpenMonth }
onOpen={ handleOpenMonth }
value={ month }
onChange={ handleChangeMonth }
MenuProps={ MenuProps }
>
{
listMonth().map((item, index) => {
return (
<MenuItem key={ index } value={ item }>{ item }</MenuItem>
);
})
}
</Select>
</FormControl>
</div>
<div className="flex items-center">
<p>Năm: </p>
<FormControl className={ classes.formControl }>
<Select
labelId="demo-controlled-open-select-label1"
id="demo-controlled-open-select1"
open={ open }
onClose={ handleOpen }
onOpen={ handleOpen }
value={ year }
onChange={ handleChange }
MenuProps={ MenuProps }
>
{
listYears().map((item, index) => {
return (
<MenuItem key={ index } value={ item }>{ item }</MenuItem>
);
})
}
</Select>
</FormControl>
</div>
</div>
</>
);
};
DateMonthYear.propTypes = {
filterParams: PropTypes.object,
title: PropTypes.string
};
export default DateMonthYear;<file_sep>import { atom } from 'recoil';
const today = new Date();
export const serviceOtherListFilterParamsState = atom({
key: 'serviceOtherListFilterParamsState',
default: {
strSearch: '',
codeSearch: '',
debitSearch: 99,
from_date: today,
to_date: today,
}
});
export const serviceOtherListPageLimitState = atom({
key: 'serviceOtherListPageLimitState',
default: 15
});
export const serviceOtherListPageState = atom({
key: 'serviceOtherListPageState',
default: 1
});
export const serviceOtherListColumnTableState = atom({
key: 'serviceOtherListColumnTableState',
default: [
{ field: 'detail', headerName: 'Chi tiết', width: 80, sortable: false, description: 'Chi tiết', cellClassName: 'cursor-pointer' },
{ field: 'id_contract', headerName: 'Mã dịch vụ', width: 200, sortable: false, description: 'Mã dịch vụ' },
{ field: 'name_contract', headerName: 'Tên dịch vụ', width: 370, sortable: false, description: 'Tên dịch vụ' },
{ field: 'name_branch', headerName: 'Giá theo giờ', width: 200, sortable: false, description: 'Giá theo giờ' },
{ field: 'date_start', headerName: 'Ngày tạo', width: 200, sortable: false, description: 'Ngày tạo dịch vụ' },
{ field: 'note', headerName: 'Ghi chú', width: 400, sortable: false, description: 'Ghi chú' },
]
});<file_sep>import React from 'react';
import SearchBar from '../Filters/SearchBar';
const Filters = () => {
return (
<>
<div className="rounded w-full bg-gray-100 my-2">
<div className="m-2">
<SearchBar />
</div>
</div>
</>
);
};
export default Filters;<file_sep>import React from 'react';
import ElectronicSocialInsurance from '../../component/serviceOrther/ElectronicSocialInsurance';
const ComponentCenter = () => {
return (
<>
<ElectronicSocialInsurance />
</>
);
};
export default ComponentCenter;<file_sep>import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
// import NewLogo from '../../assets/images/new_logo.jpg';
const LayoutError = ({ title, subTitle, children }) => {
const [ header, setHeader ] = useState(0);
useEffect(() => {
setHeader(window.innerHeight - document.getElementById('header').offsetHeight);
}, []);
useEffect(() => {
document.title = 'Lỗi!';
}, []);
return (
<div className=" w-full flex items-center justify-center bg-white" style={ { height: `${header}px` } }>
<div className="px-10 py-20 flex flex-col items-center">
<img
src={ null }
alt=""
style={ { height: 60, width: 187 } }
/>
{ children }
<h2 className="uppercase text-2xl my-4 font-thin">{ title }</h2>
<p className="text-xl font-thin">
{ subTitle }
<NavLink to="/">
<span className="text-cyan hover:text-blue-400"> Trang chủ</span>
</NavLink>
</p>
</div>
</div>
);
};
LayoutError.propTypes = {
title: PropTypes.string,
subTitle: PropTypes.string,
};
export default LayoutError;<file_sep>import React from 'react';
const LeDucTho = () => {
return (
<>
<h1>{ 'Viết code cho màn hình "địa điểm Lê Đức Thọ" tại đây' }</h1>
</>
);
};
export default LeDucTho;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {Controller, useFormContext} from 'react-hook-form';
// import DateSingle from '../../../../base/dateTime/DateSingle';
import SelectedInput from '../../../../common/SelectedInput';
import TextFieldInput from '../../../../common/TextFieldInput';
const typeRoom = [
{id: '1', text: 'Phòng họp'},
{id: '2', text: 'Chỗ ngồi làm việc'},
{id: '3', text: 'Văn phòng ảo'}
];
const branchList = [
{id: '1', text: 'Chi nhánh Thanh Xuân'},
{id: '2', text: 'Chi nhánh Hà Đông'},
{id: '3', text: 'Chi nhánh Đống Đa'}
];
const DetailInfo = () => {
const methods = useFormContext();
const {formState: {errors}, control} = methods;
return (
<>
<div>
<div className="grid grid-cols-2 gap-4">
<Controller
name={ 'code_room' }
control={ control }
rules={ {required: true} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Mã phòng" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.code_room?.type === 'required' ? 'Mã không được bỏ trống!' : null }/> }/>
<Controller
name={ 'name_room' }
control={ control }
rules={ {required: true} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Tên phòng" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.name_room?.type === 'required' ? 'Tên không được bỏ trống!' : null }/> }/>
<Controller
name={ 'position' }
control={ control }
rules={ {} }
render={ ({field: {onChange, value}}) =>
<SelectedInput
dataArr={ typeRoom }
title='Loại phòng'
value={ value }
onChange={ e => {
onChange(e.target.value);
} }
/> }
/>
<Controller
name={ 'branch' }
control={ control }
rules={ {} }
render={ ({field: {onChange, value}}) =>
<SelectedInput
dataArr={ branchList }
title='Chi nhánh'
value={ value }
onChange={ e => {
onChange(e.target.value);
} }
/> }
/>
{/*<Controller*/}
{/* name={ 'location_room' }*/}
{/* control={ control }*/}
{/* rules={ { required: true } }*/}
{/* render={ ({ field: { onChange, value } }) =>*/}
{/* <TextFieldInput label="Vị trí phòng" className="w-full"*/}
{/* onChange={ e => {*/}
{/* onChange(e.target.value);*/}
{/* } }*/}
{/* value={ value }*/}
{/* error={ errors?.location_room?.type === 'required' ? 'Vị trí phòng không được bỏ trống!' : null } /> } />*/}
<Controller
name={ 'number_customer' }
control={ control }
rules={ {required: true} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Phòng chứa tối đa" className="w-full" type={ 'number' }
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.number_customer?.type === 'required' ? 'Phòng chứa tối đa không được bỏ trống!' : null }/> }/>
{/*<div className="pt-4 pb-2">*/}
{/* <DateSingle title="Ngày tạo" classNameTitle="w-1/4"*/}
{/* onChange={ setForm }*/}
{/* value={ form } keySearch="date_created"*/}
{/* />*/}
{/*</div>*/}
</div>
<div>
<Controller
name={ 'note' }
control={ control }
rules={ {} }
render={ ({field: {onChange, value}}) =>
<TextFieldInput label="Ghi chú" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null }/> }/>
</div>
</div>
</>
);
};
DetailInfo.propTypes = {
setForm: PropTypes.func,
form: PropTypes.object
};
export default DetailInfo;<file_sep>import React from 'react';
const TamChinh = () => {
return (
<>
<h1>{ 'Viết code cho màn hình "địa điể<NAME>" tại đây' }</h1>
</>
);
};
export default TamChinh;<file_sep>import React from 'react';
import RadioGroup from '../../../base/radio/RadioGroup';
const Filters = () => {
return (
<>
<div>
<div className="w-full mx-2 mt-4 mb-8 text-xl font-bold border-b-2 rounded">
<p>Danh sách đen</p>
</div>
<RadioGroup />
</div>
</>
);
};
export default Filters;<file_sep>import {atom} from 'recoil';
const today = new Date();
export const tableSearchFilterParamsState = atom({
key: 'tableSearchFilterParamsState',
default: {
strSearch: '',
codeSearch: '',
debitSearch: 99,
from_date: today,
to_date: today,
}
});
export const tableSearchColumnTableState = atom({
key: 'tableSearchColumnTableState',
default: [
{
field: 'detail',
headerName: 'Chi tiết',
width: 100,
sortable: false,
description: 'Chi tiết',
cellClassName: 'cursor-pointer'
},
{
field: 'nameCustomer',
headerName: 'Tên khách hàng',
width: 100,
sortable: false,
description: 'Tên khách hàng'
},
{field: 'numberPhone', headerName: 'Số điện thoại', width: 100, sortable: false, description: 'Số điện thoại'},
{field: 'createDate', headerName: 'Ngày dặt lịch', width: 100, sortable: false, description: 'Ngày đặt lịch'},
{
field: 'statusOrder',
headerName: 'Trạng thái đặt lịch̉',
width: 100,
sortable: false,
description: 'Trạng thái đặt lịch'
},
{
field: 'statusPay',
headerName: 'Trang thái thanh toán',
width: 100,
sortable: false,
description: 'Trạng thái thanh toán'
}
]
});<file_sep>import React from 'react';
const LeVanLuong = () => {
return (
<>
<h1>{ 'Viết code cho màn hình "địa điểm Lê Văn Lương" tại đây' }</h1>
</>
);
};
export default LeVanLuong;<file_sep>import { atom } from 'recoil';
export const showLeftSideState = atom({
key: 'showLeftSideState',
default: true
});
export const setWidthDefault = atom({
key: 'setWidthDefault',
default: 1280
});
export const onCloseOpenDrawer = atom({
key: 'onCloseOpenDrawer',
default: false
});
<file_sep>import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from '@material-ui/core/FormGroup';
const useNumber = [
{id: 1, name: 'Thứ 2:', ca_1: false, ca_2: false, ca_3: false, ca_4: false, name_1: '8h-10h', name_2: '10h-12h', name_3: '13h-15h',name_4: '15h-17h'},
{id: 2, name: 'Thứ 3:', ca_1: false, ca_2: false, ca_3: false, ca_4: false, name_1: '8h-10h', name_2: '10h-12h', name_3: '13h-15h',name_4: '15h-17h'},
{id: 3, name: 'Thứ 4:', ca_1: false, ca_2: false, ca_3: false, ca_4: false, name_1: '8h-10h', name_2: '10h-12h', name_3: '13h-15h',name_4: '15h-17h'},
{id: 4, name: 'Thứ 5:', ca_1: false, ca_2: false, ca_3: false, ca_4: false, name_1: '8h-10h', name_2: '10h-12h', name_3: '13h-15h',name_4: '15h-17h'},
{id: 5, name: 'Thứ 6:', ca_1: false, ca_2: false, ca_3: false, ca_4: false, name_1: '8h-10h', name_2: '10h-12h', name_3: '13h-15h',name_4: '15h-17h'},
{id: 6, name: '<NAME>:', ca_1: false, ca_2: false, ca_3: false, ca_4: false, name_1: '8h-10h', name_2: '10h-12h', name_3: '13h-15h',name_4: '15h-17h'},
{id: 7, name: 'Chủ nhật: ', ca_1: false, ca_2: false, ca_3: false, ca_4: false, name_1: '8h-10h', name_2: '10h-12h', name_3: '13h-15h',name_4: '15h-17h'},
];
const UseDate=()=> {
const [time, setTime] = React.useState(useNumber);
const handleChange = (event, ca, id) => {
console.log(ca + ' ' + id);
setTime( time.map((item)=> {
console.log(item.id);
return { ...item, ca: item.id === id ? !item.ca : item.ca};
}) );
};
return (
<>
<div>
{
time.map((item, index)=> {
return (
<div className="flex justify-between items-center" key={ index }>
<p className="ml-24">{ item.name }</p>
<div className="">
<FormGroup row>
<FormControlLabel
control={ <Checkbox
checked={ item.ca_1 }
onChange={ e => handleChange(e, 'ca_1', item.id) }
name={ item.name_1 }
color="primary"
/> }
label={ item.name_1 }
/>
<FormControlLabel
control={ <Checkbox
checked={ item.ca_2 }
onChange={ e => handleChange(e, 'ca_2', item.id) }
name={ item.name_2 }
color="primary"
/> }
label={ item.name_2 }
className='pl-6'
/>
<FormControlLabel
control={ <Checkbox
checked={ item.ca_3 }
onChange={ e => handleChange(e, 'ca_3', item.id) }
name={ item.name_3 }
color="primary"
/> }
label={ item.name_3 }
className='pl-6'
/>
<FormControlLabel
control={ <Checkbox
checked={ item.ca_4 }
onChange={ e => handleChange(e, 'ca_4', item.id) }
name={ item.name_4 }
color="primary"
/> }
label={ item.name_4 }
className='pl-6'
/>
</FormGroup>
</div>
</div>
);
})
}
</div>
</>
);
};
export default UseDate;<file_sep>// import React from 'react';
// import ListEmloyee from '../../components/employees';
// import Breadcrumbs from '../../components/employees/Breadcrumbs';
// import LayoutLink from '../../layoutLink';
// const Employee = () => {
// return (
// <>
// <LayoutLink title="Nhân viên" titleLink={ Breadcrumbs }>
// <ListEmloyee />
// </LayoutLink>
// </>
// );
// };
// export default Employee;
<file_sep>import React from 'react';
import Divider from '@material-ui/core/Divider';
import List from '@material-ui/core/List';
import ListSubheader from '@material-ui/core/ListSubheader';
import {makeStyles} from '@material-ui/core/styles';
import {router, router2, router3, router4} from '../../router';
import MenuBarItem from './MenuBarItem';
// import Demo from './demo1';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
nested: {
paddingLeft: theme.spacing(4),
},
}));
const MenuBar = () => {
const classes = useStyles();
const role = 1;
return (
<List
component="nav"
aria-labelledby="nested-list-subheader"
subheader={ <ListSubheader component="div" id="nested-list-subheader">
Phong cách làm việc mới!
</ListSubheader> }
className={ classes.root }
>
<Divider/>
{role === 1 &&
router.map((item, index) => (
<MenuBarItem item={ item } key={ index }/>
))
}
{role === 2 &&
router2.map((item, index) => (
<MenuBarItem item={ item } key={ index }/>
))
}
{role === 3 &&
router3.map((item, index) => (
<MenuBarItem item={ item } key={ index }/>
))
}
{role === null &&
router4.map((item, index) => (
<MenuBarItem item={ item } key={ index }/>
))
}
</List>
);
};
export default MenuBar;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import IconHelpTooltip from '../common/IconHelpTooltip';
const InputLabel = (
{
label, tooltip,
children, className = 'mb-3',
labelClassName = 'w-48',
required = false,
flex = true
}
) => {
return (
<div className={ `${flex ? 'flex' : ''} items-center justify-between ${className}` }>
<label className={ `${labelClassName} font-bold pt-2` }>
{ label } { required ? <span className='text-red-500'>*</span> : '' }
{ tooltip && <IconHelpTooltip label={ label } tooltip={ tooltip } /> }
</label>
{
children &&
<div className="w-full">
{ children }
</div>
}
</div>
);
};
InputLabel.propTypes = {
label: PropTypes.string.isRequired,
tooltip: PropTypes.string,
className: PropTypes.string,
labelClassName: PropTypes.string,
required: PropTypes.bool,
flex: PropTypes.bool
};
export default InputLabel;
<file_sep>import {atom} from 'recoil';
// const today = new Date();
export const orderBookFilterParamsState = atom({
key: 'orderBookFilterParamsState',
default: {
branch: 0,
typeRoom: 0,
}
});
export const orderBookFilterParams = atom({
key: 'orderBookFilterParams',
default: {
listTime: [],
listService: [],
idRoom: '',
idCustomer: '',
valueType: []
}
});
export const orderBookFilterParamsContinuous = atom({
key: 'orderBookFilterParamsContinuous',
default: {
idRoom: '',
idCustomer: '',
schdules: []
}
});
export const orderBookPageLimitState = atom({
key: 'orderBookPageLimitState',
default: 15
});
export const orderBookPageState = atom({
key: 'orderBookPageState',
default: 1
});
export const totalPayment = atom({
key: 'totalPayment',
default: {
total: '0 VND'
}
});
<file_sep>import {axiosInstance} from '../../config/axios';
// import {getYearMonthDay} from '../../../helpers/helper';
export const getListBook = () => {
const getListBranch = async () => {
const {data} = await axiosInstance.get('/branch/find_all');
return data;
};
const getListTypeRoom = async () => {
const {data} = await axiosInstance.get('/typeroom/find_all');
return data;
};
const getListNumberPeoPle = async ({branch, typeRoom}) => {
const {data} = await axiosInstance.get('/room/find_all');
return dataProcesing(setDataNew(data), branch, typeRoom);
};
const getListTime = async () => {
const {data} = await axiosInstance.get('/shift/find_all');
return setDataTime(data);
};
const getListService = async () => {
const {data} = await axiosInstance.get('/service/find_all');
return setServiceList(data);
};
const getDetail = async () => {
const {data} = await axiosInstance.get('/employees-employees-employees');
return data;
};
const orderBookLT = async (value) => {
const {data} = await axiosInstance.post('/book/bookroomlt', {...value});
return data;
};
const orderBookKLT = async (value) => {
const {data} = await axiosInstance.post('/book/bookroomklt', {...value});
return data;
};
return {
getListBranch,
getDetail,
getListTypeRoom,
getListNumberPeoPle,
getListTime,
getListService,
orderBookLT,
orderBookKLT
};
};
const dataProcesing = (data, branch, typeRoom) => {
if (data.length > 0) {
const dataNew = data.filter(i => (branch !== '' ? i.idBranch === branch : true)
&& (typeRoom !== '' ? i.idTypeRoom === typeRoom : true));
// const dataUnilque = [];
// dataUnilque.forEach(i => {
// const index = dataNew.findIndex(j => i.soChoNgoi === j.soChoNgoi);
// if (index === -1) {
// dataUnilque.push(dataNew[index]);
// }
// });
const dataUnilque = [];
const map = new Map();
for (const item of dataNew) {
if (!map.has(item.soChoNgoi)) {
map.set(item.soChoNgoi, true); // set any value to Map
dataUnilque.push({
id: item.id,
name: item.name,
soChoNgoi: item.soChoNgoi
});
}
}
return dataUnilque.length === 0 ? [{id: '', name: 'Chưa có dữ liệu'}] : dataUnilque;
} else {
return [{id: '', name: 'Chưa có dữ liệu'}];
}
};
const setDataNew = (data) => {
return data.map(i => {
return {
id: i.id,
name: i.soChoNgoi.toString(),
idBranch: i.branch1.id,
idTypeRoom: i.typeRoom.id,
soChoNgoi: i.soChoNgoi
};
});
};
const setDataTime = (data) => {
return data.map(i => ({
...i,
checked: false,
value: i.startTime + '-' + i.endTime
}));
};
const setServiceList = (data) => {
return data.map(i => ({
...i,
checked: false,
value: i.name,
}));
};
// const array = [
// { id: 3, name: 'Central Microscopy', fiscalYear: 2018 },
// { id: 5, name: 'Crystallography Facility', fiscalYear: 2018 },
// { id: 3, name: 'Central Microscopy', fiscalYear: 2017 },
// { id: 5, name: 'Crystallography Facility', fiscalYear: 2017 }
// ];
// const result = [];
// const map = new Map();
// for (const item of array) {
// if(!map.has(item.id)){
// map.set(item.id, true); // set any value to Map
// result.push({
// id: item.id,
// name: item.name
// });
// }
// }
// console.log(result)<file_sep>import React from 'react';
import PropTypes from 'prop-types';
const Popover = React.forwardRef((
{
isVisible,
background = 'bg-white',
right,
children,
className = 'z-50',
maxW = true,
...props
}, ref) => {
return (
<div ref={ ref } { ...props }
className={ `absolute ${isVisible ? 'block m-0' : 'hidden'} ${maxW ? 'max-w-lg' : ''} w-56 ${right ? 'right-0' : ''} ${className}` }>
<div className={ `relative py-2 rounded-md shadow-2xl ${background}` }>
<div className="relative w">{ children }</div>
</div>
</div>
);
});
Popover.propTypes = {
isVisible: PropTypes.bool,
items: PropTypes.array,
background: PropTypes.string,
className: PropTypes.string,
right: PropTypes.bool,
maxW: PropTypes.bool
};
export default Popover;
<file_sep>import React from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormHelperText from '@material-ui/core/FormHelperText';
import IconButton from '@material-ui/core/IconButton';
import Input from '@material-ui/core/Input';
import InputAdornment from '@material-ui/core/InputAdornment';
import InputLabel from '@material-ui/core/InputLabel';
import { makeStyles } from '@material-ui/core/styles';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import clsx from 'clsx';
import PropTypes from 'prop-types';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexWrap: 'wrap',
},
margin: {
margin: theme.spacing(1),
},
withoutLabel: {
marginTop: theme.spacing(3),
},
textField: {
width: '100%',
// height: '10px'
},
}));
const TextPassword = ({ onChange, value, error }) => {
const classes = useStyles();
const [ values, setValues ] = React.useState({
// amount: '',
// password: '',
// weight: '',
// weightRange: '',
showPassword: false,
});
// const handleChange = (prop) => (event) => {
// setValues({ ...values, [ prop ]: event.target.value });
// };
const handleClickShowPassword = () => {
setValues({ ...values, showPassword: !values.showPassword });
};
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
return (
<>
<div className="-mt-2">
<FormControl className={ clsx(classes.margin, classes.textField) }>
<InputLabel htmlFor="standard-adornment-password" ><span className={ error === null ? '' : 'text-red-500' }>Mật khẩu</span></InputLabel>
<Input
id="standard-adornment-password"
type={ values.showPassword ? 'text' : 'password' }
value={ value }
onChange={ onChange }
className="mt-0"
error={ error !== null }
endAdornment={ <InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={ handleClickShowPassword }
onMouseDown={ handleMouseDownPassword }
>
{ values.showPassword ? <Visibility /> : <VisibilityOff /> }
</IconButton>
</InputAdornment> }
/>
<FormHelperText id="standard-weight-helper-text"><span className={ error === null ? '' : 'text-red-500' }>{ error }</span></FormHelperText>
</FormControl>
</div>
</>
);
};
TextPassword.propTypes = {
className: PropTypes.string,
error: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func
};
export default TextPassword;<file_sep>import React, {useCallback, useEffect, useState} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import {useQuery} from 'react-query';
import {
useRecoilValue,
// useRecoilState
} from 'recoil';
import {LIST_ORDER_PLACEHOLDER_DATA} from '../../../../fixedData/dataEmployee';
import {getListBranchs} from '../../../../service/branch/listBranch/branchList';
import {
listBranchColumnTableState,
listBranchFilterParamsState,
listBranchPageState,
listBranchPageLimitState
} from '../../../../store/atoms/branch/branchList';
import TableV7 from '../../../common/table/TableV7';
import DetailInfo from '../listBranch/Dialog/DetailInfo';
import DialogDetail from '../listBranch/Dialog/DialogDetail';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
paper: {
width: '80%',
maxHeight: 1835,
},
}));
const BranchList = () => {
const classes = useStyles();
const columnTable = useRecoilValue(listBranchColumnTableState);
const filterParams = useRecoilValue(listBranchFilterParamsState);
const pageLimit = useRecoilValue(listBranchPageLimitState);
const page = useRecoilValue(listBranchPageState);
// console.log(columnTable);
const getData = useCallback(async (page, pageLimit) => {
const {
strSearch
} = filterParams;
return await getListBranchs().getList({
page, pageLimit, strSearch
});
}, [pageLimit, filterParams, page.skip]);
const {data, refetch} = useQuery(
['PRODUCT_LIST_KEY_LIST_BRANCH', page.skip, JSON.stringify(filterParams)],
() => getData(page.skip, pageLimit),
{
keepPreviousData: true, staleTime: 5000,
placeholderData: LIST_ORDER_PLACEHOLDER_DATA
}
);
useEffect(() => {
refetch();
}, [pageLimit, filterParams, page]);
const [openDialog, setOpenDialog] = useState({open: false, id: null});
return (
<>
<TableV7 columns={ columnTable } datas={ data }
queryKey='queryKey' idDetai='detail'
keyId="id_employee" detailFunction={ getListBranchs().getDetail }
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
pageState={ listBranchPageState }
pageLimitState={ listBranchPageLimitState }
heightTable={ 690 }
/>
{openDialog.open &&
<DialogDetail
classes={ {
paper: classes.paper,
} }
id="ringtone-menu"
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
detail={ DetailInfo }/>
}
</>
);
};
export default BranchList;<file_sep>import './App.css';
import './plugins/fontAwesomeIcon';
import Routers from './router/Router';
const App = () => {
return (
<>
<Routers />
</>
);
};
export default App;
<file_sep>import React, { useState, useEffect } from 'react';
import AppBar from '@material-ui/core/AppBar';
import CssBaseline from '@material-ui/core/CssBaseline';
// import Divider from '@material-ui/core/Divider';
import Drawer from '@material-ui/core/Drawer';
// import List from '@material-ui/core/List';
// import ListItem from '@material-ui/core/ListItem';
// import ListItemIcon from '@material-ui/core/ListItemIcon';
// import ListItemText from '@material-ui/core/ListItemText';
import { makeStyles } from '@material-ui/core/styles';
import Toolbar from '@material-ui/core/Toolbar';
// import Typography from '@material-ui/core/Typography';
// import MailIcon from '@material-ui/icons/Mail';
// import InboxIcon from '@material-ui/icons/MoveToInbox';
import PropTypes from 'prop-types';
import { useRecoilValue } from 'recoil';
import useWindowDimensions from '../../hooks/useWindowDimensions';
import { setWidthDefault } from '../../store/atoms/header/header';
import MenuHeaderBar from './MenuBar';
import TopHeader from './TopHeader';
// const widthDefault = 1280;
const Header = ({ mainContent }) => {
const widthDefault = useRecoilValue(setWidthDefault);
const { screenWidth } = useWindowDimensions();
const [ widths, setWidths ] = useState(300);
const drawerWidth = widths;
useEffect(() => {
if (screenWidth > widthDefault) {
setWidths(300);
} else if (screenWidth < widthDefault) {
setWidths(0);
}
}, [ screenWidth ]);
const useStyles = makeStyles((theme) => ({
root: { display: 'flex' },
appBar: {
zIndex: theme.zIndex.drawer + 1,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
drawerContainer: {
overflow: 'auto',
// width: '22rem'
},
content: {
flexGrow: 1,
padding: theme.spacing(3),
},
}));
const classes = useStyles();
return (
<div className={ classes.root }>
<CssBaseline />
<AppBar id="header" position="fixed" className={ classes.appBar }>
<Toolbar>
<TopHeader />
</Toolbar>
</AppBar>
<Drawer
className={ classes.drawer }
variant="permanent"
classes={ {
paper: classes.drawerPaper,
} }
>
<Toolbar />
<div className={ classes.drawerContainer }>
<MenuHeaderBar />
</div>
</Drawer>
<main className={ classes.content }>
<Toolbar />
{ mainContent }
</main>
</div>
);
};
Header.propTypes = {
mainContent: PropTypes.object
};
export default Header;<file_sep>import React from 'react';
import AddCircleOutlineIcon from '@material-ui/icons/AddCircleOutline';
import PropTypes from 'prop-types';
const TableDetail = ({
data = {name: '<NAME>', numberRoom: 'Số chỗ ngồi', time: 'Ca trống', branch: 'Chi nhánh'},
text_center = 'pl-2', buttonDelete = false
}) => {
return (
<>
<div className='grid grid-cols-12'>
<div className='col-span-11 grid grid-cols-11'>
<p className={ `border-br-1 pt-2 ${text_center} col-span-2` }>{data.name}</p>
<p className={ `border-br-1 pt-2 ${text_center} col-span-2` }>{data.numberRoom}</p>
<p className={ `border-br-1 pt-2 ${text_center} col-span-2` }>{data.time}</p>
<p className={ `pt-1 ${text_center} col-span-5` }>{data.branch}</p>
</div>
{buttonDelete && <div className='ml-2 cursor-pointer' title={ 'Thay thế ngày hiện tại' }>
<AddCircleOutlineIcon className='hover:text-blue-800'/>
</div>}
</div>
</>
);
};
TableDetail.propTypes = {
data: PropTypes.object,
text_center: PropTypes.string,
buttonDelete: PropTypes.bool
};
export default TableDetail;<file_sep>import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
// import { useQueryClient } from 'react-query';
import { useSetRecoilState } from 'recoil';
// import { AUTH_USER_INFO_KEY } from '../../../constants/queryKey';
import MultipleSelect from '../../base/input/MultipleSelect';
const CardBranch = ({ filterParams, widthTitle }) => {
// const queryClient = useQueryClient();
// const { data } = queryClient.getQueryData(AUTH_USER_INFO_KEY);
const [ branch, setBranch ] = useState([]);
const branchSearch = useSetRecoilState(filterParams);
// console.log(data);
const data1 = [
{ id: 1, name: '<NAME>' },
{ id: 2, name: '<NAME>̀' },
{ id: 3, name: '<NAME>' },
{ id: 4, name: '<NAME>' }
];
useEffect(() => {
branchSearch(search => {
return {
...search,
branchSearch: branch
};
});
}, [ branch ]);
return (
<>
<div className="flex items-center w-full">
<span className={ widthTitle }>Chi nhánh</span>
<MultipleSelect data={ data1 } personName={ branch } setPersonName={ setBranch } minWidth='90%' oneChip={ true } />
</div>
</>
);
};
CardBranch.propTypes = {
filterParams: PropTypes.object,
widthTitle: PropTypes.string
};
export default CardBranch;<file_sep>import React from 'react';
import DuyTan from '../../component/place/duyTan';
const ComponentCenter = () => {
return (
<>
<DuyTan />
</>
);
};
export default ComponentCenter;<file_sep>import {lazy} from 'react';
export const Error404 = lazy(() => import('../pages/error/error404'));
export const Login = lazy(() => import('../pages/auth/login'));
export const Employee = lazy(() => import('../pages/employee/employee'));
export const Users = lazy(() => import('../pages/users/users'));
export const Room = lazy(() => import('../pages/room/room'));
//overview
export const OverviewToDay = lazy(() => import('../pages/overview/today'));
export const OverviewReport = lazy(() => import('../pages/overview/report'));
export const OverviewRevenue = lazy(() => import('../pages/overview/revenue'));
// contract
export const Contractlist = lazy(() => import('../pages/contract/contractlist'));
export const ContractReserve = lazy(() => import('../pages/contract/reserve'));
export const ContractTransfer = lazy(() => import('../pages/contract/transfer'));
export const ContractPay = lazy(() => import('../pages/contract/pay'));
// room
export const RoomList = lazy(() => import('../pages/room/roomList'));
export const Species = lazy(() => import('../pages/room/species'));
export const RoomEmpty = lazy(() => import('../pages/room/roomEmpty'));
export const Maintenance = lazy(() => import('../pages/room/maintenance'));
// employee
export const EmployeeList = lazy(() => import('../pages/employee/employeeList'));
export const Permission = lazy(() => import('../pages/employee/permission'));
export const NoLongerWorking = lazy(() => import('../pages/employee/noLongerWorking'));
//customer
export const CustomerList = lazy(() => import('../pages/customer/customerList'));
export const Unregistered = lazy(() => import('../pages/customer/unregistered'));
export const CustomerBad = lazy(() => import('../pages/customer/customerBad'));
//branch
export const BranchList = lazy(() => import('../pages/branch/branchList'));
export const BranchHistory = lazy(() => import('../pages/branch/history'));
// service
export const Equipment = lazy(() => import('../pages/service/equipment'));
export const ServiceOther = lazy(() => import('../pages/service/serviceOther'));
// report
export const ReportRevenue = lazy(() => import('../pages/report/revenue'));
export const ReportRevenuadebt = lazy(() => import('../pages/report/revenuadebt'));
export const ReportContract = lazy(() => import('../pages/report/contract'));
export const ReportSpecies = lazy(() => import('../pages/report/species'));
//book
export const SaleBookAppp = lazy(() => import('../pages/book/appointment'));<file_sep>// import {getYearMonthDay} from '../../../helpers/helper';
import {axiosInstance} from '../../../config/axios';
export const tableSearch = () => {
const getListNumberPeoPle = async ({valueBranch = 0, valueType = 0}) => {
const {data} = await axiosInstance.get('/room/find_all');
return dataProcesing(setDataNew(data), valueBranch, valueType);
};
return {getListNumberPeoPle};
};
const setDataNew = (data) => {
return data.map(i => {
return {
id: i.id,
name: i.soChoNgoi.toString(),
idBranch: i.branch1.id,
idTypeRoom: i.typeRoom.id,
soChoNgoi: i.soChoNgoi,
nameRoom: i.name
};
});
};
const dataProcesing = (data, branch, typeRoom) => {
if (data.length > 0) {
const dataNew = data.filter(i => (branch !== '' ? i.idBranch === branch : true)
&& (typeRoom !== '' ? i.idTypeRoom === typeRoom : true));
// const dataUnilque = [];
// dataUnilque.forEach(i => {
// const index = dataNew.findIndex(j => i.soChoNgoi === j.soChoNgoi);
// if (index === -1) {
// dataUnilque.push(dataNew[index]);
// }
// });
const dataUnilque = [];
const map = new Map();
for (const item of dataNew) {
if (!map.has(item.soChoNgoi)) {
map.set(item.soChoNgoi, true); // set any value to Map
dataUnilque.push({
id: item.id,
name: item.name,
});
}
}
const nameRoom = [];
const room = new Map();
for (const item of dataNew) {
if (!room.has(item.soChoNgoi)) {
room.set(item.soChoNgoi, false); // set any value to Map
nameRoom.push({
id: item.id,
name: item.nameRoom
});
}
}
return {
numberPeople: dataUnilque.length === 0 ? [{id: '', name: '<NAME>'}] : dataUnilque,
nameRoom: nameRoom.length === 0 ? [{id: '', name: '<NAME> <NAME>̣u'}] : nameRoom
};
// return dataUnilque.length === 0 ? {
// numberPeople: [{id: '', name: '<NAME>'}],
// nameRoom: [{id: '', name: '<NAME>'}]
// } : dataReturn;
} else {
return {
numberPeople: [{id: '', name: '<NAME>'}],
nameRoom: [{id: '', name: '<NAME>'}]
};
}
};<file_sep>module.exports = {
'extends': [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'react-app',
],
'parser': 'babel-eslint',
'settings': {
'react': {
'version': 'detect'
},
'import/resolver': {
'node': {
'paths': [ 'src' ]
}
}
},
'env': {
'browser': true,
'es6': true
},
'plugins': [ 'react' ],
'parserOptions': {
'sourceType': 'module',
'allowImportExportEverywhere': false,
'ecmaFeatures': {
'globalReturn': false,
'jsx': true
},
'babelOptions': {
'configFile': 'path/to/config.js'
}
},
'ignorePatterns': [
'/node_modules/**',
'/build/**',
'/src/App.test.js',
'/src/reportWebVitals.js',
'/src/setupTests.js',
'/src/initFacebookSdk.js'
],
'rules': {
'no-unused-vars': [
'error',
{
'vars': 'all',
'args': 'after-used',
'ignoreRestSiblings': false
}
],
'react/react-in-jsx-scope': 'off',
'react/prop-types': [
2,
{ 'ignore': [ 'children' ] }
],
'react/jsx-uses-react': 2,
'react/jsx-uses-vars': 'error',
'react/jsx-curly-spacing': [
2,
{
'when': 'always',
'allowMultiline': false
}
],
'react-hooks/rules-of-hooks': 'error',
'quotes': [
2,
'single'
],
'indent': [
2,
2,
{ 'SwitchCase': 1 }
],
'semi': [
2,
'always'
],
'curly': [
2,
'all'
],
'camelcase': [
0,
{ 'properties': 'always' }
],
'eqeqeq': [
2,
'smart'
],
'one-var-declaration-per-line': [
2,
'always'
],
'new-cap': 2,
'no-case-declarations': 0,
'react/function-component-definition': [
2,
{ 'namedComponents': 'arrow-function' }
],
'space-before-function-paren': 'error',
'react/display-name': [ 0 ],
'linebreak-style': [ 0, 'windows' ],
'react-hooks/exhaustive-deps': 'off',
'import/order': [
'error',
{
'groups': [ 'builtin', 'external', 'internal' ],
'pathGroups': [
{
'pattern': 'react',
'group': 'external',
'position': 'before'
}
],
'pathGroupsExcludedImportTypes': [ 'react' ],
'newlines-between': 'always',
'alphabetize': {
'order': 'asc',
'caseInsensitive': true
}
}
],
'import/no-anonymous-default-export': [ 0, { 'allowCallExpression': true } ]
}
};
<file_sep>import { getCookie } from '../config/cookies';
export default () => {
const csOfficeToken = getCookie('csoffice_accessToken');
const csofficeRefreshToken = getCookie('csoffice_refreshToken');
const userInfo = getCookie('user_info');
return { csOfficeToken, csofficeRefreshToken, userInfo };
};
<file_sep>// import React from 'react';
// import RadioGroup from '../../base/radio/RadioGroup';
// const Filter = () => {
// return (
// <>
// <div>
// <div className="m-4 text-xl font-bold">
// <p>Khách hàng</p>
// </div>
// <RadioGroup />
// </div>
// </>
// );
// };
// export default Filter;<file_sep>import React from 'react';
const Rules = () => {
return (
<>
<div className='w-full'>
<div className="border-2 mx-48">
<h4 className="text-center font-bold py-4">ĐIỀU KHOẢN VÀ CHÍNH SÁCH ĐẶT PHÒNG</h4>
<div>
<h3 className="font-bold mx-10 my-2">Điều khoản:</h3>
<ol className="list-decimal ml-20 mr-8">
<li className="text-justify">Hợp đồng dân sự được giao kết vào thời điểm bên đề nghị nhận được trả lời chấp nhận giao kết.
Hợp đồng dân sự cũng xem như được giao kết khi hết thời hạn trả lời mà bên nhận được đề nghị vẫn im lặng,
nếu có thoả thuận im lặng là sự trả lời chấp nhận giao kết.
Thời điểm giao kết hợp đồng bằng lời nói là thời điểm các bên đã thỏa thuận về nội dung của hợp đồng.
Thời điểm giao kết hợp đồng bằng văn bản là thời điểm bên sau cùng ký vào văn bản.</li>
<li className="text-justify">Hợp đồng được giao kết hợp pháp có hiệu lực từ thời điểm giao kết, trừ trường hợp
có thỏa thuận khác hoặc pháp luật có quy định khác.</li>
<li className="text-justify">Trong các điều khoản trên, có những điều khoản các bên không cần thỏa thuận ở hợp đồng này nhưng
lại bắt buộc phải thỏa thuận trong hợp đồng khác. Tùy vào mỗi hợp đồng cụ thể mà các điều khoản cũng có sự thay đổi khác nhau.
Ngoài ra, các bên trong hợp đồng còn có thể thỏa thuận, xác định với nhau thêm những điều khoản mà các bên cảm thấy cần thiết.
Nội dung trong hợp đồng dân sự thể hiện sự thỏa thuận của hai bên, những thỏa thuận này không được vi phạm pháp luật, nếu những
vấn đề mà không được đề cập trong nội dung của hợp đồng thì sẽ áp dụng quy định chung của pháp luật để giải quyết tranh chấp</li>
</ol>
</div>
<div className="mb-10">
<h3 className="font-bold mx-10 my-2">Chính sách:</h3>
<ol className="list-decimal ml-20 mr-8">
<li className="text-justify">Hợp đồng dân sự được giao kết vào thời điểm bên đề nghị nhận được trả lời chấp nhận giao kết.
Hợp đồng dân sự cũng xem như được giao kết khi hết thời hạn trả lời mà bên nhận được đề nghị vẫn im lặng,
nếu có thoả thuận im lặng là sự trả lời chấp nhận giao kết.
Thời điểm giao kết hợp đồng bằng lời nói là thời điểm các bên đã thỏa thuận về nội dung của hợp đồng.
Thời điểm giao kết hợp đồng bằng văn bản là thời điểm bên sau cùng ký vào văn bản.</li>
<li className="text-justify">Hợp đồng được giao kết hợp pháp có hiệu lực từ thời điểm giao kết, trừ trường hợp
có thỏa thuận khác hoặc pháp luật có quy định khác.</li>
<li className="text-justify">Trong các điều khoản trên, có những điều khoản các bên không cần thỏa thuận ở hợp đồng này nhưng
lại bắt buộc phải thỏa thuận trong hợp đồng khác. Tùy vào mỗi hợp đồng cụ thể mà các điều khoản cũng có sự thay đổi khác nhau.
Ngoài ra, các bên trong hợp đồng còn có thể thỏa thuận, xác định với nhau thêm những điều khoản mà các bên cảm thấy cần thiết.
Nội dung trong hợp đồng dân sự thể hiện sự thỏa thuận của hai bên, những thỏa thuận này không được vi phạm pháp luật, nếu những
vấn đề mà không được đề cập trong nội dung của hợp đồng thì sẽ áp dụng quy định chung của pháp luật để giải quyết tranh chấp</li>
</ol>
</div>
</div>
</div>
</>
);
};
export default Rules;<file_sep>import React from 'react';
// import DayPicker from 'react-day-picker';
// import Button from '@material-ui/core/Button';
import 'react-day-picker/lib/style.css';
import PropTypes from 'prop-types';
import { useFormContext, Controller } from 'react-hook-form';
// import IconCamera from '../../../../../assets/image/iconCamera.png';
import DateSingle from '../../../../base/dateTime/DateSingle';
import ImageUpdate from '../../../../common/ImageUpdate';
import SelectedInput from '../../../../common/SelectedInput';
import Sex from '../../../../common/Sex';
import TextFieldInput from '../../../../common/TextFieldInput';
import TextPassword from '../../../../common/TextPassword';
const positionList = [
{ id: '1', text: 'Admin' },
{ id: '2', text: 'Quản lý' },
{ id: '3', text: 'Lễ tân' },
{ id: '4', text: 'Sale' }
];
const branchList = [
{ id: '1', text: 'Chi nhánh Thanh Xuân' },
{ id: '2', text: 'Chi nhánh Nam Từ Liêm' },
{ id: '3', text: 'Chi nhánh Hà Đông' },
{ id: '4', text: 'Chinh nhánh Đống Đa' }
];
const DialogAddInfo = ({ setForm, form, isAdd }) => {
const methods = useFormContext();
const { formState: { errors }, control } = methods;
return (
<>
<div style={ { height: '500px' } }>
<div>
<h4 className='text-base text-blue-700'>Thông tin cá nhân</h4>
<div className='grid grid-cols-3'>
<div>
<ImageUpdate />
</div>
<div className="col-span-2 grid grid-cols-1 gap-2">
<div className="grid grid-cols-2 gap-x-8 w-full">
<Controller
name={ 'fist_name' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Họ nhân viên" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.fist_name?.type === 'required' ? 'Họ nhân viên không được bỏ trống!' : null } /> } />
<Controller
name={ 'last_name' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="<NAME>ên" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.last_name?.type === 'required' ? 'Tên nhân viên không được bỏ trống!' : null } /> } />
<div className="mt-3">
<Controller
name={ 'sex' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<Sex
onChange={ e => {
onChange(e.target.value);
} }
value={ value } /> } />
</div>
<div className="flex items-end w-full">
<DateSingle title="Ngày sinh" classNameTitle="w-1/4"
onChange={ setForm }
value={ form } keySearch="birthday"
/>
</div>
<Controller
name={ 'phone' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Số điện thoại" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.phone?.type === 'required' ? 'Số điện thoại nhân viên không được bỏ trống!' : null } /> } />
<Controller
name={ 'email' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Email" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.email?.type === 'required' ? 'Email nhân viên không được bỏ trống!' : null } /> } />
</div>
<div className="w-full">
<Controller
name={ 'address' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Quê quán" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.address?.type === 'required' ? 'Quê quán nhân viên không được bỏ trống!' : null } /> } />
</div>
<div className="w-full">
<Controller
name={ 'hktt' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Hộ khẩu thường trú" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.hktt?.type === 'required' ? 'HKTt nhân viên không được bỏ trống!' : null } /> } />
</div>
{/* <div className="w-full">
<Controller
name={ 'note_personal' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Ghi chú cá nhân" className="w-full" multiline rows={ 3 } id="standard-multiline-static"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null } /> } />
</div> */}
</div>
</div>
</div>
<div>
<p className='text-base text-blue-700 mt-6'>Thông tin làm việc</p>
<div className="grid grid-cols-3 gap-x-8">
<Controller
name={ 'code_employee' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Mã nhân viên tự động" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.code_employee?.type === 'required' ? 'Mã nhân viên không được bỏ trống!' : null } /> } />
<Controller
name={ 'position' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<SelectedInput
dataArr={ positionList }
title='Chức vụ'
value={ value }
onChange={ e => {
onChange(e.target.value);
} }
/> }
/>
<Controller
name={ 'branch' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<SelectedInput
dataArr={ branchList }
title='Chi nhánh'
value={ value }
onChange={ e => {
onChange(e.target.value);
} }
/> }
/>
<div className="flex items-end pb-3 w-full">
<DateSingle title="Thời gian vào" classNameTitle="w-1/3" onChange={ setForm } value={ form } keySearch="start_day" />
</div>
<Controller
name={ 'user_employee' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Tên tà<NAME>̉n" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.user_employee?.type === 'required' ? 'Tài khoản nhân viên không được bỏ trống!' : null } /> } />
{
isAdd &&
<Controller
name={ 'pass_employee' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextPassword className="w-full" multiline rows={ 3 } id="standard-multiline-static"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.pass_employee?.type === 'required' ? 'Mật khẩu không được bỏ trống!' : null } /> } />
}
</div>
{/*<div>*/}
{/* <Controller*/}
{/* name={ 'node_work' }*/}
{/* control={ control }*/}
{/* rules={ {} }*/}
{/* render={ ({ field: { onChange, value } }) =>*/}
{/* <TextFieldInput label="Ghi chú công việc" className="w-full" multiline rows={ 3 } id="standard-multiline-static"*/}
{/* onChange={ e => {*/}
{/* onChange(e.target.value);*/}
{/* } }*/}
{/* value={ value }*/}
{/* error={ null } /> } />*/}
{/*</div>*/}
</div>
</div>
</>
);
};
DialogAddInfo.propTypes = {
form: PropTypes.object,
setForm: PropTypes.func,
isAdd: PropTypes.bool
};
export default DialogAddInfo;<file_sep>import React, {useCallback, useEffect, useState} from 'react';
import {ArrowDropDown, ArrowDropUp, HighlightOff} from '@material-ui/icons';
// import Button from '@material-ui/core/Button';
// import {makeStyles} from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import {useQuery} from 'react-query';
import {getListAppointment} from '../../../../../service/book/listBook/appointment';
import {listBookFilterParamsState} from '../../../../../store/atoms/book/appointment';
import CheckboxGroup_V2 from '../../../../base/checkbox/CheckboxGroup_V2';
import DateFromTo_V2 from '../../../../base/dateTime/DateFromTo_V2';
// const useStyles = makeStyles((theme) => ({
// button: {
// margin: theme.spacing(1),
// },
// button1: {
// margin: theme.spacing(0),
// marginRight: '6px'
// },
// }));
const SchedulesItem = ({datas, onDelete}) => {
// const classes = useStyles();
// console.log(data);
// const {listShift, datePresent, listService} = data;
// const [data, setData] = useState(datas);
// useEffect(() => {
// setData(datas);
// }, [datas]);
// Ngày đặt lịch
const [valueFrom, setValueFrom] = useState(new Date(datas.datePresent));
useEffect(() => {
setValueFrom(new Date(datas.datePresent));
}, [datas]);
const [opentDetail, setOpentDetail] = useState(false);
//Danh sách ca đã đặt
const {data: dataTime} = useQuery(
['LIST_TIME_SALE'],
() => getListAppointment().getListTime(),
{
keepPreviousData: true, staleTime: 5000,
}
);
const dataTimeNew = useCallback(() => {
if (dataTime.filter(i => i.startTime.indexOf('C') !== -1)[0].id === datas.listShift[0].id) {
return dataTime.map(item => {
return {
...item,
checked: true
};
});
} else {
return dataTime.map(item => {
return {
...item,
checked: datas.listShift.filter(i => i.id === item.id).length === 0 ? false : true,
};
});
}
}, [datas]);
const timeSelect = dataTimeNew().filter(i => i.startTime.indexOf('C') === -1);
const timeSelectAll = dataTimeNew().filter(i => i.startTime.indexOf('C') !== -1);
// Danh sách dịch vụ
const {data: dataService} = useQuery(
['LIST_SERVICE'],
() => getListAppointment().getListService(),
{
keepPreviousData: true, staleTime: 5000,
}
);
const dataServiceNew = () => {
return dataService.map(item => {
return {
...item,
checked: datas.listService.filter(i => i.id === item.id).length === 0 ? false : true,
};
});
};
return (
<>
<div className='shadow-lg bg-gray-100 mb-3'>
<div className='w-fulll flex items-center px -3 grid grid-cols-5 gap-x-2'>
<div className='mr-6'>
<DateFromTo_V2 title={ '' } value={ valueFrom }
onChange={ setValueFrom } classNameTitle='w-64'/>
</div>
<div className='col-span-4 ml-4 flex items-center'>
<CheckboxGroup_V2 dataCheckbox={ timeSelect } title={ '' } filterParams={ listBookFilterParamsState }
name={ 'listTime' } dataAll={ timeSelectAll } className='w-full'
lableAll={ 'Cả ngày' } color={ 'primary' } column={ '5' }/>
<div onClick={ () => setOpentDetail(!opentDetail) } className='cursor-pointer' title={ 'Chi tiết' }>
{opentDetail ? <ArrowDropUp className='hover:text-blue-800'/> :
<ArrowDropDown className='hover:text-blue-800'/>}
</div>
<div className='ml-2 cursor-pointer' title={ 'Xóa ngày' }>
<HighlightOff className='hover:text-blue-800' onClick={ onDelete }/>
</div>
</div>
</div>
{
opentDetail && <div className='mx-5 my-2'>
<CheckboxGroup_V2 dataCheckbox={ dataServiceNew() } title={ 'Dịch vụ yêu cầu' }
filterParams={ listBookFilterParamsState }
name={ 'listService' } className='w-full text-xs' dataAll={ [] } column={ '5' }/>
</div>
}
</div>
</>
);
};
SchedulesItem.propTypes = {
datas: PropTypes.object,
onDelete: PropTypes.func,
};
export default SchedulesItem;<file_sep>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import { useTheme } from '@material-ui/core/styles';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import TabPanel from '../../../components/common/tabPanel/TabPanel';
import { a11yProps, useStyles } from '../../../components/common/tabPanel/tabPanelProps';
import Layout from '../../../layouts';
import ListEmployee from '../EmployeeList/listEmployee';
import Filter from '../EmployeeList/listEmployee/Filters';
import NoLongerWorking from '../EmployeeList/noLongerWorking';
import FilterNo from '../EmployeeList/noLongerWorking/Filters';
const EmployeeList = () => {
const classes = useStyles();
const theme = useTheme();
const [ value, setValue ] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<>
<Layout>
<div className={ classes.root }>
<AppBar position="static" color="default">
<Tabs
value={ value }
onChange={ handleChange }
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
aria-label="scrollable auto tabs example"
>
<Tab label="Danh sách nhân viên" { ...a11yProps(0) } />
{/*<Tab label="Nhân viên đã nghỉ" { ...a11yProps(1) } />*/}
</Tabs>
</AppBar>
<TabPanel value={ value } index={ 0 } dir={ theme.direction } className="customs-tabPanel" nav={ Filter }>
<ListEmployee />
</TabPanel>
<TabPanel value={ value } index={ 1 } dir={ theme.direction } className="customs-tabPanel" nav={ FilterNo }>
<NoLongerWorking />
</TabPanel>
</div>
</Layout>
</>
);
};
export default EmployeeList;<file_sep>import React from 'react';
import Permission from '../../components/employees/Permission';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Phân quyền' ];
const Employee = () => {
return (
<>
<LayoutLink title="Phân quyền" listLink={ listLink }>
<Permission />
</LayoutLink>
</>
);
};
export default Employee;
<file_sep>import React from 'react';
import Translate from '../../component/serviceOrther/Translate';
const ComponentCenter = () => {
return (
<>
<Translate />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import OnlineMeetingRoom from '../../component/service/OnlineMeetingRoom';
const ComponentCenter = () => {
return (
<>
<OnlineMeetingRoom />
</>
);
};
export default ComponentCenter;<file_sep>import React, { useEffect } from 'react';
// import NewLogo from '../../assets/images/new_logo_2.png';
import LayoutError from '../../layouts/error';
const Error404 = () => {
useEffect(() => {
document.title = 'Trang không tồn tại';
}, []);
return (
<>
<LayoutError
logo={ null }
title='Lỗi! Trang không tồn tại.'
subTitle={ 'Quay lại' }
nameError={ '404' }
>
<h1 style={ { fontSize: 160 } }>404</h1>
</LayoutError>
</>
);
};
export default Error404;<file_sep>import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
// import { useQueryClient } from 'react-query';
import { useSetRecoilState } from 'recoil';
// import { AUTH_USER_INFO_KEY } from '../../../constants/queryKey';
import MultipleSelect from '../../base/input/MultipleSelect';
const CardPosition = ({ filterParams }) => {
// const queryClient = useQueryClient();
// const { data } = queryClient.getQueryData(AUTH_USER_INFO_KEY);
const [ position, setPosition ] = useState([]);
const positionSearch = useSetRecoilState(filterParams);
// console.log(data);
const data1 = [
{ id: 1, name: 'Admin' },
{ id: 2, name: '<NAME>́' },
{ id: 3, name: 'Sale' },
{ id: 4, name: '<NAME>' }
];
useEffect(() => {
positionSearch(search => {
return {
...search,
positionSearch: position
};
});
}, [ position ]);
return (
<>
<div className="flex items-center w-full">
<span className="w-1/5">Chức vụ</span>
<MultipleSelect data={ data1 } personName={ position } setPersonName={ setPosition } minWidth='90%' />
</div>
</>
);
};
CardPosition.propTypes = {
filterParams: PropTypes.object
};
export default CardPosition;<file_sep>import React from 'react';
const DetailInfo = () => {
return (
<>
<h1>Thêm mới nhân viên</h1>
</>
);
};
export default DetailInfo;<file_sep>import React from 'react';
import Pay from '../../components/contract/pay';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Thanh toán hợp đồng' ];
const Contract = () => {
return (
<>
<LayoutLink title="Thanh toán hợp đồng" listLink={ listLink }>
<Pay />
</LayoutLink>
</>
);
};
export default Contract;
<file_sep>import { atom } from 'recoil';
const today = new Date();
export const listContractFilterParamsState = atom({
key: 'listContractFilterParamsState',
default: {
strSearch: '',
codeSearch: '',
// nameSearch: '',
// orderType: 99,
// branchSearch: [],
// statusSearch: 99,
// employeeSale: [],
// employeePT: [],
// tablePriceSearch: [],
// promotionSearch: [],
debitSearch: 99,
from_date: today,
to_date: today,
// from_date_expire: '',
// to_date_expire: '',
// status_expire: 99
}
});
export const listContractPageLimitState = atom({
key: 'listContractPageLimitState',
default: 15
});
export const listContractPageState = atom({
key: 'listContractPageState',
default: 1
});
export const listContractColumnTableState = atom({
key: 'listContractColumnTableState',
default: [
{ field: 'detail', headerName: 'Chi tiết', width: 80, sortable: false, description: 'Chi tiết', cellClassName: 'cursor-pointer' },
{ field: 'id_contract', headerName: 'Mã hợp đồng', width: 120, sortable: false, description: 'Mã hợp đồng' },
{ field: 'name_contract', headerName: 'Tên hợp đồng', width: 150, sortable: false, description: 'Tên hợp đồng' },
{ field: 'name_branch', headerName: 'Tên chi nhánh', width: 150, sortable: false, description: 'Tên chi nhánh' },
{ field: 'name_room_type', headerName: 'Tên loại phòng', width: 150, sortable: false, description: 'Tên loại phòng' },
{ field: 'id_customer', headerName: 'Mã khách hàng', width: 150, sortable: false, description: 'Mã khách hàng' },
{ field: 'name_customer', headerName: 'Tên khách hàng', width: 150, sortable: false, description: 'Tên khách hàng' },
{ field: 'signing_time', headerName: 'Thời gian ký', width: 150, sortable: false, description: 'Thời gian ký' },
{ field: 'start_time', headerName: 'Thời gian bắt đầu', width: 150, sortable: false, description: 'Thời gian bắt đầu' },
{ field: 'end_time', headerName: 'Thời gian kết thúc', width: 150, sortable: false, description: 'Thời gian kết thúc' },
{ field: 'time_remaining', headerName: 'Thời gian còn lại', width: 150, sortable: false, description: 'Thời gian còn lại' },
{ field: 'number_of_equipment', headerName: 'Số lượng thiết bị', width: 150, sortable: false, description: 'Số lượng thiết bị' },
{ field: 'note', headerName: 'Ghi chú', width: 150, sortable: false, description: 'Ghi chú' },
]
});<file_sep>import React from 'react';
const Quotation = () => {
return (
<>
<h1>{ 'Viết code cho trang "Bảng báo giá" ở đây' }</h1>
</>
);
};
export default Quotation;<file_sep>import React from 'react';
const ListService =() => {
return (
<>
</>
);
};
export default ListService;<file_sep>import React from 'react';
import Introduce from '../../component/introduces/introduce';
const ComponentCenter = () => {
return (
<>
<Introduce />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
const ElectronicSocialInsurance = () => {
return (
<>
<h1>{ 'Viết code cho trang "BHXH điện tử" ở đây' }</h1>
</>
);
};
export default ElectronicSocialInsurance;<file_sep>import React from 'react';
const ThemeColor = () => {
return (
<>
</>
);
};
export default ThemeColor;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
// import { useQueryClient } from 'react-query';
import {Route} from 'react-router';
import {Redirect} from 'react-router-dom';
// import { useSetRecoilState } from 'recoil';
// import { AUTH_USER_INFO_KEY } from '../../constants/queryKey';
// import { openDialogLogin } from '../../store/atoms/auth/user';
// import { getAccount } from '../../service/auth/login';
const PrivateRoute = ({component: Component, is_view = true, ...rest}) => {
// const data = {
// data: {
// user: ''
// }
// };
// const queryClient = useQueryClient();
// const data = queryClient.getQueryData(AUTH_USER_INFO_KEY);
// 1 Admin, 2 Quản lý, 3 Sale, 4 Lễ tân
const data = {
data: {
user: 'admin',
pass: '1',
branch: 1,
role: 1
}
};
// const localUser = localStorage.setItem('user', data.data.user);
// const localRole = localStorage.setItem('role', data.data.role);
// const setDialogLogin = useSetRecoilState(openDialogLogin);
// React.useEffect(() => {
// if (data !== undefined) {
// setDialogLogin(false);
// }
// }, [ data ]);
return (
<>
<Route
{ ...rest }
render={ (props) => data && data.data.user ? (is_view ? <Component { ...props } />
:
<Redirect to={ {pathname: '/error/not-permission', state: {from: props.location}} }/>) :
<Redirect to={ {pathname: '/auth/login', state: {from: props.location}} }/> }
/>
</>
);
};
PrivateRoute.propTypes = {
component: PropTypes.object,
location: PropTypes.any,
is_view: PropTypes.bool
};
export default PrivateRoute;<file_sep>import { axiosInstance } from '../../../config/axios';
export const getListContract = () => {
const getList = async () => {
const { data } = await axiosInstance.get('/employees-employees-employees');
return data;
};
const getDetail = async () => {
const { data } = await axiosInstance.get('/employees-employees-employees');
return data;
};
return { getList, getDetail };
};
<file_sep>import React from 'react';
import Unregistered from '../../components/customer/unregistered';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Chưa đăng ký phòng' ];
const Customer = () => {
return (
<>
<LayoutLink title='Chưa đăng ký phòng' listLink={ listLink }>
<Unregistered />
</LayoutLink>
</>
);
};
export default Customer;<file_sep>import React from 'react';
import {
BusinessCenter, EventSeat, MeetingRoomRounded, Money, YouTube
} from '@material-ui/icons';
const Home = () => {
return (
<>
<div className="grid grid-cols-2 gap-2 py-3">
<div className="py-36">
<h1 className="text-blue-800 font-bold text-center text-xl">HANOI OFFICE – COWORKING SPACE: GIẢI
PHÁP CHO THUÊ VĂN PHÒNG THÔNG MINH</h1>
<h1 className="text-blue-800 font-bold text-center text-xl">MINH</h1>
<span className="pl-16 font-bold text-center">Kiến tạo </span>
<span className="text-center pr-10">không gian Văn Phòng Cho Thuê – Coworking Space hiện đại và chuyên nghiệp,xây dựng cộng đồng doanh</span>
<span className="pl-52 text-center"> nghiệp năng động và đầy nhiệt huyết,</span>
<span className="font-bold text-center"> Hanoi Office – Success in all your Plans!</span>
<div className="grid grid-cols-5 gap-2 py-3">
<div className="pl-10 border-r text-center">
<p className="text-center"><EventSeat/></p>
<span className="pt-3">Chỗ ngồi làm việc</span>
</div>
<div className="border-r text-center">
<p className="text-center"><MeetingRoomRounded/></p>
<span className="pt-3">Phòng Họp</span>
</div>
<div className="border-r text-center">
<p className="text-center"><MeetingRoomRounded/></p>
<span className="pt-3">Phòng Họp Trực Tuyến</span>
</div>
<div className="border-r text-center">
<p><BusinessCenter/></p>
<span className="pt-3">Văn Phòng Ảo</span>
</div>
<div className="text-center">
<p><BusinessCenter/></p>
<span className="pt-3">Văn Phòng Cho Thuê</span>
</div>
</div>
<div>
<div>
<label className="">Chọn một địa điểm</label>
<label className="pl-72">Nhu cầu sử dụng</label>
</div>
<select name="branch" placeholder="Tất cả các địa điểm" className="border py-3 pl-4 pr-52">
<option value="">Tất cả các địa điểm</option>
<option value="">QUẬN BA ĐÌNH</option>
<option value="">QUẬN CẦU GIẤY</option>
<option value="">QUẬN HÀ ĐÔNG</option>
<option value="">QUẬN HOÀNG MAI</option>
<option value="">QUẬN NAM TỪ LIÊM</option>
<option value="">QUẬN THANH XUÂN</option>
</select>
<select name="nhucau" placeholder="Nhu cầu sử dụng" className="border ml-4 py-3 pl-4 pr-48">
<option value="">Nhu cầu sử dụng</option>
<option value="">Cá nhân</option>
<option value="">Thuê cho 2 đến 3 người</option>
<option value="">Thuê cho 4 đến 5 người</option>
<option value="">Thuê cho 5 đến 10 người</option>
<option value="">Trên 10 người</option>
</select>
<button className="mx-3 border bg-blue-500 text-white font-bold py-3 px-8">TÌM</button>
</div>
</div>
<div>
<h1>Slide Ảnh</h1>
</div>
</div>
<div className="bg-blue-800 py-6">
<div className="grid grid-cols-2 gap-2">
<div className="pl-20 mr-36">
<p className="font-bold text-white">Bạn đang tìm thuê văn phòng và chưa tìm được giải pháp phù
hợp và tối ưu?</p>
<p className="font-bold text-white">Hãy để Hanoi Office – Coworking Space giúp bạn!</p>
</div>
<div>
<button className="border border-white bg-gray-200 px-4 py-3 ml-96 hover:bg-blue-500">
ĐĂT LỊCH NGAY!
</button>
</div>
</div>
</div>
<div className="text-center pt-10">
<h1 className="inline-block pr-1.5 text-2xl">06 GIẢI PHÁP CHO THUÊ VĂN PHÒNG</h1>
<h1 className="font-bold inline-block text-2xl">TẠI HANOI OFFICE COWORKING SPACE</h1>
</div>
<div className="grid grid-cols-9 pt-16">
<div className="ml-80 col-span-3">
<a href="">
<img className="w-72 h-60"
src="https://hanoioffice.vn/wp-content/uploads/2020/09/va%CC%86n-pho%CC%80ng-a%CC%89o.jpg"
alt=""/>
<p className="font-bold text-center">VĂN PHÒNG ẢO</p>
</a>
<p>Bạn sẽ được sử dụng văn phòng ảo ở Hà Nội để: làm văn phòng đại diện, địa chỉ giao dịch, tiếp đối
tác – khách hàng, địa chỉ nhận bưu thư…</p>
</div>
<div className="col-span-2 mr-24 ml-12 ">
<a href="">
<img className="w-72 h-60"
src="https://hanoioffice.vn/wp-content/uploads/2020/08/cho-thue-van-phong-lam-viec.jpg"
alt=""/>
<p className="font-bold text-center">VĂN PHÒNG TRỌN GÓI</p>
</a>
<p>Bạn sẽ sở hữu: 1 phòng làm việc riêng, phòng họp – phòng khách sang trọng, thiết bị văn phòng
hiện đại,… Và không lo đóng phí điện – nước, internet.</p>
</div>
<div className="mr-56 col-span-4 pt-36">
<h1 className="font-bold text-xl">KHÔNG GIAN VĂN PHÒNG CHO THUÊ SANG TRỌNG & LỊCH LÃM</h1>
<p className="text-center">Hanoi Office đem đến giải pháp không gian văn phòng làm việc sang trọng
và lịch</p>
<p className="text-center">thiệp, giải pháp của Hanoi Office sẽ giúp bạn có những ngày làm việc hiệu
quả</p>
<p className="text-center">trong không gian văn phòng làm việc riêng mà không bị làm phiền.</p>
<div className="text-center pt-3">
<button
className="border-2 border-blue-400 bg-blue-500 text-white font-bold px-12 py-3 hover:bg-white hover:text-black">THUÊ
VĂN PHÒNG
</button>
</div>
</div>
</div>
<div className="">
<div className="grid grid-cols-9 pt-16">
<div className="ml-56 pt-36 col-span-5">
<h1 className="font-bold text-xl text-center">CHỖ NGỒI LÀM VIỆC CHUYÊN NGHIỆP PHÙ HỢP VỚI MỌI
NHU CẦU</h1>
<h1 className="font-bold text-xl text-center">CỦA BẠN</h1>
<p className="text-center">Chỗ ngồi làm việc trong một không gian chung mở nhưng vẫn đảm bảo
tính riêng</p>
<p className="text-center">tư (vách ngăn – bàn làm việc riêng) và bảo mật (tủ tài liệu riêng).
Chi phí phù hợp</p>
<p className="text-center">mà bạn vẫn được sử dụng đầy đủ tất cả các tiện ích từ Hanoi
Office.</p>
<div className="text-center pt-3">
<button
className="border-2 border-blue-400 bg-blue-500 text-white font-bold px-12 py-3 hover:bg-white hover:text-black">THUÊ
CHỖ NGỒI
</button>
</div>
</div>
<div className="col-span-2">
<a href="">
<img className="w-72 h-60"
src="https://hanoioffice.vn/wp-content/uploads/2020/08/Va%CC%86n-pho%CC%80ng-lu%CC%9Bu-do%CC%A3%CC%82ng.jpg"
alt=""/>
<p className="font-bold pl-12">VĂN PHÒNG LƯU ĐỘNG</p>
</a>
<div>
<p className="pr-16">Bạn có thể sử dụng không gian văn phòng trên toàn bộ hệ thống Hanoi
Office. Phù hợp với nhu cầu liên tục di chuyển tại trung tâm Hà Nội.</p>
</div>
</div>
<div className="col-span-2">
<a href="">
<img className="w-72 h-60"
src="https://hanoioffice.vn/wp-content/uploads/2020/08/cho-thue-van-phong-lam-viec.jpg"
alt=""/>
<p className="font-bold text-center pr-32">CHỖ NGỒI LÀM VIỆC</p>
</a>
<p className="pr-28">Bạn chỉ phải trả tiền cho một chỗ ngồi làm việc nhưng lại được sử dụng đầy
đủ tiện ích văn phòng, thiết bị hiện đại trong một không gian yên tĩnh.</p>
</div>
</div>
</div>
<div className="grid grid-cols-9 pt-16">
<div className="ml-80 col-span-3">
<a href="">
<img className="w-72 h-60"
src="https://hanoioffice.vn/wp-content/uploads/2020/08/phong-hop-cho-thue.jpg" alt=""/>
<p className="font-bold text-center">PHÒNG HỌP CHO THUÊ</p>
</a>
<p>Phòng họp có sức chứa từ 10-30 người sẽ phù hợp với các nhu cầu khác nhau của bạn. Được trang bị
đầy đủ thiết bị hiện đại trong không gian sang trọng.</p>
</div>
<div className="col-span-2 mr-24 ml-12 ">
<a href="">
<img className="w-72 h-60"
src="https://hanoioffice.vn/wp-content/uploads/2020/08/phong-hop-truc-tuyen.jpg" alt=""/>
<p className="font-bold text-center">PHÒNG HỌP TRỰC TUYẾN</p>
</a>
<p>Cho thuê phòng họp giá rẻ – hội nghị trực tuyến tại Hà Nội với công nghệ âm thanh, video call
hiện đại, sắc nét với chi phí chỉ từ 400.000đ/giờ.</p>
</div>
<div className="mr-48 col-span-4 pt-36">
<h1 className="font-bold text-xl">2 GIẢI PHÁP PHÒNG HỌP CHO THUÊ HIỆN ĐẠI PHÙ HỢP MỌI MỤC</h1>
<h1 className="font-bold text-xl text-center">ĐÍCH</h1>
<p className="text-center">Hanoi Office trang bị những thiết bị tối tân và hiện đại nhất cho không
gian phòng</p>
<p className="text-center">họp, ngoài ra Hanoi Office còn có thể setup phòng họp trực tuyến tại
chính cơ sở</p>
<p className="text-center">của bạn đem đến tính chủ động và linh hoạt.</p>
<div className="text-center pt-3">
<button
className="border-2 border-blue-400 bg-blue-500 text-white font-bold px-12 py-3 hover:bg-white hover:text-black">THUÊ
PHÒNG HỌP
</button>
</div>
</div>
</div>
<div className="text-center pt-10">
<h1 className="inline-block pr-1.5 text-2xl">TẠI SAO NÊN CHỌN KHÔNG GIAN</h1>
<h1 className="font-bold inline-block text-2xl">CHO THUÊ VĂN PHÒNG TẠI HANOI OFFICE COWORKING SPACE</h1>
</div>
<div className="grid grid-cols-5 text-center pt-20">
<div className="text-right pl-96 pr-10 text-justify col-span-2">
<div>
<span className="text-blue-500 pr-2"><YouTube className="mb-2"/></span>
<span className="font-bold text-xl">CHUYÊN NGHIỆP</span>
<p className="text-justify">Xây dựng một hình ảnh doanh nghiệp chuyên</p>
<p className="text-justify">nghiệp trong mắt đối tác của bạn thông qua</p>
<p className="text-justify">không gian văn phòng cho thuê hiện đại của</p>
<p className="text-justify">Hanoi Office.</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><YouTube className="mb-2"/></span>
<span className="font-bold text-xl">KẾT NỐI</span>
<p className="text-justify">Giải pháp cho thuê Văn phòng công ty thông</p>
<p className="text-justify">minh - Văn phòng chia sẻ tạo nên một cộng</p>
<p className="text-justify">đồng các doanh nghiệp trong và ngoài nước,</p>
<p className="text-justify">mở ra những cơ hội kết nối mới.</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><YouTube className="mb-2"/></span>
<span className="font-bold text-xl">LINH HOẠT</span>
<p className="text-justify">Hanoi Office cho thuê văn phòng trọn gói linh</p>
<p className="text-justify">hoạt thời gian với 4 hình thức: Theo giờ, theo</p>
<p className="text-justify">ngày, theo tuần và theo tháng.</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><YouTube className="mb-2"/></span>
<span className="font-bold text-xl">AN TÂM</span>
<p className="text-justify">Luôn sát cánh, hỗ trợ các doanh nghiệp như</p>
<p className="text-justify">một người bạn đồng hành tận tâm. Bạn sẽ </p>
<p className="text-justify">thực sự an tâm khi thuê văn phòng thông </p>
<p>minh tại Hanoi Office.</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><YouTube className="mb-2"/></span>
<span className="font-bold text-xl">HIỆN ĐẠI</span>
<p className="text-justify text-s">Hanoi Office được trang bị những trang thiết bị</p>
<p className="text-justify text-s">văn phòng hiện đại hàng đầu Việt Nam, giúp</p>
<p className="text-justify text-s">bộ máy của bạn hoạt động trơn tru hơn. </p>
</div>
</div>
<div className="col-span-1">
<img src="https://hanoioffice.vn/wp-content/uploads/2020/08/hanoi-office-cho-thue-van-phong.jpg"
alt=""/>
</div>
<div className="text-left col-span-2 pl-10">
<div className="">
<span className="text-blue-500 pr-2"><Money className="mb-2"/></span>
<span className="font-bold text-xl">TIẾT KIỆM</span>
<p className="text-justify text-s">Hanoi Office tin rằng văn phòng chia sẻ sẽ giúp</p>
<p className="text-justify text-s">bạn tiết kiệm nhiều thời gian quản lý và chi phí</p>
<p className="text-justify text-s">hoạt động. Đem lại những giá trị cốt lõi cho </p>
<p>bạn!</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><Money className="mb-2"/></span>
<span className="font-bold text-xl">ƯU ĐÃI</span>
<p className="text-justify text-s">Luôn có những chính sách ưu đãi với các gói </p>
<p className="text-justify text-s">dịch vụ cho thuê Văn Phòng công ty thông </p>
<p className="text-justify text-s">minh - Coworking Space tại Hà Nội cho những</p>
<p>khách hàng thân thiết.</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><Money className="mb-2"/></span>
<span className="font-bold text-xl">HIỆU QUẢ</span>
<p className="text-justify ">Giải pháp cho thuê văn phòng chia sẻ - văn</p>
<p className="text-justify ">phòng thông minh giúp doanh nghiệp lựa chọn</p>
<p className="text-justify ">dịch vụ phù hợp để đạt hiệu quả tốt nhất.</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><Money className="mb-2"/></span>
<span className="font-bold text-xl">DỊCH VỤ HỖ TRỢ</span>
<p className="">Cho thuê văn phòng coworking tư vấn thành</p>
<p className="">lập Doanh nghiệp, thiết kế website, kế toán,</p>
<p className="">biên - phiên dịch, soạn thảo văn bản, chữ ký số,</p>
<p>hóa đơn điện tử, BHXH điện tử...</p>
</div>
<div className="pt-2">
<span className="text-blue-500 pr-2"><Money className="mb-2"/></span>
<span className="font-bold text-xl">RIÊNG TƯ - BẢO MẬT</span>
<p className="text-justify ">Không gian văn phòng Hanoi Office được thiết</p>
<p className="text-justify ">kế riêng tư cho từng doanh nghiệp. Camera an</p>
<p className="text-justify ">ninh và Bảo vệ 24/7 giúp bạn an toàn tuyệt đối.</p>
</div>
</div>
</div>
<div className="grid grid-cols-2 pt-8">
<div className="ml-96">
<div className="pb-2">
<div className="pb-2">
<span className="font-bold">TIỆN ÍCH</span>
<span className="font-bold ml-16 pl-96">100%</span>
</div>
<div className="bg-blue-500 h-2"></div>
</div>
<div className="pb-2">
<div className="pb-2">
<span className="font-bold">TỐI ƯU CHI PHÍ</span>
<span className="font-bold ml-20 pl-80">90%</span>
</div>
<div className="bg-blue-500 h-2 w-11/12"></div>
</div>
<div className="pb-2">
<div className="pb-2">
<span className="font-bold mr-8 pr-64">TRANG THIẾT BỊ VĂN PHÒNG</span>
<span className="font-bold">100%</span>
</div>
<div className="bg-blue-500 h-2"></div>
</div>
<div className="pb-2">
<div className="pb-2">
<span className="font-bold">HỆ SINH THÁI</span>
<span className="font-bold ml-6 pl-96">100%</span>
</div>
<div className="bg-blue-500 h-2"></div>
</div>
<div className="pb-2">
<div className="pb-2">
<span className="font-bold mr-10 pr-72">KHÁCH HÀNG HÀI LÒNG</span>
<span className="font-bold">90%</span>
</div>
<div className="bg-blue-500 h-2 w-11/12"></div>
</div>
</div>
<div className="text-left pl-8">
<div>
<span className="font-bold">Hanoi Office </span>
<span>đem đến các giải pháp dịch vụ cho thuê văn phòng như: </span>
<span className="font-bold">Văn phòng</span>
<p className="font-bold">ảo – Văn phòng trọn gói – Văn phòng chia sẻ – Chỗ ngồi làm việc – Phòng
họp</p>
<span className="font-bold">Coworking Space </span>
<span>giúp bạn tối ưu 80% chi phí nhưng vẫn có được một không gian</span>
<p>và môi trường làm việc văn phòng chuyên nghiệp.</p>
</div>
<div className="pt-3">
<span>Đến với </span>
<span className="font-bold">Hanoi Office </span>
<span>bạn sẽ được tận hưởng dịch vụ </span>
<span className="font-bold">cho thuê văn phòng tại Hà</span>
<p className="font-bold ">Nội <span className="">hoàn hảo và những trải nghiệm tốt nhất. Không những được thiết kế bởi</span>
</p>
<p className="inline-block">các kiến trúc sư hàng đầu,</p>
<p className="font-bold inline-block">văn phòng cho thuê</p>
<span>còn được trang bị bởi những thiết</span>
<p>bị văn phòng hiện đại nhất.</p>
</div>
<div className="pt-3">
<span className="font-bold">Hanoi Office Coworking Space </span>
<span>sẽ hỗ trợ mọi nhu cầu của Doanh nghiệp bạn khi</span>
<p>cần, cùng bạn tiến tới thành công!</p>
</div>
</div>
</div>
<div className="grid grid-cols-12 text-center pt-8">
<div className="ml-80 pl-12 col-span-6 text-center pt-48">
<h1 className="font-bold text-center text-lg">ĐĂNG KÝ TƯ VẤN GIẢI PHÁP KHÔNG GIAN VĂN PHÒNG CHO
THUÊ</h1>
<div className="pt-4">
<p className="text-center">Hãy điền thông tin và yêu cầu của bạn, các chuyên viên Hanoi Office
sẽ liên hệ và</p>
<p className="text-center">tư vấn chi tiết cho bạn về giải pháp không gian văn phòng thuê
Coworking Space</p>
<p className="text-center">Hà Nội</p>
</div>
</div>
<div className="text-left col-span-6 ml-6 mr-80">
<div className="">
<img className="mx-auto pb-4"
src="https://hanoioffice.vn/wp-content/uploads/2020/10/cho-thue-van-phong-chi-tu-7000-vnd.png"/>
<div className="grid grid-cols-2">
<div className="inline-block mr-3">
<label>Họ và tên:*</label>
<input className="border border-gray-300 block pl-1.5 pr-28 py-1.5" type="text"/>
</div>
<div className="inline-block">
<label>Email:*</label>
<input className="border border-gray-300 block pl-1.5 pr-28 py-1.5" type="text"/>
</div>
</div>
<div className="grid grid-cols-2">
<div className="mr-3">
<label>Số điện thoại:*</label>
<input className="border border-gray-300 block pl-1.5 pr-28 py-1.5" type="text"/>
</div>
<div>
<label className="">Lựa chọn giải pháp:</label>
<select className="border border-gray-300 block pr-28 py-1.5" type="text"
placeholder="<NAME>">
<option value="">Văn Phòng Trọn Gói</option>
<option value="">Chỗ Ngồi Làm Việc</option>
<option value="">Văn Phòng Lưu Động</option>
<option value="">Văn Phòng Ảo</option>
<option value="">Phòng Họp</option>
<option value="">Phòng Họp Trực Tuyến</option>
</select>
</div>
</div>
<div>
<label>Yêu cầu chi tiết:</label>
<textarea className="block border border-gray-300 pl-1.5 pr-56"
placeholder="Hãy nhập yêu cầu chi tiết của bạn vào đây..." cols="50"
rows="10"></textarea>
</div>
<div className="pt-2">
<button
className="border border-blue-500 bg-blue-500 px-16 py-2 text-white hover:bg-white hover:text-black">GỬI
YÊU CẦU
</button>
</div>
</div>
</div>
</div>
<div className="text-center pt-10">
<h1 className="inline-block pr-1.5 text-2xl">DỊCH VỤ</h1>
<h1 className="font-bold inline-block text-2xl">HỖ TRỢ DOANH NGHIỆP</h1>
</div>
<div className="grid grid-cols-4 text-center gap-4 px-80 pt-12">
<div>
<a href=""><img
src="https://hanoioffice.vn/wp-content/uploads/2020/10/bao-hiem-xa-hoi-dien-tu-400x230.png"/></a>
<h1 className="font-bold text-center">BẢO HIỂM XÃ HỘI ĐIỆN TỬ</h1>
<p className="text-gray-400 text-center">Cung cấp phần mềm BHXH điện tử với</p>
<p className="text-gray-400 text-center">10+ tiện ích,giúp các doanh nghiệp rút</p>
<p className="text-gray-400 text-center">ngắn thời gian và linh hoạt.</p>
</div>
<div>
<a href=""><img src="https://hanoioffice.vn/wp-content/uploads/2020/10/chu-ky-so-400x230.png"/></a>
<h1 className="font-bold text-center">CHỮ KÝ SỐ</h1>
<p className="text-gray-400 text-center">Hỗ trợ doanh nghiệp đăng ký chữ ký số</p>
<p className="text-gray-400 text-center">(token), kích hoạt và hướng dẫn sử</p>
<p className="text-gray-400 text-center">dụng chi tiết.</p>
</div>
<div>
<a href=""><img
src="https://hanoioffice.vn/wp-content/uploads/2020/10/hoa-don-dien-tu-400x230.png"/></a>
<h1 className="font-bold text-center">HÓA ĐƠN ĐIỆN TỬ</h1>
<p className="text-gray-400 text-center">Hanoi Office sẽ tư vấn và giúp bạn làm</p>
<p className="text-gray-400 text-center">mọi thủ tục để tạo hóa đơn điện tử cho</p>
<p className="text-gray-400 text-center">doanh nghiệp</p>
</div>
<div>
<a href=""><img
src="https://hanoioffice.vn/wp-content/uploads/2020/10/thanh-lap-doanh-nghiep-400x230.png"/></a>
<h1 className="font-bold text-center">THÀNH LẬP DOANH NGHIỆP</h1>
<p className="text-gray-400 text-center">Hanoi Office sẽ tư vấn và giúp bạn xử</p>
<p className="text-gray-400 text-center">lý mọi thủ tục để thành lập một doanh</p>
<p className="text-gray-400 text-center">nghiệp trong thời gian nhanh nhất.</p>
</div>
</div>
<div className="text-center pt-10">
<h1 className="inline-block pr-1.5 text-2xl">KHÁM PHÁ KHÔNG GIAN VR 360</h1>
<h1 className="font-bold inline-block text-2xl">VĂN PHÒNG CHO THUÊ TẠI HANOI OFFICE</h1>
</div>
<div className="text-center py-3">Slide Ảnh</div>
<div className="bg-blue-500 py-6">
<div className="grid grid-cols-3 gap-2">
<div className="pl-20 mr-24 pl-24 col-span-2">
<p className="font-bold text-white">Bạn chưa tìm được văn phòng cho thuê tại Hà Nội phù hợp? Hãy
để Hanoi Office – Coworking</p>
<p className="font-bold text-white">Space giúp bạn!</p>
</div>
<div className="col-span-1">
<button className="border border-white bg-gray-200 ml-48 px-4 py-3 ml-96 hover:bg-blue-500">NHẬN
TƯ VẤN
</button>
</div>
</div>
</div>
<div className="text-center pt-10">
<h1 className="inline-block pr-1.5 text-2xl">HÃY LỰA CHỌN MỘT ĐỊA CHỈ</h1>
<h1 className="font-bold inline-block text-2xl">CHO THUÊ VĂN PHÒNG TẠI HÀ NỘI THUẬN TIỆN NHẤT</h1>
</div>
<div className="pt-4">
<p className="text-center text-gray-500">Văn phòng cho thuê Hanoi Office Coworking Space được đặt tại
các vị trí giao thông đi lại thuận tiện, ở những địa chỉ tập trung nhiều công ty lớn và các ngân
hàng. Chúng</p>
<p className="text-center text-gray-500">tôi sẽ giúp bạn tận dụng được tối đa các cơ hội kinh doanh của
mình.</p>
</div>
<div className="pt-16 grid grid-cols-6 text-center px-6 mx-80">
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-ba-dinh.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Ba Đình</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-cau-giay.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Cầu Giấy</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-ha-dong.jpg"/>
</a>
<p className="font-bold text-xl">2 Cơ sở</p>
<p className="font-bold text-xl">Quận Hà Đông</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/12/quan-hoang-mai.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Hoàng Mai</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-nam-tu-liem.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Nam Từ Liêm</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-thanh-xuan.jpg"/>
</a>
<p className="font-bold text-xl">2 Cơ sở</p>
<p className="font-bold text-xl">Quận Thanh Xuân</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
</div>
<div className="pt-3">
<img className="mx-auto"
src="https://static.vncommerce.com/maps/600x250/T%E1%BA%A7ng+6,T%C3%B2a+Nh%C3%A0+Vi%E1%BB%87t+%C3%81,9+Ph%E1%BB%91+Duy+T%C3%A2n,Qu%E1%BA%ADn+C%E1%BA%A7u+Gi%E1%BA%A5y,H%C3%A0+N%E1%BB%99i,Vi%E1%BB%87t+Nam.png"/>
</div>
<div className="text-center pt-16">
<h1 className="inline-block pr-1.5 text-2xl">GIỚI THIỆU VỀ</h1>
<h1 className="font-bold inline-block text-2xl">HANOI OFFICE</h1>
</div>
<div className="pt-3">
<p className="text-center text-xl">Dịch vụ cho thuê Văn Phòng Ảo - Phòng Làm Việc Riêng - Chỗ Ngồi Làm Việc -
Phòng Họp - Coworking Space tại Hà Nội</p>
</div>
<div className="pt-10 text-center">
<span className="font-bold italic">Hanoi Office – Mô hình Coworking Space </span>
<span className="italic"> tiên phong trong lĩnh vực cho</span>
<p className="italic">thuê Văn phòng ảo – Văn phòng trọn gói – Coworking Space ở Hà Nội</p>
<p className="italic">nói riêng và Việt Nam nói chung. Chúng tôi sẽ đem đến cho quý khách</p>
<p className="italic">hàng những dịch vụ và trải nghiệm tốt nhất. Vì chúng tôi hiểu bạn, luôn</p>
<p className="italic">bên bạn và cùng bạn đi tới Thành công!</p>
</div>
<div className="pt-3 text-center">
<span className="italic">Giải pháp </span>
<span className="font-bold italic">Cho thuê văn phòng – Coworking Space tại Hà Nội </span>
<span className="italic">kiến tạo</span>
<p className="italic">cho bạn một không gian làm việc chuyên nghiệp, hiện đại và sáng tạo,</p>
<p className="italic">xây dựng cộng đồng doanh nghiệp tiên phong và đứng đầu.</p>
</div>
<div className="pt-3 text-center">
<span className="font-bold italic">Hãy đến Hanoi Office – Coworking Space và trải nghiệm ngay!</span>
</div>
<div className="pt-10 text-center pb-16">
<button
className="border border-blue-500 bg-blue-500 text-white px-16 py-2 hover:bg-white hover:text-black">THUÊ VĂN
PHÒNG
</button>
</div>
<div className="grid grid-cols-2 bg-blue-500 py-3">
<div className="ml-52">
<p className="font-bold">Bạn đang tìm thuê văn phòng thông minh – Coworking Space tại Hà Nội? Hãy để Hanoi
Office</p>
<p className="font-bold">– Coworking Space giúp bạn!</p>
</div>
<div className="ml-48">
<button className="ml-24 text-white border border-black hover:bg-white hover:text-black py-2 px-16">GỢI Ý ĐỊA
ĐIỂM
</button>
</div>
</div>
<div className="pt-4">
<h1 className="font-bold text-2xl text-center">TIN TỨC</h1>
</div>
<div className="pt-4">
<div className="grid grid-cols-4 gap-2 mx-96">
<div>
<a href="" title="Tin Tức">
<img className="w-72 h-48"
src="https://hanoioffice.vn/wp-content/uploads/2021/06/van-phong-cho-thue-quan-ha-dong-day-du-tien-ich-chi-tu-650000-VND-thang-2.jpg"/>
</a>
</div>
<div>
<a href="" title="Tin Tức">
<img className="w-72 h-48"
src="https://hanoioffice.vn/wp-content/uploads/2021/06/kham-pha-tien-ich-uu-viet-tai-van-phong-cho-thue-hanoi-office-co-so-khuat-duy-tien-thanh-xuan-2.jpg"/>
</a>
</div>
<div>
<a href="" title="Tin Tức">
<img className="w-72 h-48"
src="https://hanoioffice.vn/wp-content/uploads/2021/06/nam-giu-bi-quyet-dieu-hanh-doanh-nghiep-lam-viec-tu-xa-hieu-qua.jpg"/>
</a>
</div>
<div>
<a href="" title="Tin Tức">
<img className="w-72 h-48"
src="https://hanoioffice.vn/wp-content/uploads/2021/05/5-loi-ich-uu-viet-tu-mo-hinh-van-phong-chia-se-da-nang-2-1.jpg"/>
</a>
</div>
</div>
</div>
<div className="text-center pt-3">
Slide Ảnh
</div>
</>
);
};
export default Home;<file_sep>import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from '@material-ui/core/FormGroup';
import FormLabel from '@material-ui/core/FormLabel';
import PropTypes from 'prop-types';
const UtilitiesList = ({ dataArr }) => {
return (
<>
<div>
<FormControl component="fieldset">
<FormLabel component="legend">Các tiện của chi nhánh</FormLabel>
<FormGroup aria-label="position" row className="px-5">
{
dataArr.map((item, index) => {
return (
<FormControlLabel key={ index }
value={ item.id }
control={ <Checkbox color="primary" /> }
label={ item.text }
labelPlacement="end"
/>
);
})
}
</FormGroup>
</FormControl>
</div>
</>
);
};
UtilitiesList.propTypes = {
dataArr: PropTypes.array,
};
export default UtilitiesList;<file_sep>import React from 'react';
import LeVanLuong from '../../component/place/leVanLuong';
const ComponentCenter = () => {
return (
<>
<LeVanLuong />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
const LegalNews = () => {
return (
<>
<h1>{ 'Viết code cho trang "Tin tức pháp luật" tại đây' }</h1>
</>
);
};
export default LegalNews;<file_sep>import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
// import { useQueryClient } from 'react-query';
import { useSetRecoilState } from 'recoil';
// import { AUTH_USER_INFO_KEY } from '../../../constants/queryKey';
import MultipleSelect from '../../../../base/input/MultipleSelect';
const CardBranch = ({ filterParams }) => {
// const queryClient = useQueryClient();
// const { data } = queryClient.getQueryData(AUTH_USER_INFO_KEY);
const [ branch, setBranch ] = useState([]);
const branchSearch = useSetRecoilState(filterParams);
// console.log(data);
const data1 = [
{ id: 1, name: '<NAME>' },
{ id: 2, name: '<NAME>' },
{ id: 3, name: '<NAME>' },
{ id: 4, name: '<NAME>' }
];
useEffect(() => {
branchSearch(search => {
return {
...search,
branchSearch: branch
};
});
}, [ branch ]);
return (
<>
<div className="flex items-center w-full">
<span className="w-1/5">Thành phần</span>
<MultipleSelect data={ data1 } personName={ branch } setPersonName={ setBranch } minWidth='90%' oneChip={ true } />
</div>
</>
);
};
CardBranch.propTypes = {
filterParams: PropTypes.object
};
export default CardBranch;<file_sep>
const findIndexItem = (arr, item) => {
return arr.findIndex((listItem) => listItem === item);
};
const replaceItemAtIndex = (arr, index, newValue) => {
return [ ...arr.slice(0, index), newValue, ...arr.slice(index + 1) ];
};
export {
replaceItemAtIndex,
findIndexItem
};<file_sep>import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useRecoilValue } from 'recoil';
import useWindowDimensions from '../hooks/useWindowDimensions';
import { showLeftSideState } from '../store/atoms/header/header';
const Layout = (props) => {
const { screenWidth } = useWindowDimensions();
const showLeft = useRecoilValue(showLeftSideState);
useEffect(() => {
document.title = props.title ? 'HaNoiOffice - ' + props.title : 'HaNoiOffice';
}, [ props.children ]);
return (
<div className="w-full responsive-p-4 main-container bg-white">
<div className="md:mr-4 w-full flex">
{
props.nav ?
<div className={ `w-main-left mr-4 ${screenWidth < 960 ? 'hidden' : showLeft ? 'block' : 'hidden'}` }>
{ props.nav }
</div> :
null
}
<div className={ `w-full w-main-right border-l-2 ${showLeft ? 'md:w-main-right' : 'pr-7'}` }>{ props.children }</div>
</div>
</div>
);
};
Layout.propTypes = {
nav: PropTypes.node,
title: PropTypes.string
};
export default Layout;<file_sep>import React from 'react';
import Document from '../../component/news/document';
const ComponentCenter = () => {
return (
<>
<Document />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import BranchList from '../../components/branch/branchList';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Danh sách chi nhánh' ];
const Branch = () => {
return (
<>
<LayoutLink title='Danh sách chi nhánh' listLink={ listLink }>
<BranchList />
</LayoutLink>
</>
);
};
export default Branch;<file_sep>import React from 'react';
const MeetingRoom = () => {
return (
<>
<h1>{ 'Viết code cho màn hình "Phòng họp" tại đây' }</h1>
</>
);
};
export default MeetingRoom;<file_sep>import React from 'react';
import { ResponsivePie } from '@nivo/pie';
import PropTypes from 'prop-types';
import DateYear from '../../../base/dateTime/DateYear';
const RatioBranchRevenueChart = ({ data }) => {
return (
<>
<div className="w-full bg-white shadow-lg rounded-lg">
<div className="flex justify-between">
<p className="text-xl font-medium antialiased px-3 pt-3">Tỉ lệ doanh thu theo chi nhánh</p>
<div className="mx-3"><DateYear /></div>
</div>
<div className="w-full h-190 ">
<ResponsivePie
data={ data }
margin={ { top: 10, right: 80, bottom: 10, left: -40 } }
activeOuterRadiusOffset={ 8 }
borderWidth={ 1 }
borderColor={ { from: 'color', modifiers: [ [ 'darker', 0.2 ] ] } }
enableArcLinkLabels={ false }
arcLinkLabelsSkipAngle={ 10 }
arcLinkLabelsTextColor="#333333"
arcLinkLabelsThickness={ 2 }
arcLinkLabelsColor={ { from: 'color' } }
arcLabelsSkipAngle={ 10 }
arcLabelsTextColor={ { from: 'color', modifiers: [ [ 'darker', 2 ] ] } }
defs={ [
{
id: 'dots',
type: 'patternDots',
background: 'inherit',
color: 'rgba(255, 255, 255, 0.3)',
size: 4,
padding: 1,
stagger: true
},
{
id: 'lines',
type: 'patternLines',
background: 'inherit',
color: 'rgba(255, 255, 255, 0.3)',
rotation: -45,
lineWidth: 6,
spacing: 10
}
] }
fill={ [
{
match: {
id: 'ruby'
},
id: 'dots'
},
{
match: {
id: 'c'
},
id: 'dots'
},
{
match: {
id: 'go'
},
id: 'dots'
},
{
match: {
id: 'python'
},
id: 'dots'
},
{
match: {
id: 'scala'
},
id: 'lines'
},
{
match: {
id: 'lisp'
},
id: 'lines'
},
{
match: {
id: 'elixir'
},
id: 'lines'
},
{
match: {
id: 'javascript'
},
id: 'lines'
}
] }
legends={ [
{
anchor: 'top-right',
direction: 'column',
justify: false,
translateX: 33,
translateY: 20,
itemsSpacing: 16,
itemWidth: 103,
itemHeight: 11,
itemTextColor: '#999',
itemDirection: 'left-to-right',
itemOpacity: 1,
symbolSize: 18,
symbolShape: 'circle',
effects: [
{
on: 'hover',
style: {
itemTextColor: '#000'
}
}
]
}
] }
/>
<div className="pb-3 px-4 flex justify-start">
<p className="hover:text-blue-700 cursor-pointer">Xem chi tiết</p>
</div>
</div>
</div>
</>
);
};
RatioBranchRevenueChart.propTypes = {
title: PropTypes.string,
data: PropTypes.array
};
export default RatioBranchRevenueChart;<file_sep>import React from 'react';
import {ChevronRight} from '@material-ui/icons';
const AllInclusiveOffice = () => {
return (
<>
<div className="grid grid-cols-2 gap-2">
<div className="bg-gradient-to-r from-yellow-400 via-red-500 to-pink-500">
<div>
<img src="" alt=""/>
</div>
</div>
<div className="mt-20 mb-24 mr-5 pl-2 pl-2">
<h2 className="text-center text-3xl font-bold text-blue-500">CHO THUÊ VĂN PHÒNG TRỌN GÓI</h2>
<h4 className="text-center border-b-2 border-fuchsia-600 font-bold">Cho thuê không gian làm việc
sang trọng, trọn gói tiện ích tại Hà Nội</h4>
<div className="mt-4">
<span className="text-center">Hanoi Office </span>
<span className="font-bold text-center">cho thuê văn phòng trọn gói </span>
<span className="text-center">đáp ứng đầy đủ tất cả các nhu cầu hoạt động của một doanh nghiệp: Địa chỉ Đăng ký</span>
<p className="text-center">kinh doanh; Phòng làm việc chuyên nghiệp; Phòng họp – Phòng khách
sang trọng; Thiết bị văn phòng: Điện thoại bàn, máy fax,</p>
<p className="text-center">máy in scan, photocopy, internet,…</p>
</div>
<div className="mt-10">
<p className="text-red-400 font-bold text-xl"><ChevronRight url=""/>Tìm hiểu văn phòng trọn gói
là gì?</p>
</div>
<div className="pb-20">
<p>Chọn một địa điểm</p>
<select className="pl-8 pr-96 py-2 mr-2 border border-gray-300" placeholder="Tất cả địa điểm">
<option value="">Tất cả địa điểm</option>
</select>
<button
className="border border-blue-500 bg-blue-500 text-white px-32 py-1.5 max-w-max hover:bg-white hover:text-black">TÌM
</button>
</div>
</div>
</div>
<div className="grid grid-cols-2 bg-blue-500 mt-3 py-3">
<div className="ml-52">
<p className="font-bold text-white">Bạn đang tìm thuê văn phòng trọn gói tại Hà Nội giúp để tối ưu
90% chi phí vận hành?</p>
<p className="font-bold text-white">Liên hệ Hanoi Office ngay!</p>
</div>
<div className="ml-48">
<button
className="ml-24 bg-white font-bold text-black border border-white hover:bg-blue-500 hover:text-white py-2 px-16">NHẬN
TƯ VẤN
</button>
</div>
</div>
<div className="mt-12">
<h1 className="font-bold text-2xl text-center">TẠI SAO NÊN CHỌN GIẢI PHÁP CHO THUÊ VĂN PHÒNG TRỌN GÓI
TẠI HANOI OFFICE?</h1>
<div className="mt-3">
<p className="text-center">Với ngân sách chỉ từ 4.000.000 VNĐ/tháng, bạn thuê được văn phòng ở
đâu?</p>
<p className="text-center">1 tháng doanh nghiệp của bạn phải chi cho điện – nước – mạng bao nhiêu
tiền?</p>
<p className="text-center">Bạn mất bao nhiêu tiền để đầu tư setup cho 1 văn phòng mới?</p>
</div>
</div>
<div className="mt-12 grid grid-cols-4 mx-80 gap-3">
<div>
<img className="mx-auto" src="https://hanoioffice.vn/wp-content/uploads/2020/12/7-01.png" alt=""/>
<h3 className="font-bold text-center pt-6 text-xl">ĐẦY ĐỦ TIỆN ÍCH HIỆN ĐẠI & SANG TRỌNG</h3>
<div className="pt-2 pl-3">
<p>Hanoi Office được thiết kế chủ đạo với</p>
<p>nội thất bằng gỗ tạo nên một không</p>
<p>gian sang trọng và được trang bị đầy đủ</p>
<p>tiện ích văn phòng cho bạn.</p>
</div>
</div>
<div>
<img className="mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/07/hanoioffice-save-money-icon.png"
alt=""/>
<h3 className="font-bold text-center pt-6 text-xl">TÍNH PHÍ TRỌN GÓI - TỐI ƯU CHI PHÍ</h3>
<div className="pt-2 pl-3">
<p>Doanh nghiệp chỉ chi trả đúng phần</p>
<p>diện tích mà mình sử dụng, nhưng</p>
<p>được sử dụng toàn bộ không gian</p>
<p>chung như: Phòng họp - Phòng khách</p>
</div>
</div>
<div>
<img className="mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/07/hanoioffice-growth-icon.png" alt=""/>
<h3 className="font-bold text-center pt-6 text-xl">TĂNG TRƯỞNG VÀ PHÁT TRIỂN DOANH NGHIỆP</h3>
<div className="pt-2 pl-3">
<p>Văn phòng trọn gói Hanoi Office tại các</p>
<p>vị trí đắc địa tại Hà Nội, nơi hội tụ tất</p>
<p>cả về kinh tế… là cơ hội giúp bạn mở</p>
<p>rộng cơ hội giao thương</p>
</div>
</div>
<div>
<img className="mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/07/hanoioffice-connect-business-icon.png"
alt=""/>
<h3 className="font-bold text-center pt-6 text-xl">CỘNG ĐỒNG KẾT NỐI DOANH NGHIỆP</h3>
<div className="pt-2 pl-3">
<p>Hanoi Office là một cộng đồng doanh</p>
<p>nghiệp với 3000 tổ chức và 5000 cá</p>
<p>nhân hiện đang sử dụng giải pháp văn</p>
<p>phòng của chúng tôi.</p>
</div>
</div>
</div>
<div className="grid grid-cols-2 mx-80 px-4 gap-4 pt-16">
<div>
<a href=""><img
src="https://hanoioffice.vn/wp-content/uploads/2020/10/van-phong-tron-goi-1.jpg"/></a>
</div>
<div>
<a href=""> <img
src="https://hanoioffice.vn/wp-content/uploads/2020/08/cho-thue-phong-lam-viec-phong-hop.jpg"/></a>
</div>
</div>
<div className="grid grid-cols-2 mx-80 px-4 gap-4 pt-2">
<div>
<a href="">
<img
src="https://hanoioffice.vn/wp-content/uploads/2020/08/cho-thue-van-phong-lam-viec-phong-khach.jpg"/>
</a>
</div>
<div>
<a href="">
<img
src="https://hanoioffice.vn/wp-content/uploads/2020/08/cho-thue-van-phong-lam-viec-le-tan.jpg"/>
</a>
</div>
</div>
<h3 className="font-bold mx-80 text-xl pt-4 border-b-2">TIẾT KIỆM 5 LOẠI CHI PHÍ KHI CHỌN THUÊ VĂN PHÒNG
TRỌN GÓI HANOI OFFICE</h3>
<div className="pt-10 grid grid-cols-2 px-80 mx-8 text-center">
<div className="border border-dashed border-black">
<div className="px-4">
<svg className="w-64 h-48 mx-auto pt-6" viewBox="0 0 36 36">
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="blue"
strokeWidth="1"
strokeDasharray="50, 100"
/>
<text className="text-xs percentage" x="10" y="20.35">50%</text>
</svg>
<h1 className="text-center font-bold pt-6">TIẾT KIỆM CHI PHÍ HOẠT ĐỘNG</h1>
<p className="text-center pt-4">Văn Phòng Cho Thuê tại Hanoi Office hoàn toàn miễn phí điện -
nước - mạng</p>
<p>giúp bạn tối ưu chi phí hoạt động</p>
</div>
</div>
<div className="border border-dashed border-black">
<svg className="w-64 h-48 mx-auto pt-6" viewBox="0 0 36 36">
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="blue"
strokeWidth="1"
strokeDasharray="100, 100"
/>
<text className="text-xs percentage" x="4" y="20.35">100%</text>
</svg>
<h1 className="text-center font-bold pt-6">TIẾT KIỆM CHI PHÍ ĐẦU TƯ THIẾT BỊ</h1>
<p className="text-center pt-4">Hanoi Office đã trang bị đầy đủ các thiết bị văn phòng: Máy in, máy
photocopy,</p>
<p>máy fax, điện thoại bàn, tủ tài liệu, bàn, ghế...</p>
</div>
</div>
<div className="pt-16 text-center">
<h1 className="text-xl font-bold">TIẾT KIỆM CHI PHÍ CƠ HỘI</h1>
<p>Hanoi Office không chỉ là cho thuê văn phòng trọn gói mà còn kiến tạo một cộng đồng doanh nghiệp,
giúp bạn tận dụng tối đa các cơ hội kinh doanh.</p>
</div>
<div className="pt-2 grid grid-cols-3 mx-72 pl-56">
<div className="">
<h3 className="text-blue-500 font-bold text-7xl pl-2">3000</h3>
<div className="border-b-2 ml-16 mr-64 pr-4 pt-4"></div>
<h3 className="font-bold pt-4">CÔNG TY & TỔ CHỨC</h3>
<p className="pt-4 pl-10">Trong nước</p>
</div>
<div>
<h3 className="text-blue-500 font-bold text-7xl pl-2">5000</h3>
<div className="border-b-2 ml-16 mr-64 pr-4 pt-4"></div>
<h3 className="font-bold pt-4 pl-12">CÁ NHÂN</h3>
<p className="pt-4 pl-2">Trong và ngoài nước</p></div>
<div>
<h3 className="text-blue-500 font-bold text-7xl pl-6">322</h3>
<div className="border-b-2 ml-16 mr-64 pr-4 pt-4"></div>
<h3 className="font-bold pt-4 pl-6">ĐỐI TÁC QUỐC TẾ</h3>
<p className="pt-4 pl-5">Trong và ngoài nước</p>
</div>
</div>
<div className="pt-10 grid grid-cols-2 px-80 mx-8 text-center">
<div className="border border-dashed border-black">
<svg className="w-64 h-48 mx-auto pt-6" viewBox="0 0 36 36">
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="blue"
strokeWidth="1"
strokeDasharray="100, 100"
/>
<text className="text-xs percentage" x="4" y="20.35">100%</text>
</svg>
<h1 className="text-center font-bold pt-6">NHÂN SỰ 0 ĐỒNG</h1>
<p className="text-center pt-4">Bạn sẽ không phải bỏ chi phí để có một lễ tân xinh đẹp, bảo vệ 24/7,
nhân viên</p>
<p>tạp vụ luôn giữ văn phòng sạch đẹp.</p>
</div>
<div className="border border-dashed border-black">
<div className="px-4">
<svg className="w-64 h-48 mx-auto pt-6" viewBox="0 0 36 36">
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="blue"
strokeWidth="1"
strokeDasharray="50, 100"
/>
<text className="text-xs percentage" x="10" y="20.35">50%</text>
</svg>
<h1 className="text-center font-bold pt-6">DEAL HỜI TỪ HANOI OFFICE</h1>
<p className="text-center pt-4">Giảm 50% tháng đầu tiên cho hợp đồng 06 tháng. Tặng thêm 01
tháng sử dụng</p>
<p>không mất phí + Miễn phí ĐKKD khi ký hợp đồng 12 tháng.</p>
</div>
</div>
</div>
<div className="grid grid-cols-12 text-center pt-8">
<div className="ml-80 pl-12 col-span-6 text-center">
<img src="https://hanoioffice.vn/wp-content/uploads/2020/10/van-phong-tron-goi-1-1.jpg" alt=""/>
</div>
<div className="text-left col-span-6 ml-6 mr-80">
<div className="pt-6">
<h1 className="font-bold text-center pb-4 text-center">ĐĂNG KÝ TƯ VẤN VĂN PHÒNG TRỌN GÓI</h1>
<div className="grid grid-cols-2">
<div className="inline-block mr-3">
<label>Họ và tên:*</label>
<input className="border border-gray-300 block pl-1.5 pr-28 py-1.5" type="text"/>
</div>
<div className="inline-block">
<label>Email:*</label>
<input className="border border-gray-300 block w-full pl-1.5 pr-28 py-1.5" type="text"/>
</div>
</div>
<div className="grid grid-cols-2">
<div className="mr-1.5">
<label>Số điện thoại:*</label>
<input className="border border-gray-300 block pl-1.5 pr-28 py-1.5" type="text"/>
</div>
<div className="ml-1">
<label className="">Ngày hẹn:</label>
<input className="border border-gray-300 block w-full pl-1.5 pr-2 py-1.5" type="date"/>
</div>
</div>
<div className="pt-2">
<label>Địa điểm bạn quan tâm:</label>
<select className="border border-gray-300 block pr-28 py-1.5 w-full " type="text"
placeholder="Chọn địa điểm">
<option value="Chọn địa điểm">Chọn địa điểm</option>
<option value="131 Trần Phú - Hà Đông">131 Trần Phú - Hà Đông</option>
<option value="87 Nguyễn Thái Học - Ba Đình">87 Nguyễn Thái Học - Ba Đình</option>
<option value="121-123 Tô Hiệu - Hà Đông">121-123 Tô Hiệu - Hà Đông</option>
<option value="Lê Đức Thọ - Nam Từ Liêm">Lê Đức Thọ - Nam Từ Liêm</option>
<option value="12 Khuất Duy Tiến - Thanh Xuân">12 Khuất Duy Tiến - Thanh Xuân</option>
<option value="78 Duy Tân - Cầu Giấy">78 Duy Tân - Cầu Giấy</option>
</select>
</div>
<div className="pt-2">
<label>Yêu cầu chi tiết:</label>
<input type="text" className="border border-gray-300 block w-full pl-1.5 py-1.5"/>
</div>
<div className="pt-2">
<button
className="border border-blue-500 bg-blue-500 px-10 py-2 text-white hover:bg-white hover:text-black">GỬI
</button>
</div>
</div>
</div>
</div>
<div className="bg-gray-100 mt-12">
<h1 className="text-2xl pt-12 font-bold text-center">DỊCH VỤ CHO THUÊ VĂN PHÒNG TRỌN GÓI TẠI HÀ NỘI VỚI
12 TIỆN ÍCH MIỄN PHÍ</h1>
<p className="pt-2 text-center">Thuê văn phòng tại Hanoi Office bạn chỉ cần bỏ ra chi phí từ 4.000.000đ/
tháng để sử dụng trọn gói tiện ích: Phòng họp hiện đại, phòng khách sang trọng, điện - nước -</p>
<p className="text-center">internet, trang thiết bị văn phòng.</p>
<div className="grid grid-cols-4 pt-4 mx-80 pl-4 gap-2">
<div>
<h4 className="font-bold">1. PHÒNG KHÁCH SANG TRỌNG</h4>
<p>Bạn được sử dụng phòng khách sang</p>
<p>trọng hoàn toàn miễn phí trên toàn</p>
<p>hệ thống của Hanoi Office.</p>
</div>
<div>
<h4 className="font-bold">2. PHÒNG HỌP HIỆN ĐẠI</h4>
<p>Phòng họp được trang bị đầy đủ trang</p>
<p>thiết bị: Máy chiếu, tivi, bảng viết,...</p>
<p>luôn sẵn sàng phục vụ bạn khi bạn cần.</p>
</div>
<div>
<h4 className="font-bold">3. ĐỊA CHỈ ĐĂNG KÝ KINH DOANH</h4>
<p>Bạn sẽ có 1 địa chỉ đăng ký kinh doanh</p>
<p>ở các vị trí đắc địa tại trung tâm Hà</p>
<p>Nội, thuận lợi di chuyển và giao thương.</p>
</div>
<div>
<h4 className="font-bold">4. LỄ TÂN XINH ĐẸP</h4>
<p>Nhân viên đại diện chuyên nghiệp và</p>
<p>xinh đẹp sẽ xử lý những công việc</p>
<p>trong phạm vi cho phép khi bạn vắng mặt.</p>
</div>
</div>
<div className="grid grid-cols-4 pt-4 mx-80 pl-4 gap-2">
<div>
<h4 className="font-bold">5. MIỄN PHÍ ĐIỆN - NƯỚC</h4>
<p>Không lo về hóa đơn điện - nước tăng</p>
<p>cao, không lo về sự cố bất thường khi</p>
<p>thuê văn phòng Hanoi Office.</p>
</div>
<div>
<h4 className="font-bold">6. INTERNET TỐC ĐỘ CAO</h4>
<p>Được sử dụng miễn phí Internet tốc độ</p>
<p>cao, không phải lo về giật - lag khiến</p>
<p>công việc bị gián đoạn.</p>
</div>
<div>
<h4 className="font-bold">7. MÁY IN - PHOTOCOPY - FAX</h4>
<p>Điện thoại - Máy in - Máy photocopy -</p>
<p>Máy fax: Đã được trang bị đầy đủ, đáp</p>
<p>ứng tất cả nhu cầu của doanh nghiệp.</p>
</div>
<div>
<h4 className="font-bold">8. NHẬN THƯ - BƯU PHẨM</h4>
<p>Lễ tân sẽ giúp bạn nhận bưu thư, bưu</p>
<p>phẩm và chuyển về địa chỉ bạn mong</p>
<p>muốn. Luôn bảo mật - Đúng hẹn.</p>
</div>
</div>
<div className="grid grid-cols-4 pt-4 mx-80 pl-4 gap-2 pb-12">
<div>
<h4 className="font-bold">9. AN NINH 24/7</h4>
<p>Hệ thống an ninh nghiêm ngặt với bảo</p>
<p>về và CCTV hoạt động liên tục 24/7</p>
<p>giúp bạn an tâm làm việc.</p>
</div>
<div>
<h4 className="font-bold">10. NHÂN VIÊN HỖ TRỢ</h4>
<p>Đội ngũ hỗ trợ tại Hanoi Office luôn sẵn</p>
<p>sàng hỗ trợ bạn, chúng tôi sẽ không</p>
<p>làm công việc bạn bị gián đoạn.</p>
</div>
<div>
<h4 className="font-bold">11. DỊCH VỤ SUPPORT</h4>
<p>Hanoi Office sẽ giải quyết toàn bộ các</p>
<p>vấn đề của doanh nghiệp: Kế toán,</p>
<p>Thuế, Marketing, Quản lý văn phòng...</p>
</div>
<div>
<h4 className="font-bold">12. TẠP VỤ</h4>
<p>Văn phòng của bạn sẽ luôn sạch sẽ và</p>
<p>được dọn dẹp theo khung giờ bạn yêu</p>
<p>cầu.</p>
</div>
</div>
</div>
<h1 className="font-bold text-2xl text-center pt-12">CHỌN GÓI THUÊ VĂN PHÒNG TRỌN GÓI PHÙ HỢP VÀ NHẬN BÁO
GIÁ</h1>
<div className="pt-16 mx-80">
<span>Hanoi Office cung cấp dịch vụ </span>
<span className="font-bold">cho thuê văn phòng hạng a tại Hà Nội </span>
<span>giúp doanh nghiệp tiết kiệm đến 80% chi phí. Bởi chúng tôi đã trang bị đầy đủ thiết bị văn phòng: Bàn</span>
</div>
<div className="mx-80">
<span>ghế, tủ tài liệu, máy in, máy photo, điện thoại bàn,… Bên cạnh đó, chỉ với </span>
<span className="font-bold">giá thuê văn phòng hạng a tại Hà Nội </span>
<span>Office cực rẻ. Bạn được sử dụng miễn phí điện, nước,</span>
</div>
<div className="mx-80">
<span>internet tốc độ cao,… Vệ sinh hàng ngày, bảo vệ 24/7,… Tất cả tiện ích dịch vụ đều trọn gói. Bạn chỉ việc xách laptop đến và làm việc, còn lại đã có Hanoi Office lo!</span>
</div>
<div className="pt-3">
<div className="mx-80">
<span>Hanoi Office linh động trong việc </span>
<a href=""><span className="font-bold text-blue-500">cho thuê văn phòng. </span></a>
<span>Giá thuê văn phòng tại Hà Nội có thể theo giờ, theo ngày, theo tuần tùy theo nhu cầu của khách hàng. Qúy khách vui</span>
</div>
<div className="mx-80">
<span>lòng liên hệ số </span>
<span className="font-bold">Hotline: 085 339 4567 hoặc 0904 388 909 </span>
<span>để nhận báo giá chi tiết.</span>
</div>
</div>
<div className="pt-3">
<div className="mx-80">
<span>Giá thuê Văn phòng trọn gói </span>
<span className="font-bold">chỉ từ 4.000.000 VNĐ/ tháng</span>
<span>, tùy từng khu vực lựa chọn, vui lòng </span>
<a href=""><span className="font-bold text-blue-500 text-xl">LIÊN HỆ</span></a>
</div>
</div>
<div className="grid grid-cols-4 mx-64 pt-16">
<div>
<img src="https://hanoioffice.vn/wp-content/uploads/2021/02/bao-gia-van-phong-tron-goi-1-3.jpg"
alt=""/>
</div>
<div>
<img src="https://hanoioffice.vn/wp-content/uploads/2021/02/bao-gia-van-phong-tron-goi-2-2.jpg"
alt=""/>
</div>
<div>
<img src="https://hanoioffice.vn/wp-content/uploads/2021/02/bao-gia-van-phong-tron-goi-3-3.jpg"
alt=""/>
</div>
<div>
<img src="https://hanoioffice.vn/wp-content/uploads/2021/02/bao-gia-van-phong-tron-goi-4-2.jpg"
alt=""/>
</div>
</div>
<div className="grid grid-cols-2 bg-blue-500 mt-12 py-3">
<div className="ml-64">
<p className="font-bold text-white pt-3">Bạn đang tìm thuê văn phòng tại các quận nội thành Hà Nội?
Hãy để Hanoi Office giúp bạn!</p>
</div>
<div className="ml-48">
<button
className="ml-24 bg-white font-bold text-black border border-white hover:bg-blue-500 hover:text-white py-2 px-16">ĐĂNG
KÝ NHẬN TƯ VẤN
</button>
</div>
</div>
<div className="mt-12">
<h2 className="font-bold text-center text-2xl">TRẢI NGHIỆM KHÔNG GIAN VĂN PHÒNG TRỌN GÓI CHO THUÊ</h2>
</div>
<div className="text-center mt-16">
Slide Ảnh
</div>
<div className="mt-12 bg-gray-200">
<div className="py-12">
<h3 className="font-bold text-center text-2xl">BẠN ĐANG CẦN TÌM THUÊ VĂN PHÒNG TRỌN GÓI Ở ĐÂU HÀ
NỘI?</h3>
<p className="text-xl text-center">Hanoi Office cho thuê văn phòng tại các quận nội thành: Ba Đình,
Hà Đông, Thanh Xuân, Cầu Giấy, Nam Từ Liêm.</p>
<p className="text-xl text-center">Hãy lựa chọn địa điểm thuận tiện nhất!</p>
<div className="pt-12 grid grid-cols-6 text-center px-6 mx-80">
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-ba-dinh.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Ba Đình</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-cau-giay.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Cầu Giấy</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-ha-dong.jpg"/>
</a>
<p className="font-bold text-xl">2 Cơ sở</p>
<p className="font-bold text-xl">Quận Hà Đông</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/12/quan-hoang-mai.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Hoàng Mai</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-nam-tu-liem.jpg"/>
</a>
<p className="font-bold text-xl">1 Cơ sở</p>
<p className="font-bold text-xl">Quận Nam Từ Liêm</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
<div className="">
<a href="">
<img className="w-40 h-52 mx-auto"
src="https://hanoioffice.vn/wp-content/uploads/2020/06/quan-thanh-xuan.jpg"/>
</a>
<p className="font-bold text-xl">2 Cơ sở</p>
<p className="font-bold text-xl">Quận Thanh Xuân</p>
<p className="font-bold text-xl">Hà Nội</p>
</div>
</div>
</div>
</div>
<div className="pt-8">
<h1 className="font-bold text-2xl pl-80 ml-6">TÌM HIỂU VỀ VĂN PHÒNG TRỌN GÓI</h1>
</div>
<div className="pt-8 mx-80 pl-6">
<span>Dịch vụ </span>
<span className="font-bold">“cho thuê văn phòng trọn gói” </span>
<span>được du nhập vào Việt Nam năm 2006, được bùng nổ và phát triển vào giai đoạn năm 2013 đến nay. Là một trong những đơn vị</span>
</div>
<div className="mx-80 pl-6">
<span>đầu tiên đưa văn phòng trọn gói về Việt Nam, Hanoi Office là một lá cờ đầu, một đơn vị tiên phong trong lĩnh vực cung cấp dịch vụ cho thuê văn phòng trọn gói tại Hà Nội.</span>
</div>
<div className="pt-4">
<div className="mx-80 pl-6">
<span>Đặc biệt, Hanoi Office còn cung cấp dịch vụ cho thuê văn phòng trọn gói giá rẻ linh hoạt theo giờ Hà Nội. Giá chỉ từ </span>
<span className="font-bold">7.000 VNĐ/giờ/người </span>
<span>bạn đã có một chỗ ngồi làm việc</span>
</div>
<div className="mx-80 pl-6">
<span>linh hoạt, chuyên nghiệp và hiện đại. Hãy đến với Hanoi Office, chúng tôi sẽ đem đến cho các bạn một văn phòng chuyên nghiệp – hiện đại – sang trọng.</span>
</div>
</div>
<div className="pt-4">
<div className="mx-80 pl-6">
<span>Với dịch vụ </span>
<a href=""><span className="font-bold text-blue-500">cho thuê văn phòng</span></a>
<span>này bạn hay doanh nghiệp của bạn chỉ cần tập trung toàn bộ sức mạnh và nguồn lực vào lĩnh vực kinh doanh chính của mình còn các vấn</span>
</div>
<div className="mx-80 pl-6">
<span>đề phụ trợ đã có Hanoi Office thay bạn chịu trách nhiệm. Bạn hoàn toàn chủ động trong công việc kinh doanh!</span>
</div>
</div>
<div className="pt-12">
<h3 className="font-bold text-2xl pl-80 ml-6">Những câu hỏi thường gặp về giải pháp Văn phòng trọn
gói:</h3>
</div>
<div className="pt-3 pl-80 ml-6">
<p>Văn phòng trọn gói là gì? Văn phòng chia sẻ là gì?</p>
<p>Lợi ích của văn phòng trọn gói là gì?</p>
<p>Share văn phòng làm việc có những ưu điểm gì?</p>
<p>Tính chất pháp lý của Văn Phòng Trọn Gói?</p>
<p>Doanh nghiệp nào phù hợp với Văn phòng trọn gói?</p>
<p>Hanoi Office cho thuê văn phòng trọn gói ở đâu Hà Nội?</p>
<p>Thuê văn phòng trọn gói tại Hanoi Office có phát sinh thêm chi phí không?</p>
</div>
<div className="grid grid-cols-2 bg-blue-500 mt-12 py-3">
<div className="ml-52">
<p className="font-bold text-white pt-6">Bạn đang tìm giải pháp cho thuê văn phòng trọn gói tại Hà Nội? Hãy để Hanoi Office giúp bạn!</p>
</div>
<div className="ml-48">
<button
className="ml-24 bg-white font-bold text-black border border-white hover:bg-blue-500 hover:text-white my-3 py-2 px-16">NHẬN BÁO GIÁ
</button>
</div>
</div>
</>
);
};
export default AllInclusiveOffice;<file_sep>import React from 'react';
import ServiceOther from '../../components/service/serviceOther';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Dịch vụ khác' ];
const Service = () => {
return (
<>
<LayoutLink title='Dịch vụ khác' listLink={ listLink }>
<ServiceOther />
</LayoutLink>
</>
);
};
export default Service;<file_sep>import React from 'react';
import EmployeeList from '../../components/report/contract';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Báo cáo hợp đồng' ];
const Employee = () => {
return (
<>
<LayoutLink title="Báo cáo hợp đồng" listLink={ listLink }>
<EmployeeList />
</LayoutLink>
</>
);
};
export default Employee;
<file_sep>import React, { useCallback, useEffect, useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { useQuery } from 'react-query';
import {
useRecoilValue,
// useRecoilState
} from 'recoil';
import { LIST_ORDER_PLACEHOLDER_DATA } from '../../../../fixedData/dataEmployee';
import { getListCustomer } from '../../../../service/customer/customerList/listCustomer';
import {
listCustomerColumnTableState,
listCustomerFilterParamsState,
listCustomerPageState,
listCustomerPageLimitState
} from '../../../../store/atoms/customer/customerList/listCustomer';
import TableV7 from '../../../common/table/TableV7';
import DetailInfo from '../badCustomer/Dialog/DetailInfo';
import DialogDetail from '../badCustomer/Dialog/DialogDetail';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
paper: {
width: '80%',
maxHeight: 1835,
},
}));
const BadCustomer = () => {
const classes = useStyles();
const columnTable = useRecoilValue(listCustomerColumnTableState);
const filterParams = useRecoilValue(listCustomerFilterParamsState);
const pageLimit = useRecoilValue(listCustomerPageLimitState);
const page = useRecoilValue(listCustomerPageState);
// console.log(columnTable);
const getData = useCallback(async (page, pageLimit) => {
const {
strSearch
} = filterParams;
return await getListCustomer().getList({
page, pageLimit, strSearch
});
}, [ pageLimit, filterParams, page.skip ]);
const { data, refetch } = useQuery(
[ 'PRODUCT_LIST_KEY_CUSTOMER', page.skip, JSON.stringify(filterParams) ],
() => getData(page.skip, pageLimit),
{
keepPreviousData: true, staleTime: 5000,
placeholderData: LIST_ORDER_PLACEHOLDER_DATA
}
);
useEffect(() => {
refetch();
}, [ pageLimit, filterParams, page ]);
const [ openDialog, setOpenDialog ] = useState({ open: false, id: null });
return (
<>
<TableV7 columns={ columnTable } datas={ data }
queryKey='queryKey' idDetai='detail'
keyId="id_employee" detailFunction={ getListCustomer().getDetail }
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
pageState={ listCustomerPageState }
pageLimitState={ listCustomerPageLimitState }
/>
{ openDialog.open &&
<DialogDetail
classes={ {
paper: classes.paper,
} }
id="ringtone-menu"
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
detail={ DetailInfo } />
}
</>
);
};
export default BadCustomer;<file_sep>import React from 'react';
import Species from '../../components/room/species';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Loại phòng' ];
const Room = () => {
return (
<>
<LayoutLink title="Loại phòng" listLink={ listLink }>
<Species />
</LayoutLink>
</>
);
};
export default Room;
<file_sep>import {axiosInstance} from '../../../config/axios';
import {getYearMonthDay} from '../../../helpers/helper';
export const getListAppointment = () => {
const role = 2;
const getList = async (value) => {
const {page = '1', pageLimit = '15'} = value;
const {data} = await axiosInstance.get('/book/listbookroom');
return dataProcesing(setDataNew(data, role), page, pageLimit);
};
const getDetail = async (id) => {
const {data} = await axiosInstance.get(`/book/roombookdetailsale?idOrderDetail=${id}`);
return setDataDetailNew(data);
};
const getListTime = async () => {
const {data} = await axiosInstance.get('/shift/find_all');
return setDataTime(data);
};
const getListService = async () => {
const {data} = await axiosInstance.get('/service/find_all');
return setServiceList(data);
};
return {getList, getDetail, getListTime, getListService};
};
const dataProcesing = (data, page, limit) => {
if (data.length > 0) {
const startLimit = (page - 1) * limit;
const endLimit = page * limit > data.length ? data.length : page * limit;
const dataNew = data.slice(startLimit, endLimit);
return {
data: dataNew,
meta: {
total_data: data.length,
total_dataNew: dataNew.length,
total_dataPage: data.length
}
};
} else {
return {
data: [],
meta: {
total_data: 0,
total_dataNew: 0,
total_dataPage: 0
}
};
}
};
const setDataNew = (data, role) => {
if (role !== 1) { // lễ tân
return data.filter(j => j.statusOrder || j.statusPay).map(i => {
return {
...i,
id: i.idOrderDetail,
detail: 'Xem',
createDate: getYearMonthDay(i.createDate, 'dd-MM-yyyy'),
statusOrder: i.statusOrder ? 'Đã tạo lịch' : 'Chưa tạo lịch',
statusPay: i.statusPay ? 'Chưa thanh toán' : ''
};
});
} else { // admin
return data.filter(j => !j.statusOrder && !j.statusPay).map(i => {
return {
...i,
id: i.idOrderDetail,
detail: 'Xem',
createDate: getYearMonthDay(i.createDate, 'dd-MM-yyyy'),
// statusOrder: i.statusOrder ? 'Chưa tạo lịch' : 'Đã tạo lịch',
// statusPay: i.statusPay ? 'Chưa thanh toán' : ''
};
});
}
};
const setDataDetailNew = (data) => {
if (data) {
return {
...data,
branch: [{...data.branch}]
};
} else {
return {};
}
};
const setDataTime = (data) => {
return data.map(i => ({
...i,
checked: false,
value: i.startTime + '-' + i.endTime
}));
};
const setServiceList = (data) => {
return data.map(i => ({
...i,
checked: false,
value: i.name,
}));
};<file_sep>import {axiosInstance} from '../../../config/axios';
import {getYearMonthDay} from '../../../helpers/helper';
export const getListBranchs = () => {
const getListArr = async () => {
const {data} = await axiosInstance.get('/branch/find_all');
return data;
};
const getList = async (value) => {
const {page = '1', pageLimit = '15'} = value;
const {data} = await axiosInstance.get('/branch/find_all');
return dataProcesing(setDataNew(data), page, pageLimit);
};
const getListArray = async () => {
const {data} = await axiosInstance.get('/branch/find_all');
return data;
};
const getDetail = async () => {
const {data} = await axiosInstance.get('/branchs-branchs-branchs');
return data;
};
return {getListArr, getList, getDetail, getListArray};
};
const dataProcesing = (data, page, limit) => {
if (data.length > 0) {
const startLimit = (page - 1) * limit;
const endLimit = page * limit > data.length ? data.length : page * limit;
const dataNew = data.slice(startLimit, endLimit);
return {
data: dataNew,
meta: {
total_data: data.length,
total_dataNew: dataNew.length,
total_dataPage: data.length
}
};
} else {
return {
data: [],
meta: {
total_data: 0
}
};
}
};
const setDataNew = (data) => {
return data.map(i => {
return {
...i,
detail: 'Xem',
createDate: getYearMonthDay(i.createDate, 'dd-MM-yyyy'),
statusBranch: i.status ? 'Hoạt động' : 'Ngừng hoạt động'
};
});
};<file_sep>import React from 'react';
import {
AllInbox,
ChevronRight,
CompareArrows, ContactPhone,
Devices,
EditLocationOutlined,
Email, FormatListBulleted,
FreeBreakfast, HeadsetMic,
ImportContacts, LocalCafe, MeetingRoomSharp, PermPhoneMsg,
Person, PersonAdd,
Security, Send,
Wifi
}
from '@material-ui/icons';
const VirtualOffice = () => {
return (
<>
<div className="bg-gray-500">
<div className="grid grid-cols-2 gap-2">
{/*<div> </div>*/}
<div className="bg-gray-600 mt-20 mb-24 mr-5 pl-2">
<h2 className="text-white text-center text-3xl font-bold">CHO THUÊ VĂN PHÒNG ẢO</h2>
<h4 className="text-white text-center border-b-2 border-fuchsia-600 font-medium ">Một địa chỉ kinh doanh chuyên nghiệp ở vị trí đắc địa tại Thủ đô Hà Nội</h4>
<div className="mt-4">
<p className="text-white text-center">Giải pháp Cho Thuê Văn Phòng Ảo sẽ giúp bạn tạo dựng hình ảnh chuyên nghiệp và hiện đại. Dịch vụ Văn Phòng Ảo của
Hanoi Office giải quyết toàn bộ nhu cầu của mọi doanh nghiệp và sẽ giúp do
anh nghiệp tận dụng được tối đa các cơ hội kinh doanh.</p>
</div>
<div className="mt-10">
<p className="text-red-700"><ChevronRight url=""/> Tìm hiểu Văn phòng ảo là gì?</p>
</div>
<div className="pb-20">
<p>Chọn một địa điểm</p>
<select className="pl-8 pr-96 py-2 mr-2" placeholder="Tất cả địa điểm">
<option value="">Tất cả địa điểm</option>
</select>
<button className="border border-blue-500 bg-blue-500 text-white pl-16 pr-20 py-1.5 max-w-max hover:bg-gray-600">TÌM</button>
</div>
</div>
<div className="bg-gradient-to-r from-yellow-400 via-red-500 to-pink-500">
<div>
<img src="" alt=""/>
</div>
</div>
</div>
</div>
<div className="bg-blue-700">
<div>
<p className="text-white pl-24 py-10 text-xl inline-block ">Bạn đang tìm thuê Văn Phòng Ảo Hà Nội và cần được tư vấn? Hãy để Hanoi Office giúp bạn!</p>
<button className="ml-32 border border-blue-500 bg-white text-black pl-14 pr-20 py-1.5 hover:bg-blue-700 inline-block">GỌI CHO HÀ NỘI OFFICE</button>
</div>
</div>
<div>
<h1 className="text-center text-2xl font-semibold ">TẠI SAO NÊN THUÊ VĂN PHÒNG ẢO TẠI HANOI OFFICE?</h1>
<p className="text-center ">Bạn muốn doanh nghiệp của mình ở vị trí đắc địa, thuận lợi và sang trọng?</p>
<p className="text-center">Bạn cũng muốn sử dụng trọn gói tiện ích văn phòng MIỄN PHÍ?</p>
<p className="text-center">Bạn muốn sử dụng Phòng họp, Phòng khách sang trọng? Hay bạn muốn một nhân viên đại diện doanh nghiệp, một điện thoại viên chuyên nghiệp?</p>
<p className="text-center">Giải pháp cho thuê văn phòng ảo có giúp được bạn không?</p>
</div>
<div >
<img className="mx-auto" src="https://hanoioffice.vn/wp-content/uploads/2020/09/cho-thue-van-phong-ao.jpg" alt=""/>
</div>
<div>
<h1 className="pl-24 text-xl border-b-2 font-bold text">HANOI OFFICE - CHO THUÊ VĂN PHÒNG ẢO FULL TIỆN ÍCH</h1>
</div>
{/*item slide*/}
<div className="grid grid-cols-4 gap-2 px-40 mx-20 pt-8">
<div className="">
<div className="text-center">
<span className="text-blue-500"> <EditLocationOutlined primary url=""/></span>
</div>
<p className="text-center font-bold">ĐỊA CHỈ KINH DOANH</p>
<p className="text-left">Cho thuê địa chỉ đăng ký kinh doanh Hà Nội sang trọng và hiện đại ở những vị trí đắc địa nhất tại Thủ đô.</p>
</div>
<div className="">
<div className="text-center">
<span className="text-blue-500"> <Email primary url=""/></span>
</div>
<p className="text-center font-bold">NHẬN THƯ & BƯU PHẨM</p>
<p className="text-left">Hanoi Office sẽ nhận thư tín và bưu phẩm thay bạn sau đó sẽ chuyển tiếp đến địa chỉ được yêu cầu đúng hẹn.</p>
</div>
<div className="">
<div className="text-center">
<span className="text-blue-500"> <Person /> </span>
</div>
<p className="text-center font-bold">NHÂN VIÊN ĐẠI DIỆN</p>
<p className="text-left">Nhân viên đại diện chuyên nghiệp và xinh đẹp sẽ xử lý những công việc trong phạm vi cho phép khi bạn vắng mặt.</p>
</div>
<div className="">
<div className="text-center">
{/* eslint-disable-next-line react/jsx-no-undef */}
<span className="text-blue-500"> <MeetingRoomSharp primary url=""/></span>
</div>
<p className="text-center font-bold">KHÔNG GIAN HIỆN ĐẠI</p>
<p className="text-left">Được sử dụng linh hoạt Phòng họp và Phòng khách sang trọng để tiếp khách trên toàn hệ thống của Hanoi Office.</p>
</div>
</div>
{/*items slide*/}
<div className="grid grid-cols-4 gap-2 px-40 mx-20 pt-8">
<div className="">
<div className="text-center">
<span className="text-blue-500"> <Devices primary url=""/></span>
</div>
<p className="text-center font-bold">THIẾT BỊ VĂN PHÒNG</p>
<p className="text-left">Được sử dụng các thiết bị văn phòng hiện đại: Máy in, fax, máy photocopy, điện thoại hệ thống…</p>
</div>
<div className="">
<div className="text-center">
<span className="text-blue-500"> <Security primary url=""/></span>
</div>
<p className="text-center font-bold">DỊCH VỤ AN NINH 24/7</p>
<p className="text-left">Dịch vụ an ninh 24/7, dịch vụ vệ sinh hàng ngày giúp bạn an tâm hơn để phát triển doanh nghiệp.</p>
</div>
<div className="">
<div className="text-center">
<span className="text-blue-500"> <Wifi /> </span>
</div>
<p className="text-center font-bold">INTERNET TỐC ĐỘ CAO</p>
<p className="text-left">Văn phòng ảo trang bị internet tốc độ cao tại toàn bộ không gian văn phòng Hanoi Office.</p>
</div>
<div className="">
<div className="text-center">
<span className="text-blue-500"> <FreeBreakfast primary url=""/></span>
</div>
<p className="text-center font-bold">TRÀ VÀ NƯỚC MIỄN PHÍ</p>
<p className="text-left">Hanoi Office cung cấp trà và nước miễn phí cho toàn bạn và quý khách hàng của bạn.</p>
</div>
</div>
<div>
<h1 className="pl-24 text-xl border-b-2 font-bold text text-center pt-8">KHÔNG CHỈ LÀ THUÊ VĂN PHÒNG ẢO MÀ BẠN CÒN THAM GIA VÀO CỘNG ĐỒNG DOANH NGHIỆP</h1>
</div>
<div className="grid grid-cols-2 gap-8 pt-8">
<div className="pl-24">
<img className="w-full h-full" src="https://hanoioffice.vn/wp-content/uploads/2020/10/van-phong-ao-cho-thue.jpg" alt=""/>
</div>
<div className="pt-8">
<h1 className="text-center font-bold">ĐĂNG KÝ TƯ VẤN VĂN PHÒNG ẢO</h1>
<div className="grid grid-cols-2 gap-2 ">
<div>
<span><p>Họ và Tên:*</p>
</span>
<input
className="shadow py-2 pr-32 text-gray-700"
id="username" type="text" />
<span><p>Số điện thoại:*</p>
</span>
<input
className="shadow py-2 pr-32 text-gray-700"
id="username" type="text" />
</div>
<div>
<span><p>Email:*</p>
</span>
<input
className="shadow py-2 pr-32 text-gray-700"
id="username" type="text" />
<span><p>Ngày hẹn:*</p>
</span>
<input
className="shadow py-2 pr-32 text-gray-700"
id="username" type="text" />
</div>
</div>
<div className="">
<span><p>Địa điểm bạn quan tâm:</p></span>
<input
className="shadow py-2 w-10/12 text-gray-700"
id="username" type="text" placeholder="<NAME>" />
</div>
<div className="">
<span><p>Yêu cầu chi tiết:</p></span>
<input
className="shadow py-2 w-10/12 text-gray-700"
id="username" type="text" placeholder="<NAME>" />
</div>
<div className="pt-4">
<button className="bg-blue-700 py-2 px-16 text-white">GỬI</button>
</div>
</div>
</div>
{/*// gói chọn phòng*/}
<div>
<div className="text-center font-extrabold text-2xl">
<h1>HÃY LỰA CHỌN GÓI VĂN PHÒNG ẢO CHO THUÊ PHÙ HỢP VỚI BẠN</h1>
</div>
<div className="grid grid-cols-3 gap-2 px-40 mx-20">
<div>
<img className="h-full w-96" src="https://hanoioffice.vn/wp-content/uploads/2021/06/VPA-ECONOMY.png" alt=""/>
</div>
<div>
<img className="h-full w-96" src="https://hanoioffice.vn/wp-content/uploads/2021/06/VPA-ECONOMY.png" alt=""/>
</div>
<div>
<img className="h-full w-96" src="https://hanoioffice.vn/wp-content/uploads/2021/06/VPA-ECONOMY.png" alt=""/>
</div>
</div>
</div>
{/*//tiện ích*/}
<div>
<div className="pl-32">
<h1 className="font-bold text-lg">12 TIỆN ÍCH KHI SỬ DỤNG DỊCH VỤ CHO THUÊ VĂN PHÒNG ẢO TẠI HANOI OFFICE:</h1>
</div>
<div className="grid grid-cols-2">
<div className="pl-32">
<p><CompareArrows className="text-blue-500"/> Sử dụng địa chỉ văn phòng giao dịch</p>
<p> <ImportContacts className="text-blue-500"/> Địa chỉ chi nhánh, văn phòng đại diện</p>
<p> <Person className="text-blue-500"/>Lễ tân, tiếp khách</p>
<p> <Email className="text-blue-500"/> Tiếp nhận thư/bưu phẩm</p>
<p> <Send className="text-blue-500"/> Chuyển tiếp thư/bưu phẩm</p>
<p> <AllInbox className="text-blue-500"/>Tư vấn đăng ký kinh doanh</p>
</div>
<div>
<div className="">
<p> <LocalCafe className="text-blue-500" /> Nước uống (café, trà, nước)</p>
<p> <PersonAdd className="text-blue-500" /> Nhân viên đại diện doanh nghiệp</p>
<p> <ContactPhone className="text-blue-500" /> Số fax chung</p>
<p> <PermPhoneMsg className="text-blue-500" /> Điện thoại viên trả lời cuộc gọi</p>
<p> <HeadsetMic className="text-blue-500" /> Tổng đài nội bộ và chuyển cuộc gọi</p>
<p> <FormatListBulleted className="text-blue-500" />Tư vấn đăng ký thuế ban đầu</p>
</div>
</div>
</div>
<div className="pl-32">
<h2 className="font-bold">GHI CHÚ:</h2>
<p>– Số lượng/thời lượng dịch vụ được quy định theo mỗi tháng, không có giá trị quy đổi hay cộng dồn cho các tháng sau.</p>
<p> – Giá trên chưa bao gồm VAT </p>
<p> – Tiện ích sử dụng trong giờ hành chính</p>
<p> – Sử dụng tiện ích trên tất cả các cơ sở của Hanoi Office</p>
<p> – Giá trên áp dụng cho Doanh nghiệp vốn Việt Nam, Doanh nghiệp vốn nước ngoài vui lòng ” Liên hệ“.</p>
<p> – Văn phòng phẩm phụ trội thanh toán theo thực tế sử dụng.</p>
<p> – Cước điện thoại thanh toán thực tế theo hóa đơn nhà cung cấp.</p>
<p> – Phí chuyển tiếp thư/ bưu phẩm theo yêu cầu sẽ thanh toán theo thực tế.</p>
<p> – Sử dụng phòng họp báo trước 24h; sử dụng khu vực tiếp khách chung báo trước 24h.</p>
</div>
</div>
<div className="bg-blue-700">
<div>
<p className="text-white pl-24 py-10 text-xl inline-block ">Bạn đang tìm thuê Văn Phòng Ảo Hà Nội và cần được tư vấn? Hãy để Hanoi Office giúp bạn!</p>
<button className="ml-32 border border-blue-500 bg-white text-black pl-14 pr-20 py-1.5 hover:bg-blue-700 inline-block">GỌI CHO HÀ NỘI OFFICE</button>
</div>
</div>
{/*titil khám phá văn phòng*/}
<div className="py-20">
<h1 className="text-center font-bold text-2xl">KHÁM PHÁ VĂN PHÒNG ẢO CHO THUÊ TẠI HANOI OFFICE</h1>
</div>
{/*ảnh */}
<div className="pb-8">
<img className="mx-auto" src="https://langmaster.edu.vn/public/files/editor-upload/images/3-chu-de-tieng-anh-van-phong-pho-bien-nhat-1.jpg" alt=""/>
</div>
{/* buttom*/}
<div className="bg-gray-200 px-40 pb-8">
<div >
<h1 className="pt-16 font-bold text-xl border-b-2">TÌM HIỂU VỀ VĂN PHÒNG ẢO</h1>
</div>
<div>
<p className="text-basic">Dịch Vụ Cho Thuê Văn Phòng Ảo tại sao lại có thể đáp ứng được tất cả mong muốn của các doanh nghiệp? Tại sao doanh nghiệp lại cần đến một Văn Phòng Ảo? 5 lý do sau đây sẽ giải thích những thắc mắc này:</p>
<div className="grid grid-cols-5 border-b-2">
<div>
<p className="text-sm">1.TIẾT KIỆM TỐI ĐA CHI PHÍ</p>
</div>
<div>
<p className="text-sm">2.TRỤ SỞ DOANH NGHIỆP</p>
</div>
<div>
<p className="text-sm">3.THÔNG TIN LIÊN LẠC</p>
</div>
<div>
<p className="text-sm">4.XÂY DỰNG HÌNH ẢNH</p>
</div>
<div>
<p className="text-sm">5.NẮM BẮT CƠ HỘI</p>
</div>
</div>
<div><p>
<div>
<p>Dịch vụ Văn Phòng Ảo tại Hà Nội tức là bạn có thể thuê địa chỉ mở công ty để có thể giảm thiểu chi phí vận hành một cách tối đa. Giải pháp Văn Phòng Ảo sẽ giúp doanh nghiệp, Start-up tối ưu được 80% chi phí vận hành, chi phí đầu tư ban đầu (chi phí cố định) và cả chi phí cơ hội. Tại sao vậy?
Sử dụng dịch vụ cho thuê Văn Phòng Ảo tại Hà Nội, bạn sẽ không phải đầu tư một khoản chi phí lớn để thuê văn phòng theo kiểu truyền thống.</p>
</div></p></div>
</div>
</div>
{/* tittle buttom*/}
<div className="px-40 py-8"> <h1 className="font-bold text-2xl">NHỮNG CÂU HỎI THƯỜNG GẶP VỀ GIẢI PHÁP CHO THUÊ VĂN PHÒNG ẢO</h1> </div>
<div className="px-40 py-8 bg-gray-200 text-2xl">
<div><h1>+ Văn phòng ảo là gì? </h1></div>
<div><h1>+ Văn phòng ảo là gì? </h1></div>
<div><h1>+ Văn phòng ảo là gì? </h1></div>
<div><h1>+ Văn phòng ảo là gì? </h1></div>
<div><h1>+ Văn phòng ảo là gì? </h1></div>
</div>
<div className="bg-blue-700">
<div>
<p className="text-white pl-24 py-10 text-xl inline-block ">Bạn đang tìm thuê Văn Phòng Ảo Hà Nội và cần được tư vấn? Hãy để Hanoi Office giúp bạn!</p>
<button className="ml-32 border border-blue-500 bg-white text-black pl-14 pr-20 py-1.5 hover:bg-blue-700 inline-block">GỌI CHO HÀ NỘI OFFICE</button>
</div>
</div>
</>
);
};
export default VirtualOffice;<file_sep>import React from 'react';
const Document = () => {
return (
<>
<h1>{ 'Viết code cho trang "Tài liệu" tại đây' }</h1>
</>
);
};
export default Document;<file_sep>import React, { useEffect, useState } from 'react';
import Dialog from '@material-ui/core/Dialog';
import Slide from '@material-ui/core/Slide';
import { useForm } from 'react-hook-form';
import {
useMutation,
useQuery
} from 'react-query';
import { useHistory, useLocation } from 'react-router-dom';
import { toast } from 'react-toastify';
import { useSetRecoilState } from 'recoil';
import ButtonBase from '../../components/base/button/ButtonBase';
import BaseInput from '../../components/base/input/BaseInput';
import SelectInput from '../../components/base/input/SelectInput';
import InputLabel from '../../components/common/InputLabel';
// import ToastMessage from '../../components/common/toast/ToastMessage';
import { setCookie } from '../../config/cookies';
import {
ACCESS_TOKEN,
AUTH_USER_INFO_KEY,
CURRENT_BRANCH,
USER_INFO
} from '../../constants/queryKey';
import { getAccount, getUserInfo } from '../../service/auth/login';
import { authUserInfoState } from '../../store/atoms/auth/user';
// import RoleLogin from './branch';
const Transitions = (props, ref) => {
return <Slide direction="up" ref={ ref } { ...props } />;
};
const Transition = React.forwardRef(Transitions);
const Login = () => {
useEffect(() => {
document.title = 'Đăng nhập';
localStorage.removeItem(CURRENT_BRANCH);
}, []);
const methods = useForm();
const { handleSubmit, register, formState: { errors }, } = methods;
const [ open, setOpen ] = useState('branch');
const [ role, setRole ] = useState(2);
console.log(role);
const setUserInfo = useSetRecoilState(authUserInfoState);
const [ dialogLogin, setDialogLogin ] = useState(true);
const location = useLocation();
const history = useHistory();
const loginMutation = useMutation(param => getAccount(param));
const [ isFetchUser, setIsFetchUser ] = React.useState(false);
const { data } = useQuery(AUTH_USER_INFO_KEY, () => getUserInfo(), { suspense: true, enabled: isFetchUser });
const { from } = location.state || { from: { pathname: '/' } };
const handleClose = () => {
};
const onSubmit = (value) => {
const makeValue = {
...value,
};
loginMutation.mutate(makeValue, {
onSuccess: async ({ meta: { message, status_code }, data }) => {
if (status_code === 1) {
return toast.error(message);
} else {
await setCookie(ACCESS_TOKEN, data?.token, data?.expires_in);// lưu trữ token trên cookie
await setCookie(USER_INFO, data ? data.user.id : null, data?.expires_in);// lưu trữ thông tin người dùng trên cookie
// await setCookie(CURRENT_BRANCH, data ? data.user.branch : null, data?.expires_in);// lưu trữ chi nhánh người dùng trên cookie
await setUserInfo(data?.user); // lưu trữ thông tin người dùng
await setIsFetchUser(true);
setDialogLogin(false);
toast.success(message);
}
// setOpen(false);
},
onError: (error) => {
toast.error('Đã xảy ra lỗi khi đăng nhập! ' + error);
}
});
};
useEffect(() => {
if (data !== undefined) {
// if (!dialogLogin) {
history.replace(from);// quay lại component Routers.jsx
// }
}
}, [ data ]);
const onHandleClick = (roles) => {
setRole(roles);
setOpen('login');
};
const dataArr = [ { id: 1, name: '<NAME>' }, { id: 2, name: '<NAME>' } ];
return (
<div>
<Dialog fullScreen open={ dialogLogin } onClose={ handleClose } TransitionComponent={ Transition }>
{/* <div className="bg-blue-200"> */ }
{ open === 'branch' &&
<div className="flex px-28 py-5 text-xl font-extrabold bg-blue-200">
<div>
<img src="" alt="" />
</div>
<div onClick={ () => onHandleClick(0) } className="cursor-pointer hover:text-gray-600 transition delay-100">Admin</div>
<div onClick={ () => onHandleClick(1) } className="cursor-pointer px-12 hover:text-gray-600 transition delay-100">Sale</div>
<div onClick={ () => onHandleClick(2) } className="cursor-pointer hover:text-gray-600 transition delay-100">Lễ tân</div>
</div>
}
{ open === 'login' &&
<div className="h-full flex justify-center flex-wrap content-center">
<div className="min-h-72 w-96 flex-wrap content-center shadow-2xl">
<div className="font-bold text-sm mt-4 flex justify-center">CS_OFFICE</div>
<div className="flex justify-center font-bold text-xl text-blue-800">ĐĂNG NHẬP</div>
<form onSubmit={ handleSubmit(onSubmit) } className="p-5 ">
<InputLabel label={ 'Chi nhánh :' }>
<SelectInput title="Chi nhánh"
dataArr={ dataArr } className="mr-2 -ml-2" classNameItem="w-full" />
</InputLabel>
<InputLabel label={ 'Tài khoản :' }>
<BaseInput
placeholder={ 'Nhập tài khoản' }
{ ...register('user', { required: true }) }
/>
<p className='text-red-500 mt-1'>{ errors.user && 'Tài khoản không được bỏ trống!' }</p>
</InputLabel>
<InputLabel label={ 'Mật khẩu :' } >
<BaseInput
name="pass"
type="password"
placeholder={ '<NAME>' }
{ ...register('pass', { required: true }) }
/>
<p className='text-red-500 mt-1'>{ errors.pass && 'Mâ<PASSWORD>ẩu không được bỏ trống!' }</p>
</InputLabel>
<ButtonBase title="Đăng nhập" type="submit" className="flex justify-center" />
</form>
</div>
</div>
}
{/* </div> */ }
</Dialog>
</div>
);
};
export default Login;<file_sep>import React from 'react';
import Species from '../../components/report/species';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Báo cáo loại phòng' ];
const Employee = () => {
return (
<>
<LayoutLink title="Báo cáo loại phòng" listLink={ listLink }>
<Species />
</LayoutLink>
</>
);
};
export default Employee;
<file_sep>// import React from 'react';
// import Rooms from '../../components/room';
// // import Filter from '../../components/room/filters';
// import LayoutLink from '../../layoutLink';
// const Room = () => {
// return (
// <>
// <LayoutLink title='Phòng'>
// <Rooms />
// </LayoutLink>
// </>
// );
// };
// export default Room;<file_sep>import React, { useState } from 'react';
import {
listContractFilterParamsState
} from '../../../../../store/atoms/contract/contractList/listContract';
import ButtonBase from '../../../../base/button/ButtonBase';
import CardBranch from '../../../../common/filter/CardBranch';
import SelectInput from '../../../../common/filter/CardPosition';
import CardSex from '../../../../common/filter/CardSex';
// import Dialog from '../../../../common/Dialog/Dialog';
import DialogAdd from '../DialogAdd/DialogAdd';
import SearchBar from '../filters/SearchBar';
const Filters = () => {
const [ openAdd, setOpenAdd ] = useState(false);
return (
<>
<div className="rounded w-full bg-gray-100 my-2">
<div className="m-2">
<div className='flex gap-4'>
<SearchBar />
< CardBranch filterParams={ listContractFilterParamsState } />
<SelectInput filterParams={ listContractFilterParamsState } />
</div>
<div>
<CardSex filterParams={ listContractFilterParamsState } />
</div>
<div className="flex justify-end ">
<ButtonBase title={ 'Thêm nhân viên' } color={ 'primary' } className='m-3' onClick={ () => setOpenAdd(!openAdd) } />
{
<DialogAdd setOpenDialog={ setOpenAdd } openDialog={ openAdd } />
}
</div>
</div>
</div>
</>
);
};
export default Filters;<file_sep>export const LIST_ORDER_PLACEHOLDER_DATA = {
'data': [
{
'id': 'Đang tải',
'detail': 'Đang tải',
'id_employee': 'Đang tải',
'image': 'Đang tải',
'name': '<NAME>',
'branch': 'Đang tải',
'position': 'Đang tải',
'sex': 'Đang tải',
'birthday': 'Đang tải',
'phone': 'Đang tải',
'email': 'Đang tải',
'address': 'Đang tải',
'home_town': 'Đang tải',
'permanent_residence': 'Đang tải',
'note': null
},
],
'meta': {
'pagination': {
'total': 1,
'count': 1,
'per_page': 1,
'current_page': 1,
'total_pages': 1,
},
'summation': {
'total_order': 0,
'order_payment': 0
},
'status_code': 0,
'message': 'Successfully'
},
'recordsTotal': 1,
'recordsFiltered': 1,
};<file_sep>import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import PropTypes from 'prop-types';
const CheckboxSingle = ({ checked, color, handleChange, label, labelPlacement, ...props }) => {
return (
<>
<FormControlLabel
control={ <Checkbox checked={ checked } { ...props } onChange={ handleChange } color={ color }
inputProps={ { 'aria-label': 'primary checkbox' } } /> } labelPlacement={ labelPlacement }
label={ label }>
</FormControlLabel>
</>
);
};
CheckboxSingle.propTypes = {
checked: PropTypes.bool,
handleChange: PropTypes.func,
color: PropTypes.string,
name: PropTypes.string,
label: PropTypes.string,
labelPlacement: PropTypes.string // vị trí của chữ so với checkbox
};
CheckboxSingle.defaultProps = {
checked: false,
color: 'primary',
name: '',
label: '',
labelPlacement: 'end',
};
export default CheckboxSingle;
//top, start, button, end<file_sep>import React from 'react';
import {useRecoilValue} from 'recoil';
import {orderBookFilterParamsContinuous} from '../../../../store/actom/orderBook/orderBook';
import PaymentDetail from './paymentDetail';
const PaymentIntermittent = () => {
const filterData = useRecoilValue(orderBookFilterParamsContinuous);
const data = filterData.schdules;
return (
<>
<div className='mb-8 mt-4'>
{
data.map((item, index) => {
return (
<PaymentDetail key={ index } dataItem={ item } index={ index } data={ data }/>
);
})
}
</div>
</>
);
};
export default PaymentIntermittent;<file_sep>import React, { useState } from 'react';
import ButtonBase from '../../../../base/button/ButtonBase';
import DialogAdd from '../Dialog/DialogAdd';
import SearchBar from '../Filters/SearchBar';
const Filters = () => {
const [ openAdd, setOpenAdd ] = useState(false);
return (
<>
<div className="rounded w-full bg-gray-100 my-2">
<div className="m-2">
<div className='flex grid grid-cols-3 gap-4'>
<SearchBar />
</div>
<div className="flex justify-end ">
<ButtonBase title={ 'Thêm dịch vụ khác' } color={ 'primary' } className='m-3' onClick={ () => setOpenAdd(!openAdd) } />
{
<DialogAdd setOpenDialog={ setOpenAdd } openDialog={ openAdd } />
}
</div>
</div>
</div>
</>
);
};
export default Filters;<file_sep>import React from 'react';
import SetUpABusiness from '../../component/serviceOrther/SetUpABusiness';
const ComponentCenter = () => {
return (
<>
<SetUpABusiness />
</>
);
};
export default ComponentCenter;<file_sep>import { library } from '@fortawesome/fontawesome-svg-core';
import { fab } from '@fortawesome/free-brands-svg-icons';
import { far, faCommentDots } from '@fortawesome/free-regular-svg-icons';
import { fas, faSignOutAlt } from '@fortawesome/free-solid-svg-icons';
import {
faBars,
faChartBar,
faChevronDown,
faChevronUp,
faCube,
faDollarSign,
faExchangeAlt,
faEye,
faFileExport,
faFileImport,
faPlus,
faSearch,
faShoppingBasket,
faSortDown,
faUserFriends,
faUserTie,
faCaretDown,
faInbox,
faFileInvoice,
faTags,
faClipboardCheck,
faTh,
faFileInvoiceDollar,
faPlusCircle,
faUserCircle,
faCog,
faInfoCircle,
faMapMarkerAlt,
faDownload,
faCheckSquare,
faBarcode,
faClone,
faLock,
faTrashAlt,
faEllipsisV,
faSave,
faBan,
faFilter,
faPen,
faSort,
faCalendarAlt,
faMinusCircle,
faTimes
} from '@fortawesome/free-solid-svg-icons';
library.add(
fab,
fas,
far,
faEye,
faCube,
faExchangeAlt,
faUserTie,
faUserFriends,
faDollarSign,
faChartBar,
faShoppingBasket,
faChevronUp,
faChevronDown,
faSearch,
faSortDown,
faPlus,
faFileImport,
faFileExport,
faBars,
faCaretDown,
faInbox,
faFileInvoice,
faTags,
faClipboardCheck,
faTh,
faFileInvoiceDollar,
faPlusCircle,
faUserCircle,
faSignOutAlt,
faCog,
faInfoCircle,
faMapMarkerAlt,
faDownload,
faCommentDots,
faCheckSquare,
faBarcode,
faClone,
faLock,
faTrashAlt,
faEllipsisV,
faSave,
faBan,
faFilter,
faPen,
faSort,
faCalendarAlt,
faMinusCircle,
faTimes
);
<file_sep>import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { func, string, number, oneOfType } from 'prop-types';
const BaseIconButton = React.forwardRef((
{
onClick,
icon,
size = 'lg',
className
}, ref, ...props) => {
return (
<>
<div { ...props } ref={ ref } onClick={ onClick } className={ `icon__button ${className}` }>
<FontAwesomeIcon icon={ icon } size={ size } color={ '#666' } fixedWidth />
</div>
</>
);
});
BaseIconButton.propTypes = {
onClick: func,
icon: string,
className: string,
size: oneOfType([ number, string ]),
};
export default BaseIconButton;
<file_sep>import {atom} from 'recoil';
const today = new Date();
export const typeRoomFilterParamsState = atom({
key: 'typeRoomFilterParamsState',
default: {
idType: '',
nameType: '',
debitSearch: 99,
from_date: today,
to_date: today,
}
});
export const typeRoomPageLimitState = atom({
key: 'typeRoomPageLimitState',
default: 15
});
export const typeRoomPageState = atom({
key: 'typeRoomPageState',
default: 1
});
export const typeRoomColumnTableState = atom({
key: 'typeRoomColumnTableState',
default: [
{
field: 'detail',
headerName: 'Chi tiết',
width: 80,
sortable: false,
description: 'Chi tiết',
cellClassName: 'cursor-pointer'
},
{
field: 'codeTypeRoom',
headerName: 'Mã loại phòng',
width: 200,
sortable: false,
description: 'Mã loại phòng'
},
{field: 'name', headerName: 'Tên loại phòng', width: 300, sortable: false, description: 'Tên loại phòng'},
{
field: 'priceTypeRoom',
headerName: 'Giá loại phòng',
width: 150,
sortable: false,
description: 'Giá loại phòng'
},
{
field: 'createDate',
headerName: 'Ngày tạo',
width: 250,
sortable: false,
description: 'Thời gian bắt đầu sử dụng loại phòng'
},
// { field: 'date_stop', headerName: 'Thời gian ngừng sử dụng', width: 200, sortable: false, description: 'Thời gian ngừng sử dụng loại phòng' },
{field: 'status', headerName: 'Đang sử dụng', width: 200, sortable: false, description: 'Đang sử dụng'},
{field: 'description', headerName: 'Ghi chú', width: 400, sortable: false, description: 'Ghi chú'},
]
});<file_sep>export const data = [
{
'id': '2021',
'color': 'hsl(174, 70%, 50%)',
'data': [
{
'x': '1',
'y': 151
},
{
'x': '2',
'y': 242
},
{
'x': '3',
'y': 238
},
{
'x': '4',
'y': 224
},
{
'x': '5',
'y': 136
},
{
'x': '6',
'y': 24
},
{
'x': '7',
'y': 101
},
{
'x': '8',
'y': 13
},
{
'x': '9',
'y': 238
},
{
'x': '10',
'y': 3
},
{
'x': '11',
'y': 146
},
{
'x': '12',
'y': 228
}
]
},
{
'id': '2020',
'color': 'hsl(230, 70%, 50%)',
'data': [
{
'x': '1',
'y': 78
},
{
'x': '2',
'y': 231
},
{
'x': '3',
'y': 284
},
{
'x': '4',
'y': 80
},
{
'x': '5',
'y': 54
},
{
'x': '6',
'y': 53
},
{
'x': '7',
'y': 147
},
{
'x': '8',
'y': 60
},
{
'x': '9',
'y': 22
},
{
'x': '10',
'y': 213
},
{
'x': '11',
'y': 145
},
{
'x': '12',
'y': 101
}
]
}
];
export const data1 = [
{
'country': '1',
'hot dog': 53,
'hot dogColor': 'hsl(286, 70%, 50%)',
'burger': 198,
'burgerColor': 'hsl(90, 70%, 50%)',
'sandwich': 149,
'sandwichColor': 'hsl(138, 70%, 50%)',
'kebab': 120,
'kebabColor': 'hsl(181, 70%, 50%)',
'fries': 82,
'friesColor': 'hsl(97, 70%, 50%)',
'donut': 4,
'donutColor': 'hsl(165, 70%, 50%)'
},
{
'country': '2',
'hot dog': 56,
'hot dogColor': 'hsl(113, 70%, 50%)',
'burger': 146,
'burgerColor': 'hsl(6, 70%, 50%)',
'sandwich': 170,
'sandwichColor': 'hsl(17, 70%, 50%)',
'kebab': 141,
'kebabColor': 'hsl(229, 70%, 50%)',
'fries': 74,
'friesColor': 'hsl(51, 70%, 50%)',
'donut': 89,
'donutColor': 'hsl(193, 70%, 50%)'
},
{
'country': '3',
'hot dog': 56,
'hot dogColor': 'hsl(21, 70%, 50%)',
'burger': 139,
'burgerColor': 'hsl(93, 70%, 50%)',
'sandwich': 76,
'sandwichColor': 'hsl(346, 70%, 50%)',
'kebab': 196,
'kebabColor': 'hsl(153, 70%, 50%)',
'fries': 185,
'friesColor': 'hsl(154, 70%, 50%)',
'donut': 116,
'donutColor': 'hsl(320, 70%, 50%)'
},
{
'country': '4',
'hot dog': 135,
'hot dogColor': 'hsl(68, 70%, 50%)',
'burger': 89,
'burgerColor': 'hsl(47, 70%, 50%)',
'sandwich': 6,
'sandwichColor': 'hsl(117, 70%, 50%)',
'kebab': 30,
'kebabColor': 'hsl(223, 70%, 50%)',
'fries': 76,
'friesColor': 'hsl(287, 70%, 50%)',
'donut': 45,
'donutColor': 'hsl(199, 70%, 50%)'
},
{
'country': '5',
'hot dog': 9,
'hot dogColor': 'hsl(181, 70%, 50%)',
'burger': 129,
'burgerColor': 'hsl(352, 70%, 50%)',
'sandwich': 75,
'sandwichColor': 'hsl(20, 70%, 50%)',
'kebab': 182,
'kebabColor': 'hsl(41, 70%, 50%)',
'fries': 33,
'friesColor': 'hsl(306, 70%, 50%)',
'donut': 12,
'donutColor': 'hsl(269, 70%, 50%)'
},
{
'country': '6',
'hot dog': 160,
'hot dogColor': 'hsl(125, 70%, 50%)',
'burger': 165,
'burgerColor': 'hsl(23, 70%, 50%)',
'sandwich': 164,
'sandwichColor': 'hsl(60, 70%, 50%)',
'kebab': 41,
'kebabColor': 'hsl(135, 70%, 50%)',
'fries': 81,
'friesColor': 'hsl(301, 70%, 50%)',
'donut': 17,
'donutColor': 'hsl(85, 70%, 50%)'
}
];
export const data2 = [
{
'id': 'go',
'label': 'go',
'value': 385,
'color': 'hsl(88, 70%, 50%)'
},
{
'id': 'erlang',
'label': 'erlang',
'value': 324,
'color': 'hsl(360, 70%, 50%)'
},
{
'id': 'stylus',
'label': 'stylus',
'value': 389,
'color': 'hsl(335, 70%, 50%)'
},
{
'id': 'javascript',
'label': 'javascript',
'value': 106,
'color': 'hsl(343, 70%, 50%)'
},
{
'id': 'lisp',
'label': 'lisp',
'value': 349,
'color': 'hsl(36, 70%, 50%)'
}
];
export const data3 = [
{
'country': '1',
'hot dog': 53,
'hot dogColor': 'hsl(286, 70%, 50%)',
'burger': 198,
'burgerColor': 'hsl(90, 70%, 50%)'
},
{
'country': '2',
'hot dog': 56,
'hot dogColor': 'hsl(113, 70%, 50%)',
'burger': 146,
'burgerColor': 'hsl(6, 70%, 50%)'
},
{
'country': '3',
'hot dog': 56,
'hot dogColor': 'hsl(21, 70%, 50%)',
'burger': 139,
'burgerColor': 'hsl(93, 70%, 50%)'
},
{
'country': '4',
'hot dog': 135,
'hot dogColor': 'hsl(68, 70%, 50%)',
'burger': 89,
'burgerColor': 'hsl(47, 70%, 50%)'
},
{
'country': '5',
'hot dog': 9,
'hot dogColor': 'hsl(181, 70%, 50%)',
'burger': 129,
'burgerColor': 'hsl(352, 70%, 50%)'
},
{
'country': '6',
'hot dog': 160,
'hot dogColor': 'hsl(125, 70%, 50%)',
'burger': 165,
'burgerColor': 'hsl(23, 70%, 50%)'
}
];<file_sep>import React from 'react';
import Reserve from '../../components/contract/reserve';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Bảo lưu hợp đồng' ];
const Contract = () => {
return (
<>
<LayoutLink title="Bảo lưu hợp đồng" listLink={ listLink }>
<Reserve />
</LayoutLink>
</>
);
};
export default Contract;
<file_sep>import React from 'react';
import Button from '@material-ui/core/Button';
import PropTypes from 'prop-types';
const ButtonBase = ({ variant, color, onClick, startIcon, title, className, ...props }) => {
return (
<>
<div className={ className }>
<Button variant={ variant }
color={ color }
onClick={ onClick }
startIcon={ startIcon } { ...props }>
{ title }
</Button>
</div>
</>
);
};
ButtonBase.propTypes = {
variant: PropTypes.string,
color: PropTypes.string,
onClick: PropTypes.func,
startIcon: PropTypes.object,
title: PropTypes.string,
className: PropTypes.string
};
ButtonBase.defaultProps = {
variant: 'contained',// chọn màu nền
color: 'primary',// chọn màu nền cho chữ
// disableElevation (chọn bóng )
// disabled (vô hiệu hóa)
};
export default ButtonBase;
// contained: màu nền
// outlined: chỉ có viền<file_sep>import React, { useState } from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
// import FormLabel from '@material-ui/core/FormLabel';
// import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import PropTypes from 'prop-types';
// import { useSetRecoilState } from 'recoil';
import FramesFilter from '../framesFilter';
import { StyledRadio } from '../radio/tabRadio';
const RadioSex = ({ dataRadio, values, labelPlacement }) => {
// const setParams = useSetRecoilState(filterParams);
const [ value, setValue ] = useState(values);
const handleChange = (event) => {
setValue(event.target.value);
};
// React.useEffect(() => {
// setParams(data => {
// return {
// ...data,
// [ name ]: value
// };
// });
// }, [ value ]);
return (
<>
<FramesFilter event={ <FormControl component="fieldset">
<RadioGroup aria-label="gender" name="gender1" value={ value } onChange={ handleChange }>
{
dataRadio.map((item, index) => {
return (
<FormControlLabel key={ index } value={ item.value } control={ <StyledRadio /> } label={ item.label }
labelPlacement={ labelPlacement } />
);
})
}
</RadioGroup>
</FormControl> } title={ 'Giới tính' } />
</>
);
};
RadioSex.propTypes = {
dataRadio: PropTypes.array,
values: PropTypes.number,
name: PropTypes.string,
filterParams: PropTypes.object,
labelPlacement: PropTypes.string
};
RadioSex.defaultProps = {
dataRadio: [
{ id: 1, label: 'Tất cả', value: 0 },
{ id: 2, label: 'Nam', value: 1 },
{ id: 3, label: 'Nữ', value: 2 },
],
values: 0,
labelPlacement: 'end'
};
export default RadioSex;
<file_sep>import React from 'react';
import TextField from '@material-ui/core/TextField';
import PropTypes from 'prop-types';
const TextFieldInput = React.forwardRef((
{ className = 'w-full',
label,
type = 'text',
name,
error = '',
value,
onChange,
...props }
, ref) => {
return (
<>
<TextField
{ ...props }
ref={ ref }
id={ name }
label={ label }
className={ className }
helperText={ error }
type={ type }
error={ error !== null }
value={ value }
onChange={ onChange }
/>
</>
);
});
TextFieldInput.propTypes = {
className: PropTypes.string,
label: PropTypes.string,
helperText: PropTypes.string,
type: PropTypes.string,
name: PropTypes.string,
error: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
onChange: PropTypes.func,
};
export default React.memo(TextFieldInput);<file_sep>import React, { useState } from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
// import FormLabel from '@material-ui/core/FormLabel';
// import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import PropTypes from 'prop-types';
// import { useSetRecoilState } from 'recoil';
import FramesFilter from '../framesFilter';
import { StyledRadio } from '../radio/tabRadio';
const RadioGroupForm = ({ dataRadio, values, disabled, labelPlacement }) => {
// const setParams = useSetRecoilState(filterParams);
const [ value, setValue ] = useState(values);
const handleChange = (event) => {
setValue(event.target.value);
};
// React.useEffect(() => {
// setParams(data => {
// return {
// ...data,
// [ name ]: value
// };
// });
// }, [ value ]);
return (
<>
<FramesFilter event={ <FormControl component="fieldset">
{/* <FormLabel component="legend">{ title }</FormLabel> */ }
<RadioGroup aria-label="gender" name="gender1" value={ value } onChange={ handleChange }>
{
dataRadio.map((item, index) => {
return (
<FormControlLabel key={ index } value={ item.value } control={ <StyledRadio /> } label={ item.label }
disabled={ disabled && (item.disabled !== null && item.disabled !== undefined) ? item.disabled : false }
labelPlacement={ labelPlacement } />
);
})
}
</RadioGroup>
</FormControl> } title={ 'Chi nhánh' } />
</>
);
};
RadioGroupForm.propTypes = {
dataRadio: PropTypes.array,
title: PropTypes.string,
values: PropTypes.number,
name: PropTypes.string,
filterParams: PropTypes.object,
disabled: PropTypes.bool,
labelPlacement: PropTypes.string
};
RadioGroupForm.defaultProps = {
dataRadio: [
{ id: 1, label: 'Giá trị 1', value: 0, disabled: false },
{ id: 2, label: 'Giá trị 2', value: 1, disabled: false },
],
values: 0,
disabled: false,
labelPlacement: 'end'
};
export default RadioGroupForm;
<file_sep>import React from 'react';
import Transfer from '../../components/contract/transfer';
import LayoutLink from '../../layoutLink';
const listLink = [ 'Chuyển nhượng hợp đồng' ];
const Contract = () => {
return (
<>
<LayoutLink title="Chuyển nhượng hợp đồng" listLink={ listLink }>
<Transfer />
</LayoutLink>
</>
);
};
export default Contract;
<file_sep>import React from 'react';
import Button from '@material-ui/core/Button';
import {
AddLocation, Phone, Email, Twitter,
Pinterest, Facebook, Instagram, YouTube
} from '@material-ui/icons';
import { useForm, Controller } from 'react-hook-form';
import { NavLink } from 'react-router-dom';
import TextFieldInput from '../common/TextFieldInput';
const Footer = () => {
const defaultValues = {
user_customer: '',
pass_customer: ''
};
const methods = useForm({ defaultValues });
const { formState: { errors }, control } = methods;
const onSubmitForm = (value) => {
console.log(value);
};
return (
<>
<div className="mt-8">
<div className="bg-black text-white py-28">
<div className="grid grid-cols-5 gap-8">
<div></div>
<div className="gap-4">
<img src="https://hanoioffice.vn/wp-content/uploads/2020/06/logo_white.png" alt="Hà Nội Office" style={ { height: '18%' } } />
<p className="text-sm text-gray-400 py-4 text-justify ">
Hanoi Office chuyên cung cấp các giải pháp cho thuê văn phòng chuyên nghiệp – hiện đại,
phù hợp với mọi hoạt động kinh doanh của các doanh nghiệp. Đến với Hanoi Office,
bạn sẽ được tận hưởng dịch vụ cho thuê hoàn hảo trong không gian sang trọng.</p>
<NavLink to={ '/gioi-thieu' } >
<span className="text-sm text-gray-200 hover:text-blue-700 cursor-pointer">{ 'Chi tiết >' }</span>
</NavLink>
</div>
<div>
<h3>Liên hệ</h3>
<div className="text-sm text-gray-400 pt-8 text-justify">
<AddLocation fontSize="small" />
<span>Trụ sở chính: Tầng 8 tòa nhà Sannam, 78 Duy Tân, Dịch Vọng Hậu, Cầu Giấy, Hà Nội</span>
</div>
<div className="text-sm text-gray-400 pt-3 text-justify">
< Phone fontSize='small' />
<span>Gọi Ngay (+84) 853 39 4567</span>
</div>
<div className="text-sm text-gray-400 pt-3 pb-4 text-justify">
<Email fontSize='small' />
<span><EMAIL></span>
</div>
<NavLink to={ '/lien-he ' } >
<span className="text-sm text-gray-200 hover:text-blue-700 cursor-pointer">{ 'Liên hệ >' }</span>
</NavLink>
</div>
<div>
<form >
<h2>ĐĂ<NAME></h2>
<div className="flex gap-4">
<Controller
name={ 'email' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Email" className="w-full bg-white"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.email?.type === 'required' ? 'Địa chỉ email không được bỏ trống!' : null } /> } />
<Controller
name={ 'phone' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Số điện thoại" className="w-full bg-white"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.phone?.type === 'required' ? 'Số điện thoại không được bỏ trống!' : null } /> } />
</div>
<div className="mt-4">
<Button color="primary" variant="contained" onClick={ () => methods.handleSubmit(onSubmitForm)() } className="w-full">
Đăng ký
</Button>
</div>
<div className="mt-12">
<p className="">Đồng hành cùng Hanoi Office tại:</p>
<div className="pt-1">
<YouTube className="text-gray-500 hover:text-blue-500 mx-1" fontSize='small' />
<Twitter className="text-gray-500 hover:text-blue-500 mx-1" fontSize='small' />
<Pinterest className="text-gray-500 hover:text-blue-500 mx-1" fontSize='small' />
<Facebook className="text-gray-500 hover:text-blue-500 mx-1" fontSize='small' />
<Instagram className="text-gray-500 hover:text-blue-500 mx-1" fontSize='small' />
</div>
</div>
</form>
</div>
<div></div>
</div>
</div>
<div className="bg-gray-900 text-white">
<p className="text-center py-4">Copyright © Hanoi Office 2020 All Rights Reserved</p>
</div>
</div>
</>
);
};
export default Footer;<file_sep>import React, { useCallback, useEffect, useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { useQuery } from 'react-query';
import {
useRecoilValue,
// useRecoilState
} from 'recoil';
import { LIST_ORDER_PLACEHOLDER_DATA } from '../../../../fixedData/dataEmployee';
import { getListRoom } from '../../../../service/room/listRoom/listRoom';
import {
listRoomColumnTableState,
listRoomFilterParamsState,
listRoomPageState,
listRoomPageLimitState
} from '../../../../store/atoms/room/listRoom/listRoom';
import TableV7 from '../../../common/table/TableV7';
import DetailInfo from '../listRoom/Dialog/DetailInfo';
import DialogDetail from '../listRoom/Dialog/DialogDetail';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
paper: {
width: '80%',
maxHeight: 1835,
},
}));
const BadCustomer = () => {
const classes = useStyles();
const columnTable = useRecoilValue(listRoomColumnTableState);
const filterParams = useRecoilValue(listRoomFilterParamsState);
const pageLimit = useRecoilValue(listRoomPageLimitState);
const page = useRecoilValue(listRoomPageState);
const getData = useCallback(async (page, pageLimit) => {
const {
strSearch,
nameRoom, numberPeople, branchRoom, kindOfRoom
} = filterParams;
return await getListRoom().getList1({
page, pageLimit, strSearch, nameRoom, numberPeople, branchRoom, kindOfRoom
});
}, [ pageLimit, filterParams, page ]);
const { data, refetch } = useQuery(
[ 'PRODUCT_LIST_KEY_ROOM', page, JSON.stringify(filterParams) ],
() => getData(page, pageLimit),
{
keepPreviousData: true, staleTime: 5000,
placeholderData: LIST_ORDER_PLACEHOLDER_DATA
}
);
useEffect(() => {
refetch();
}, [ pageLimit, filterParams, page ]);
const [ openDialog, setOpenDialog ] = useState({ open: false, id: null });
return (
<>
<TableV7 columns={ columnTable } datas={ data }
queryKey='queryKey' idDetai='detail'
keyId="id_employee" detailFunction={ getListRoom().getDetail }
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
pageState={ listRoomPageState }
pageLimitState={ listRoomPageLimitState } />
{ openDialog.open &&
<DialogDetail
classes={ {
paper: classes.paper,
} }
id="ringtone-menu"
data={ data }
openDialog={ openDialog }
setOpenDialog={ setOpenDialog }
detail={ DetailInfo } />
}
</>
);
};
export default BadCustomer;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { useFormContext, Controller } from 'react-hook-form';
import DateSingle from '../../../../base/dateTime/DateSingle';
import ImageUpdate from '../../../../common/ImageUpdate';
import Sex from '../../../../common/Sex';
import TextFieldInput from '../../../../common/TextFieldInput';
import TextPassword from '../../../../common/TextPassword';
const DetailInfo = ({ form, setForm, isAdd = true }) => {
const methods = useFormContext();
const { formState: { errors }, control } = methods;
return (
<>
<div>
<div className="grid grid-cols-3 gap-4">
<div >
<ImageUpdate />
</div>
<div className='col-span-2'>
<h3 className="text-blue-500">Thông tin cá nhân</h3>
<div className=" grid grid-cols-2 gap-4">
<Controller
name={ 'code_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Mã khách hàng" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.code_customer?.type === 'required' ? 'Mã khách hàng không được bỏ trống!' : null } /> } />
<Controller
name={ 'fist_name' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Họ khách hàng" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.fist_name?.type === 'required' ? 'Họ khách hàng không được bỏ trống!' : null } /> } />
<Controller
name={ 'last_name' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="<NAME>" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.last_name?.type === 'required' ? 'Tên <NAME>̀ng không được bỏ trống!' : null } /> } />
<Controller
name={ 'user_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="<NAME>" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.user_customer?.type === 'required' ? 'Tài khoản khách hàng không được bỏ trống!' : null } /> } />
{
isAdd &&
<Controller
name={ 'pass_employee' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextPassword className="w-full" multiline rows={ 3 } id="standard-multiline-static"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.pass_employee?.type === 'required' ? 'Mật khẩu không được bỏ trống!' : null } /> } />
}
<div className="mt-3">
<Controller
name={ 'sex' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<Sex
onChange={ e => {
onChange(e.target.value);
} }
value={ value } /> } />
</div>
<div className="flex items-end w-full">
<DateSingle title="Ngày sinh" classNameTitle="w-1/4"
onChange={ setForm }
value={ form } keySearch="birthday"
/>
</div>
<Controller
name={ 'phone_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Số điện thoại" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.phone_customer?.type === 'required' ? 'Số điện thoại khách hàng không được bỏ trống!' : null } /> } />
<Controller
name={ 'email_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Email" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.email_customer?.type === 'required' ? 'Email khách hàng không được bỏ trống!' : null } /> } />
<div className="flex items-end w-full">
<DateSingle title="Ngày tạo" classNameTitle="w-1/4"
onChange={ setForm }
value={ form } keySearch="date_created"
/>
</div>
</div>
<div>
<Controller
name={ 'address_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Quê quán" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.address_customer?.type === 'required' ? 'Quê quán khách hàng không được bỏ trống!' : null } /> } />
<Controller
name={ 'hktt_customer' }
control={ control }
rules={ { required: true } }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Hộ khẩu thường trú" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ errors?.hktt_customer?.type === 'required' ? 'HKTT khách không được bỏ trống!' : null } /> } />
</div>
</div>
</div>
<div>
<h4 className="text-blue-500">Thông tin công ty</h4>
<div>
<div className="grid grid-cols-2 gap-4">
<Controller
name={ 'name_company' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Tên công ty" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null } /> } />
<Controller
name={ 'address_company' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Địa chỉ công ty" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null } /> } />
</div>
<div className="grid grid-cols-3 gap-4">
<Controller
name={ 'code_company' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Mã đăng ký công ty" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null } /> } />
<Controller
name={ 'phone_company' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Số điện thoại công ty" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null } /> } />
<Controller
name={ 'mail_company' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Email công ty" className="w-full"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null } /> } />
</div>
<Controller
name={ 'node' }
control={ control }
rules={ {} }
render={ ({ field: { onChange, value } }) =>
<TextFieldInput label="Ghi chú" className="w-full" multiline rows={ 3 } id="standard-multiline-static"
onChange={ e => {
onChange(e.target.value);
} }
value={ value }
error={ null } /> } />
</div>
</div>
</div>
</>
);
};
DetailInfo.propTypes = {
setForm: PropTypes.func,
form: PropTypes.object,
isAdd: PropTypes.bool
};
export default DetailInfo;<file_sep>import React from 'react';
// import { useQuery } from 'react-query';
// import { getAccount } from '../../service/auth/login';
const Overview = () => {
// const getLogin = async () => {
// return await getAccount();
// };
// const { data } = useQuery(
// [ 'EMPLOYEE_LIST_KEY' ],
// () => getLogin(),
// { keepPreviousData: true, staleTime: 5000 }
// );
// console.log(data);
return (
<>
<h1>Tổng quan</h1>
</>
);
};
export default Overview;<file_sep>import React from 'react';
const ToHieu = () => {
return (
<>
<h1>{ 'Viết code cho màn hình "địa điểm <NAME>ệu" tại đây' }</h1>
</>
);
};
export default ToHieu;<file_sep>import React from 'react';
const SetUpABusiness = () => {
return (
<>
<h1>{ 'Viết code cho trang "Thành lập doanh nghiệp" ở đây' }</h1>
</>
);
};
export default SetUpABusiness;<file_sep>import React, {useEffect, useState} from 'react';
import Button from '@material-ui/core/Button';
import {makeStyles} from '@material-ui/core/styles';
import AddIcon from '@material-ui/icons/Add';
import PropTypes from 'prop-types';
import {useRecoilState} from 'recoil';
import {getYearMonthDay} from '../../../../helpers/helper';
import {orderBookFilterParamsContinuous} from '../../../../store/actom/orderBook/orderBook';
import DateFromTo from '../../../base/dateTime/DateFromTo';
import CheckboxGroupTime from './CheckboxGroupTime';
import DialogService from './DialogService';
// const timeSelect = [
// {id: 200, value: '8h-10', checked: false},
// ];
// const timeSelect = [
// {id: 200, value: '8h-10', checked: false}
// ];
const useStyles = makeStyles((theme) => ({
button: {
margin: theme.spacing(1),
},
button1: {
margin: theme.spacing(0),
marginRight: '6px'
},
}));
const IntermittentUse = ({data}) => {
const classes = useStyles();
const timeSelect = data.filter(i => i.startTime.indexOf('C') === -1);
const timeSelectAll = data.filter(i => i.startTime.indexOf('C') !== -1);
const [filterState, setFilterState] = useRecoilState(orderBookFilterParamsContinuous);
const [newDate, setNewDate] = useState(new Date());
const addDate = {startDate: newDate, listShift: [], listService: []};
const [listDate, setListDate] = useState([addDate]);
const onClickAdd = () => {
setListDate([...listDate, addDate]);
};
const onDelete = (index, listDate) => {
listDate.length > 1 ? listDate.splice(index, 1) : listDate.splice(index, 0);
setListDate([...listDate]);
};
const [openDialog, setOpenDialog] = useState(false);
const [indexNumber, setIndexNumber] = useState(0);
const listService = (index) => {
setOpenDialog(!openDialog);
setIndexNumber(index);
};
const [selectedDay, setSelectedDay] = useState([]);
useEffect(() => {
setSelectedDay(
listDate.map(i => {
return new Date(i.startDate);
})
);
setNewDate(maxDate(listDate.map(i => {
return new Date(i.startDate);
})));
}, [listDate]);
useEffect(() => {
setFilterState({
...filterState,
idAll: timeSelectAll[0].id.toString(),
schdules: listDate.map(item => {
return {
...item,
startDate: getYearMonthDay(item.startDate),
// listService: item.listService.filter(i => i.checked).map(j => j.id.toString()),
// // listShift: item.listShift.filter(k => k.checked).map(h => h.id.toString())
// listShift: (item.listShift.filter(k => k.checked).length === timeSelect.length ?
// [timeSelectAll[0].id.toString()] : item.listShift.filter(h => h.checked).map(t => t.id.toString()))
};
})
});
}, [listDate]);
const maxDate = (day) => {
if (day.length <= 0) {
return new Date();
}
let maxDay = new Date();
for (let i = 0; i < day.length; i++) {
if (day[i] - maxDay > 0) {
maxDay = day[i];
}
}
maxDay.setDate(maxDay.getDate() + 1);
return maxDay;
};
return (
<>
{
listDate.map((item, index) => {
return (
<div className='border-dashed pl-3 pt-2 ml-10 mb-1' key={ index }>
<div>
<div className='flex justify-between items-start'>
<div className='w-1/2'>
<DateFromTo title={ `Ngày (${index + 1})` } keySearch={ 'oneDate' }
valueItem={ item.startDate }
classNameTitle='w-64' selectedDay={ selectedDay }
setListDate={ setListDate } index={ index } listDate={ listDate }
newDate={ newDate }/>
</div>
<div>
<Button variant="outlined" color="primary" className={ classes.button1 }
size="small"
onClick={ () => listService(index) }>Dịch vụ</Button>
<Button variant="outlined" color="primary" className={ classes.button1 }
size="small"
onClick={ () => onDelete(index, listDate) }>Xóa</Button>
</div>
</div>
<div className='pl-16 pt-1'>
<CheckboxGroupTime listDate={ listDate } setListDate={ setListDate }
timeSelectAll={ timeSelectAll } timeSelect={ timeSelect }
dataItem={ item.listShift }
indexs={ index } className='w-full'/>
</div>
</div>
</div>
);
})
}
{
openDialog &&
<DialogService openDialog={ openDialog } setOpenDialog={ setOpenDialog } indexs={ indexNumber }
listDate={ listDate }
setListDate={ setListDate } dataItem={ listDate[indexNumber].listService }/>
}
<div className='flex justify-center mb-5'>
<Button variant="outlined" color="primary" className={ classes.button } startIcon={ <AddIcon/> }
onClick={ onClickAdd }>
Thêm ngày
</Button>
</div>
</>
);
}
;
IntermittentUse.propTypes = {
data: PropTypes.array
};
export default IntermittentUse;<file_sep>import React from 'react';
const BranchDetail = () => {
return (
<>
<div className="border mt-8">
<div className="m-4">
<h4 className="text-center mb-6 text-xl font-semibold">Thông tin phòng chi tiết</h4>
<div className="grid grid-cols-3 mx-16">
<div>
</div>
<div></div>
<img src="https://hanoioffice.vn/wp-content/uploads/2021/02/phong-hop-cho-thue-1.jpg" alt="" />
</div>
<div className="grid grid-cols-5 mx-16">
<img src="https://hanoioffice.vn/wp-content/uploads/2020/09/cho-ngoi-lam-viec-n1.jpg" alt="" />
<img src="https://hanoioffice.vn/wp-content/uploads/2020/09/cho-ngoi-lam-viec-n2.jpg" alt="" />
<img src="https://hanoioffice.vn/wp-content/uploads/2020/10/Phong-hop-cho-thue.jpg" alt="" />
<img src="https://hanoioffice.vn/wp-content/uploads/2020/08/cho-thue-phong-hop.jpg" alt="" />
<img src="https://hanoioffice.vn/wp-content/uploads/2020/08/cho-thue-phong-hop-lon.jpg" alt="" />
</div>
</div>
</div>
</>
);
};
export default BranchDetail;<file_sep>import React from 'react';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Radio from '@material-ui/core/Radio';
// import FormLabel from '@material-ui/core/FormLabel';
// import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import PropTypes from 'prop-types';
// import { useSetRecoilState } from 'recoil';
// import FramesFilter from '../framesFilter';
// import { StyledRadio } from '../radio/tabRadio';
const CardWork = ({ values = '2' }) => {
// const setParams = useSetRecoilState(filterParams);
const [ value, setValue ] = React.useState(values);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<>
<div className="shadow-md bg-white">
<div className="flex items-center">
<span className='pr-6 pl-4 font-medium'>Hoạt động</span>
<FormControl component="fieldset">
<RadioGroup row aria-label="position" defaultValue={ '2' } name="position" onChange={ handleChange }>
<FormControlLabel
value={ '2' }
control={ <Radio color="primary" /> }
label="Tất cả"
labelPlacement="end"
onChange={ handleChange }
checked={ value === '2' }
/>
<FormControlLabel
value={ '0' }
control={ <Radio color="primary" /> }
label="Còn hoạt động"
labelPlacement="end"
onChange={ handleChange }
checked={ value === '0' }
/>
<FormControlLabel
value={ '1' }
control={ <Radio color="primary" /> }
label="Ngừng hoạt động"
labelPlacement="end"
onChange={ handleChange }
checked={ value === '1' }
/>
</RadioGroup>
</FormControl>
</div>
</div>
</>
);
};
CardWork.propTypes = {
values: PropTypes.number,
name: PropTypes.string,
filterParams: PropTypes.object
};
export default CardWork;
<file_sep>// import React from 'react';
// import AppBar from '@material-ui/core/AppBar';
// import { useTheme } from '@material-ui/core/styles';
// import Tab from '@material-ui/core/Tab';
// import Tabs from '@material-ui/core/Tabs';
// import TabPanel from '../common/tabPanel/TabPanel';
// import { a11yProps, useStyles } from '../common/tabPanel/tabPanelProps';
// const Users = () => {
// const classes = useStyles();
// const theme = useTheme();
// const [ value, setValue ] = React.useState(0);
// const handleChange = (event, newValue) => {
// setValue(newValue);
// };
// return (
// <div className={ classes.root }>
// <AppBar position="static" color="default">
// <Tabs
// value={ value }
// onChange={ handleChange }
// indicatorColor="primary"
// textColor="primary"
// variant="scrollable"
// scrollButtons="auto"
// aria-label="scrollable auto tabs example"
// >
// <Tab label="Danh sách khách hàng" { ...a11yProps(0) } />
// <Tab label="Danh sách đen" { ...a11yProps(1) } />
// </Tabs>
// </AppBar>
// <TabPanel value={ value } index={ 0 } dir={ theme.direction }>
// Danh sách nhân viên
// </TabPanel>
// <TabPanel value={ value } index={ 1 } dir={ theme.direction }>
// Phân quyền
// </TabPanel>
// </div>
// );
// };
// export default Users;<file_sep>import React from 'react';
import CardBranch from './CardBranch';
import CardTypeRoom from './CardTypeRoom';
import MaxPeople from './maxPeople';
const Filter = () => {
return (
<>
<div className='flex items-center'>
<CardBranch/>
<CardTypeRoom/>
</div>
<div className='pb-4'>
<MaxPeople/>
</div>
</>
);
};
export default Filter;<file_sep>import {axiosInstance} from '../../../config/axios';
import {getYearMonthDay} from '../../../helpers/helper';
export const getListCustomer = () => {
// const getList = async (value) => {
// const {page = '1', pageLimit = '15', strSearch ='', nameRoom='',
// numberPeople='', branchRoom=[], kindOfRoom=''}= value;
// const param = `page=${page}&pageLimit=${pageLimit}&strSearch=${strSearch}`+
// `&nameRoom=${nameRoom}&numberPeople=${numberPeople}&branchRoom=${branchRoom}&kindOfRoom=${kindOfRoom}`;
// const { data } = await axiosInstance.get('/customers-customers-customers?'+param);
// return data;
// return dataProcesing(data, page, pageLimit, [strSearch, nameRoom, numberPeople, kindOfRoom], branchRoom);
// };
// const getDetail = async (id) => {
// const { data } = await axiosInstance.get('/customers-customers-customers?id='+id);
// return data;
// };
const getList = async (value) => {
const {
page = '1', pageLimit = '15', strSearch = '', nameRoom = '',
numberPeople = '', branchRoom = [], kindOfRoom = []
} = value;
const {data} = await axiosInstance.get('/customer/find_all');
return dataProcesing(setDataNew(data), page, pageLimit, [strSearch, nameRoom, numberPeople], kindOfRoom, branchRoom);
};
const addRoom = async (value) => {
console.log(value);
const {data} = await axiosInstance.get('/typeroom/insert', {...value});
return data;
};
const updateRoom = async (id) => {
const {data} = await axiosInstance.put('/customers-customers-customers?param=' + id);
return data;
};
const deleteRoom = async (id) => {
const {data} = await axiosInstance.delete('/customers-customers-customers?param=' + id);
return data;
};
return {addRoom, updateRoom, deleteRoom, getList};
};
const dataProcesing = (data, page, limit, filter, kindOfRoom, branchRoom) => {
if (data.length > 0) {
const dataId = data.filter(i => (filter[0] !== '' ? i.codeRoom === filter[0] : true)
&& (filter[1] !== '' ? i.name === filter[1] : true)
&& (filter[2] !== '' ? i.soChoNgoi.toString() === filter[2] : true)
&& (branchRoom.length > 0 ? branchRoom.includes(i.idBranch) : true)
&& (kindOfRoom.length > 0 ? kindOfRoom.includes(i.typeRoom) : true));
const startLimit = (page - 1) * limit;
const endLimit = page * limit > data.length ? data.length : page * limit;
const dataNew = dataId.slice(startLimit, endLimit);
return {
data: dataNew,
meta: {
total_data: data.length,
total_dataNew: dataNew.length,
total_dataPage: dataId.length
}
};
} else {
return {
data: [],
meta: {
total_data: 0
}
};
}
};
const setDataNew = (data) => {
return data.map(i => {
return {
...i,
detail: 'Xem',
gender: i.gender ? 'Nam' : 'Nữ',
birthDay: getYearMonthDay(i.birthDay, 'dd-MM-yyyy'),
createDate: getYearMonthDay(i.createDate, 'dd-MM-yyyy'),
fullName: i.lastName + ' ' + i.firstName,
status: i.status ? 'Đang sử dụng' : 'Chưa sử dụng',
};
});
};
// 1. Đang sử dụng
// 2. Ngừng sử dụng
// 3. Chưa sử dụng
// 4. Đã sử dụng xong<file_sep>import React, {useState, useEffect} from 'react';
import PropTypes from 'prop-types';
import {useRecoilState} from 'recoil';
import {getYearMonthDay} from '../../../../helpers/helper';
import {orderBookFilterParams} from '../../../../store/actom/orderBook/orderBook';
import DateFromTo_V2 from '../../../base/dateTime/DateFromTo_V2';
import ServiceBook from '../serviceBook';
import ContinuousShift from './continuousShift';
const ContinuousUse = ({data = []}) => {
const [valueFrom, setValueFrom] = useState(new Date());
const [valueTo, setValueTo] = useState(new Date());
useEffect(() => {
setValueTo(valueFrom > valueTo ? valueFrom : valueTo);
}, [valueFrom]);
const [filterState, setFilterState] = useRecoilState(orderBookFilterParams);
useEffect(() => {
setFilterState({
...filterState,
startDate: getYearMonthDay(valueFrom),
endDate: getYearMonthDay(valueTo)
});
}, [valueFrom, valueTo]);
return (
<>
<div className='mb-6 border-dashed pl-3 pt-2 ml-10'>
<div className='grid grid-cols-2 gap-6 mb-1'>
<DateFromTo_V2 title={ 'Ngày bắt đầu' } value={ valueFrom }
onChange={ setValueFrom } classNameTitle='w-64'/>
<DateFromTo_V2 title={ 'Ngày kết thúc' } value={ valueTo } onChange={ setValueTo }
classNameTitle='w-64'
disabledDays={ valueFrom }/>
</div>
<div className='pl-16'>
<ContinuousShift data={ data }/>
</div>
</div>
<div className='ml-10'>
<ServiceBook/>
</div>
</>
);
};
ContinuousUse.propTypes = {
values: PropTypes.number,
name: PropTypes.string,
filterParams: PropTypes.object,
data: PropTypes.array
};
export default ContinuousUse;
<file_sep>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import { useTheme } from '@material-ui/core/styles';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import TabPanel from '../../../components/common/tabPanel/TabPanel';
import { a11yProps, useStyles } from '../../../components/common/tabPanel/tabPanelProps';
import Layout from '../../../layouts';
import TransferList from '../transfer/transferList';
import Filter from '../transfer/transferList/Filters';
const Transfer = () => {
const classes = useStyles();
const theme = useTheme();
const [ value, setValue ] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<>
<Layout>
<div className={ classes.root }>
<AppBar position="static" color="default">
<Tabs
value={ value }
onChange={ handleChange }
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
aria-label="scrollable auto tabs example"
>
<Tab label="Chuyển nhượng hợp đồng" { ...a11yProps(0) } />
</Tabs>
</AppBar>
<TabPanel value={ value } index={ 0 } dir={ theme.direction } className="customs-tabPanel" nav={ Filter }>
<TransferList />
</TabPanel>
</div>
</Layout>
</>
);
};
export default Transfer;<file_sep>import {axiosInstance} from '../../../config/axios';
import {getYearMonthDay} from '../../../helpers/helper';
export const getListEmployees = () => {
const getList = async (value) => {
const {
page = '1', pageLimit = '15', strSearch = '', nameRoom = '',
numberPeople = '', branchRoom = [], kindOfRoom = []
} = value;
const {data} = await axiosInstance.get('/staff/find_all');
return dataProcesing(setDataNew(data), page, pageLimit, [strSearch, nameRoom, numberPeople], kindOfRoom, branchRoom);
};
const getDetail = async () => {
const {data} = await axiosInstance.get('/employees-employees-employees');
return data;
};
return {getList, getDetail};
};
const dataProcesing = (data, page, limit, filter, kindOfRoom, branchRoom) => {
if (data.length > 0) {
const dataId = data.filter(i => (filter[0] !== '' ? i.codeRoom === filter[0] : true)
&& (filter[1] !== '' ? i.name === filter[1] : true)
&& (filter[2] !== '' ? i.soChoNgoi.toString() === filter[2] : true)
&& (branchRoom.length > 0 ? branchRoom.includes(i.idBranch) : true)
&& (kindOfRoom.length > 0 ? kindOfRoom.includes(i.idTypeRoom) : true));
const startLimit = (page - 1) * limit;
const endLimit = page * limit > data.length ? data.length : page * limit;
const dataNew = dataId.slice(startLimit, endLimit);
return {
data: dataNew,
meta: {
total_data: data.length,
total_dataNew: dataNew.length,
total_dataPage: dataId.length
}
};
} else {
return {
data: [],
meta: {
total_data: 0
}
};
}
};
const setDataNew = (data) => {
return data.map(i => {
return {
...i,
id: i.id,
detail: 'Xem',
gender: i.gender ? 'Nam' : 'Nữ',
birthDay: getYearMonthDay(i.birthDay, 'dd-MM-yyyy'),
roleName: i.role.name,
roleId: i.role.id,
branchName: i.branch.name,
branchId: i.branch.id,
status: i.status ? 'Còn làm' : 'Đã nghỉ',
createDate: getYearMonthDay(i.createDate, 'dd-MM-yyyy')
};
});
};
<file_sep>import React, {useState} from 'react';
// import Button from '@material-ui/core/Button';
// import {makeStyles} from '@material-ui/core/styles';
import {useQuery} from 'react-query';
import {getListAppointment} from '../../../../../service/book/listBook/appointment';
import {listBookFilterParamsState} from '../../../../../store/atoms/book/appointment';
import CheckboxGroup_V2 from '../../../../base/checkbox/CheckboxGroup_V2';
import DateFromTo_V2 from '../../../../base/dateTime/DateFromTo_V2';
// const useStyles = makeStyles((theme) => ({
// button: {
// margin: theme.spacing(1),
// },
// button1: {
// margin: theme.spacing(0),
// marginRight: '6px'
// },
// }));
const SchedulesItem2 = () => {
// const classes = useStyles();
const [valueTo, setValueTo] = useState(new Date());
const [valueFrom, setValueFrom] = useState(new Date());
// const [opentDetail, setOpentDetail] = useState(false);
const {data} = useQuery(
['LIST_TIME_SALE'],
() => getListAppointment().getListTime(),
{
keepPreviousData: true, staleTime: 5000,
}
);
const timeSelect = data.filter(i => i.startTime.indexOf('C') === -1);
const timeSelectAll = data.filter(i => i.startTime.indexOf('C') !== -1);
const {data: dataService} = useQuery(
['LIST_SERVICE'],
() => getListAppointment().getListService(),
{
keepPreviousData: true, staleTime: 5000,
}
);
// const listService = () => {
//
// };
return (
<>
<div className='shadow-lg bg-gray-100'>
<div className='w-fulll items-center px-3 gap-x-2'>
<div className='grid grid-cols-2 gap-6 mb-1'>
<DateFromTo_V2 title={ 'Ngày bắt đầu' } value={ valueFrom }
onChange={ setValueFrom } classNameTitle='w-64'/>
<DateFromTo_V2 title={ 'Ngày kết thúc' } value={ valueTo } onChange={ setValueTo }
classNameTitle='w-64'
disabledDays={ valueFrom }/>
</div>
<div className='m-2 pt-3 flex items-center'>
<CheckboxGroup_V2 dataCheckbox={ timeSelect } title={ '' } filterParams={ listBookFilterParamsState }
name={ 'listTime' } dataAll={ timeSelectAll } className='w-full'
lableAll={ 'Cả ngày' } color={ 'primary' } column={ '5' }/>
</div>
</div>
{
<div className='mx-5 my-2'>
<CheckboxGroup_V2 dataCheckbox={ dataService } title={ 'Dịch vụ yêu cầu' }
filterParams={ listBookFilterParamsState }
name={ 'listService' } className='w-full text-xs' dataAll={ [] } column={ '5' }/>
</div>
}
</div>
</>
);
};
export default SchedulesItem2;<file_sep>// import React from 'react';
// import Breadcrumbs from '@material-ui/core/Breadcrumbs';
// import Typography from '@material-ui/core/Typography';
// import { NavLink } from 'react-router-dom';
// const BreadcrumbsContract = () => {
// const handleClick = (event) => {
// event.preventDefault();
// };
// return (
// <>
// <Breadcrumbs aria-label="breadcrumb">
// <NavLink color="inherit" href="/" onClick={ handleClick }>
// Material-UI
// </NavLink>
// <NavLink color="inherit" href="/getting-started/installation/" onClick={ handleClick }>
// Core
// </NavLink>
// <Typography color="textPrimary">Breadcrumb</Typography>
// </Breadcrumbs>
// </>
// );
// };
// export default BreadcrumbsContract;<file_sep>import React from 'react';
import MuiAccordion from '@material-ui/core/Accordion';
// import AccordionDetails from '@material-ui/core/AccordionDetails';
import MuiAccordionDetails from '@material-ui/core/AccordionDetails';
import MuiAccordionSummary from '@material-ui/core/AccordionSummary';
// import AccordionSummary from '@material-ui/core/AccordionSummary';
import Paper from '@material-ui/core/Paper';
import {
withStyles,
makeStyles
} from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
// import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TablePagination from '@material-ui/core/TablePagination';
// import TableRow from '@material-ui/core/TableRow';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
// const StyledTableCell = withStyles((theme) => ({
// head: {
// backgroundColor: '#4466ca',
// color: theme.palette.common.white,
// },
// body: {
// fontSize: 14,
// },
// }))(TableCell);
// const StyledTableRow = withStyles((theme) => ({
// root: {
// '&:nth-of-type(odd)': {
// backgroundColor: theme.palette.action.hover,
// // minWidth: '100%'
// },
// },
// }))(TableRow);
const createData = (name, calories, fat, carbs, protein) => {
return { name, calories, fat, carbs, protein };
};
const rows = [
createData(1, '<NAME>̣p', 6.0, 24, 4.0),
createData(2, 'Ta<NAME>', 9.0, 37, 4.3),
createData(3, 'Nguyễ<NAME> <NAME>̣nh', 16.0, 24, 6.0),
createData(4, 'Trầ<NAME>́<NAME>̉o', 3.7, 67, 4.3),
createData(5, 'Nguyễ<NAME> <NAME>', 16.0, 49, 3.9),
createData(6, 'Bùi Vă<NAME>ệp', 6.0, 24, 4.0),
createData(7, 'Bùi Quang Trung', 9.0, 37, 4.3),
createData(8, 262, 16.0, 24, 6.0),
createData(9, 305, 3.7, 67, 4.3),
createData(10, 356, 16.0, 49, 3.9),
createData(11, '<NAME>̣p', 6.0, 24, 4.0),
createData(12, 237, 9.0, 37, 4.3),
createData(13, 262, 16.0, 24, 6.0),
createData(14, 305, 3.7, 67, 4.3),
createData(15, 356, 16.0, 49, 3.9),
];
const useStyles = makeStyles({
table: {
minWidth: 1200,
},
details: {
alignItems: 'center',
},
});
const Accordion = withStyles({
root: {
border: '1px solid rgba(0, 0, 0, .125)',
boxShadow: 'none',
'&:not(:last-child)': {
borderBottom: 0,
},
'&:before': {
display: 'none',
},
'&$expanded': {
margin: 'auto',
},
},
expanded: {},
})(MuiAccordion);
const AccordionSummary = withStyles({
root: {
backgroundColor: 'rgba(0, 0, 0, .03)',
borderBottom: '1px solid rgba(0, 0, 0, .125)',
marginBottom: -1,
minHeight: 56,
'&$expanded': {
minHeight: 56,
},
},
content: {
'&$expanded': {
margin: '12px 0',
},
},
expanded: {},
})(MuiAccordionSummary);
const AccordionDetails = withStyles((theme) => ({
root: {
padding: theme.spacing(2),
},
}))(MuiAccordionDetails);
const TableV1 = () => {
const [ page, setPage ] = React.useState(0);
const [ rowsPerPage, setRowsPerPage ] = React.useState(10);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(+event.target.value);
setPage(0);
};
const classes = useStyles();
const [ expanded, setExpanded ] = React.useState('');
const handleChange = (panel) => (event, newExpanded) => {
setExpanded(newExpanded ? panel : false);
};
const Detail = () => {
return (
<li>
<h1>Không có dữ liệu</h1>
</li>
);
};
return (
<>
<TableContainer component={ Paper }>
<Table className={ classes.table } aria-label="customized table">
<TableHead>
{/* <TableRow> */ }
<tr className='flex'>
<th className="w-20">Mã NV</th>
<th align="center" className="w-56">Họ tên</th>
<th align="center" className="w-36">Ảnh</th>
<th align="center" className="w-36">Giới tính</th>
<th align="center" className="w-36">Ngày sinh</th>
<th align="center" className="w-36">Chức vụ</th>
<th align="center" className="w-36">Số điện thoại</th>
<th align="center" className="w-36">Email</th>
<th align="center" className="w-36">Quê quán</th>
<th align="center" className="w-36">HKTT</th>
<th align="center" className="w-36">Ghi chú</th>
</tr>
{/* </TableRow> */ }
</TableHead>
<TableBody>
{ rows.map((row, index) => (
// <StyledTableRow key={ index }>
// <li key={ index }>
<Accordion square expanded={ expanded === 'panel' + index } onChange={ handleChange('panel' + index) } key={ index }>
<AccordionSummary
expandIcon={ <ExpandMoreIcon /> }
// aria-controls="panel1c-content"
// id="panel1c-header"
>
<tbody>
<tr>
<th className='w-20'>{ row.name }</th>
<th align="" className="w-56">{ row.calories }</th>
<th align="center" className="w-36">{ }</th>
<th align="center" className="w-36">{ row.fat }</th>
<th align="center" className="w-36">{ row.carbs }</th>
<th align="center" className="w-36">{ row.protein }</th>
<th align="center" className="w-36">{ row.carbs }</th>
<th align="center" className="w-36">{ row.protein }</th>
<th align="center" className="w-36">{ row.fat }</th>
<th align="center" className="w-36">{ row.fat }</th>
</tr>
</tbody>
</AccordionSummary>
<AccordionDetails className={ classes.details }>
<Detail />
</AccordionDetails>
</Accordion>
// </li>
// </StyledTableRow>
)) }
</TableBody>
</Table>
<TablePagination
rowsPerPageOptions={ [ 10, 25, 100 ] }
component="div"
count={ rows.length }
rowsPerPage={ rowsPerPage }
page={ page }
onChangePage={ handleChangePage }
onChangeRowsPerPage={ handleChangeRowsPerPage }
/>
</TableContainer>
</>
);
};
export default TableV1;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {orderBookFilterParams} from '../../../../store/actom/orderBook/orderBook';
import CheckboxGroup from '../../../base/checkbox/CheckboxGroup';
// const timeSelect = [
// {id: 200, value: '8h-10', checked: false},
// ];
const ContinuousShift = ({data}) => {
const timeSelect = data.filter(i => i.startTime.indexOf('C') === -1);
const timeSelectAll = data.filter(i => i.startTime.indexOf('C') !== -1);
return (
<>
<CheckboxGroup dataCheckbox={ timeSelect } title={ '' } filterParams={ orderBookFilterParams } name={ 'listTime' }
dataAll={ timeSelectAll } className='w-full' lableAll={ 'Cả ngày' } color={ 'primary' }/>
</>
);
};
ContinuousShift.propTypes = {
data: PropTypes.array
};
export default ContinuousShift;<file_sep>import {
// CalendarToday,
AttachMoney
} from '@material-ui/icons';
// const color = 'primary';
export const router = [
{
id: 1,
icon: null,
title: 'Trang chủ',
path: '/',
type: 'home',
subMenu: [
{ id: 101, subTitle: 'Trang chủ', subPath: '/', subItem: [] },
]
},
{
id: 2,
icon: null,
title: 'Dịch vụ',
path: '/service',
type: 'service',
subMenu: [
{ id: 201, subTitle: 'Văn phòng ảo', subPath: '/van-phong-ao', subItem: [] },
{ id: 202, subTitle: 'Văn phòng trọn gói', subPath: '/van-phong-tron-goi', subItem: [] },
{ id: 203, subTitle: 'Chỗ ngồi làm việc', subPath: '/cho-ngoi-lam-viec', subItem: [] },
{ id: 204, subTitle: 'Văn phòng lưu động', subPath: '/van-phong-luu-dong', subItem: [] },
{ id: 205, subTitle: 'Phòng họp', subPath: '/phong-hop', subItem: [] },
{ id: 206, subTitle: 'Phòng họp trực tuyến', subPath: '/phong-hop-truc-tuyen', subItem: [] },
// {
// id: 207, subTitle: 'Dịch vụ khác', subPath: '#', subIcon: <CalendarToday />, subItem: [
// { id: 2071, itemTitle: 'Zoom conference', itemPath: '/zoom-conference' },
// { id: 2072, itemTitle: 'Chữ ký số', itemPath: '/chu-ky-so' },
// { id: 2073, itemTitle: 'Hóa đơn điện tử', itemPath: '/hoa-don-dien-tu' },
// { id: 2074, itemTitle: 'BHXH điện tử', itemPath: '/bhxh-dien-tu' },
// { id: 2075, itemTitle: 'Các dịch vụ viễn thông', itemPath: '/cac-dich-vu-vien-thong' },
// { id: 2076, itemTitle: 'Thành lập doanh nghiệp', itemPath: '/thanh-lap-doanh-nghiep' },
// { id: 2077, itemTitle: 'Biên - Phiên dịch', itemPath: '/bien-phien-dich' },
// { id: 2078, itemTitle: 'Creative Content', itemPath: '/creative-content' },
// ]
// },
]
},
{
id: 9,
icon: null,
title: 'Dịch vụ khác',
path: '/service_orther',
type: 'service_orther',
subMenu: [
{ id: 901, subTitle: 'Zoom conference', subPath: '/zoom-conference' },
{ id: 902, subTitle: 'Chữ ký số', subPath: '/chu-ky-so' },
{ id: 903, subTitle: 'Hóa đơn điện tử', subPath: '/hoa-don-dien-tu' },
{ id: 904, subTitle: 'BHXH điện tử', subPath: '/bhxh-dien-tu' },
{ id: 905, subTitle: 'Các dịch vụ viễn thông', subPath: '/cac-dich-vu-vien-thong' },
{ id: 906, subTitle: 'Thành lập doanh nghiệp', subPath: '/thanh-lap-doanh-nghiep' },
{ id: 907, subTitle: 'Biên - Phiên dịch', subPath: '/bien-phien-dich' },
{ id: 908, subTitle: 'Creative Content', subPath: '/creative-content' },
]
},
{
id: 3,
icon: null,
title: 'Địa điểm',
path: '/place',
type: 'place',
subMenu: [
{ id: 301, subTitle: 'Lê văn Lương - Thanh Xuân', subPath: '/le-van-luong-thanh-xuan' },
{ id: 302, subTitle: 'Khuất Duy tiến - Thanh xuân', subPath: '/khuat-duy-tien-thanh-xuan' },
{ id: 303, subTitle: 'Tam chinh - Hoàng Mai', subPath: '/tam-chinh-hoang-mai' },
{ id: 304, subTitle: 'Trần phú - Hà Đông', subPath: '/tran-phu-ha-dong' },
{ id: 305, subTitle: 'Nguyễn Thái Học - Ba Đình', subPath: '/nguyen-thai-hoc-ba-dinh' },
{ id: 306, subTitle: 'Duy Tân - Cầu Giấy', subPath: '/duy-tan-cau-giay' },
{ id: 306, subTitle: 'Tô Hiệu - Hà Đông', subPath: '/to-hieu-ha-dong' },
{ id: 306, subTitle: 'Lê ĐỨc Thọ - Nam Từ Liêm', subPath: '/le-duc-tho-nam-tu-liem' },
]
},
{
id: 4,
icon: null,
title: 'Tin tức',
path: '/news',
type: 'news',
subMenu: [
{ id: 401, subTitle: 'Bản tin kinh tế', subPath: '/ban-tin-kinh-te' },
{ id: 402, subTitle: 'Bản tin pháp luật', subPath: '/ban-tin-phap-luat' },
{ id: 403, subTitle: 'Tài liệu', subPath: '/tai-lieu' },
{ id: 404, subTitle: 'Tuyển dụng', subPath: '/tuyen-dung' },
]
},
{
id: 5,
icon: null,
title: 'Giới thiệu',
path: '/gioi-thieu',
type: 'introduce',
subMenu: [
{ id: 501, subTitle: 'Giới thiệu', subPath: '/gioi-thieu', subItem: [] },
]
},
{
id: 6,
icon: null,
title: 'Liên hệ',
path: '/lien-he',
type: 'contact',
subMenu: [
{ id: 601, subTitle: 'Liên hệ', subPath: '/lien-he', subItem: [] }, ]
},
{
id: 7,
icon: <AttachMoney />,
title: 'Bảng báo giá',
path: '/bang-bao-gia',
type: 'quotation',
subMenu: [
{ id: 701, subTitle: 'Bảng báo giá', subPath: '/bang-bao-gia', subItem: [] }, ]
},
{
id: 8,
icon: null,
title: 'Đăng ký phòng',
path: '/dat-van-phong',
type: 'book_an_office',
subMenu: [
{ id: 801, subTitle: 'Đăng ký phòng', subPath: '/dang-ky-phong', subItem: [] },
{ id: 802, subTitle: 'Lịch sử dụng', subPath: '/lich-su-dung', subItem: [] },
]
},
{
id: 10,
icon: null,
title: 'Chính sách chuyển nhượng',
path: '/chinh-sach-chuyen-nhuong',
type: '',
subMenu: [
{ id: 110, subTitle: 'Chính sách chuyển nhượng', subPath: '/chinh-sach-chuyen-nhuong', subItem: [] }
]
}
];<file_sep>import React from 'react';
// import AppBar from '@material-ui/core/AppBar';
import Badge from '@material-ui/core/Badge';
import IconButton from '@material-ui/core/IconButton';
// import InputBase from '@material-ui/core/InputBase';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import { fade, makeStyles } from '@material-ui/core/styles';
import SwipeableDrawer from '@material-ui/core/SwipeableDrawer';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import AccountCircle from '@material-ui/icons/AccountCircle';
import ColorLensIcon from '@material-ui/icons/ColorLens';
import MailIcon from '@material-ui/icons/Mail';
// import MenuIcon from '@material-ui/icons/Menu';
import MenuIcon from '@material-ui/icons/Menu';
import MoreIcon from '@material-ui/icons/MoreVert';
import NotificationsIcon from '@material-ui/icons/Notifications';
// import SearchIcon from '@material-ui/icons/Search';
import { useRecoilState, useRecoilValue } from 'recoil';
import useWindowDimensions from '../../hooks/useWindowDimensions';
import { setWidthDefault } from '../../store/atoms/header/header';
import { onCloseOpenDrawer } from '../../store/atoms/header/header';
import MenuHeaderBar from './MenuBar';
const useStyles = makeStyles((theme) => ({
grow: {
flexGrow: 1
},
menuButton: {
marginRight: theme.spacing(2)
},
title: {
display: 'none',
[ theme.breakpoints.up('sm') ]: {
display: 'block'
}
},
search: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white, 0.15),
'&:hover': {
backgroundColor: fade(theme.palette.common.white, 0.25)
},
marginRight: theme.spacing(2),
marginLeft: 0,
width: '100%',
[ theme.breakpoints.up('sm') ]: {
marginLeft: theme.spacing(3),
width: 'auto'
}
},
searchIcon: {
padding: theme.spacing(0, 2),
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
},
inputRoot: {
color: 'inherit'
},
inputInput: {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
transition: theme.transitions.create('width'),
width: '100%',
[ theme.breakpoints.up('md') ]: {
width: '20ch'
}
},
sectionDesktop: {
display: 'none',
[ theme.breakpoints.up('md') ]: {
display: 'flex'
}
},
sectionMobile: {
display: 'flex',
[ theme.breakpoints.up('md') ]: {
display: 'none'
}
}
}));
const TopHeader = () => {
const { screenWidth } = useWindowDimensions();
const widthDefault = useRecoilValue(setWidthDefault);
const [ stateMenu, setStateMenu ] = useRecoilState(onCloseOpenDrawer);
const classes = useStyles();
const [ anchorEl, setAnchorEl ] = React.useState(null);
const [ mobileMoreAnchorEl, setMobileMoreAnchorEl ] = React.useState(null);
const isMenuOpen = Boolean(anchorEl);
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
const handleProfileMenuOpen = (event) => {
setAnchorEl(event.currentTarget);
};
const handleMobileMenuClose = () => {
setMobileMoreAnchorEl(null);
};
const handleMenuClose = () => {
setAnchorEl(null);
handleMobileMenuClose();
};
const handleMobileMenuOpen = (event) => {
setMobileMoreAnchorEl(event.currentTarget);
};
const menuId = 'primary-search-account-menu';
const renderMenu = (
<Menu
anchorEl={ anchorEl }
anchorOrigin={ { vertical: 'top', horizontal: 'right' } }
id={ menuId }
keepMounted
transformOrigin={ { vertical: 'top', horizontal: 'right' } }
open={ isMenuOpen }
onClose={ handleMenuClose }
>
<MenuItem onClick={ handleMenuClose }>Thông tin cá nhân</MenuItem>
<MenuItem onClick={ handleMenuClose }>Tùy chỉnh</MenuItem>
<MenuItem onClick={ handleMenuClose }>Cài đặt</MenuItem>
<MenuItem onClick={ handleMenuClose }>Trợ giúp</MenuItem>
<MenuItem onClick={ handleMenuClose }>Đăng xuất</MenuItem>
</Menu>
);
const mobileMenuId = 'primary-search-account-menu-mobile';
const renderMobileMenu = (
<Menu
anchorEl={ mobileMoreAnchorEl }
anchorOrigin={ { vertical: 'top', horizontal: 'right' } }
id={ mobileMenuId }
keepMounted
transformOrigin={ { vertical: 'top', horizontal: 'right' } }
open={ isMobileMenuOpen }
onClose={ handleMobileMenuClose }
>
<MenuItem>
<IconButton aria-label="show 4 new mails" color="inherit">
<Badge badgeContent={ 4 } color="secondary">
<MailIcon />
</Badge>
</IconButton>
<p>Tin nhắn</p>
</MenuItem>
<MenuItem>
<IconButton aria-label="show 11 new notifications" color="inherit">
<Badge badgeContent={ 11 } color="secondary">
<NotificationsIcon />
</Badge>
</IconButton>
<p>Thông báo</p>
</MenuItem>
<MenuItem onClick={ handleProfileMenuOpen }>
<IconButton
aria-label="account of current user"
aria-controls="primary-search-account-menu"
aria-haspopup="true"
color="inherit"
>
<AccountCircle />
</IconButton>
<p>Thông tin cá nhân</p>
</MenuItem>
<MenuItem onClick={ handleProfileMenuOpen }>
<IconButton
aria-label="account of current user"
aria-controls="primary-search-account-menu"
aria-haspopup="true"
color="inherit"
>
<AccountCircle />
</IconButton>
<p>Chủ đề</p>
</MenuItem>
</Menu>
);
return (
<div className={ classes.grow } >
<Toolbar>
<div className="flex items-center">
{ screenWidth < widthDefault && <MenuIcon onClick={ () => setStateMenu(true) } /> }
<Typography className={ classes.title } variant="h6" noWrap>
<span className="pl-2">HaNoiOffice</span>
</Typography>
</div>
<SwipeableDrawer anchor={ 'left' } open={ stateMenu } onClose={ () => setStateMenu(false) } onOpen={ () => setStateMenu(true) }>
<div className="w-72"
// onClick={ toggleDrawer(false) }
// onKeyDown={ toggleDrawer(false) }
>
<MenuHeaderBar />
</div>
</SwipeableDrawer>
<div className={ classes.grow } />
<div className={ classes.sectionDesktop }>
<IconButton color="inherit">
<ColorLensIcon />
</IconButton>
<IconButton aria-label="show 4 new mails" color="inherit">
<Badge badgeContent={ 4 } color="secondary">
<MailIcon />
</Badge>
</IconButton>
<IconButton aria-label="show 17 new notifications" color="inherit">
<Badge badgeContent={ 17 } color="secondary">
<NotificationsIcon />
</Badge>
</IconButton>
<IconButton
edge="end"
aria-label="account of current user"
aria-controls={ menuId }
aria-haspopup="true"
onClick={ handleProfileMenuOpen }
color="inherit"
>
<AccountCircle />
</IconButton>
</div>
<div className={ classes.sectionMobile }>
<IconButton
aria-label="show more"
aria-controls={ mobileMenuId }
aria-haspopup="true"
onClick={ handleMobileMenuOpen }
color="inherit"
>
<MoreIcon />
</IconButton>
</div>
</Toolbar>
{ renderMobileMenu }
{ renderMenu }
</div >
);
};
export default TopHeader;<file_sep>import { axiosInstance } from '../../../config/axios';
export const getSpecies = () => {
const getList = async (value) => {
const {page = '1', pageLimit = '15', strSearch ='', nameRoom='',
numberPeople='', branchRoom='', kindOfRoom=''}= value;
const param = `page=${page}&pageLimit=${pageLimit}&strSearch=${strSearch}`+
`&nameRoom=${nameRoom}&numberPeople=${numberPeople}&branchRoom=${branchRoom}&kindOfRoom=${kindOfRoom}`;
const { data } = await axiosInstance.get('/customers-customers-customers?'+param);
return {
data: data,
meta: {
total_data: data.length
}
};
};
const addSpecies = async (param) => {
const { data } = await axiosInstance.get('/customers-customers-customers?param='+param);
return data;
};
const updateSpecies = async (id) => {
const { data } = await axiosInstance.put('/customers-customers-customers?param='+id);
return data;
};
const deleteSpecies = async (id) => {
const { data } = await axiosInstance.delete('/customers-customers-customers?param='+id);
return data;
};
return { getList, addSpecies, updateSpecies, deleteSpecies };
};
<file_sep>import { atom } from 'recoil';
// const today = new Date();
export const listRoomFilterParamsState = atom({
key: 'listRoomFilterParamsState',
default: {
strSearch: '',
nameRoom: '',
numberPeople: '',
kindOfRoom: [],
branchRoom: []
}
});
export const listRoomPageLimitState = atom({
key: 'listRoomPageLimitState',
default: 15
});
export const listRoomPageState = atom({
key: 'listRoomPageState',
default: 1
});
export const listRoomColumnTableState = atom({
key: 'listRoomColumnTableState',
default: [
{ field: 'detail', headerName: 'Chi tiết', width: 80, sortable: false, description: 'Chi tiết', cellClassName: 'cursor-pointer' },
{ field: 'codeRoom', headerName: 'Mã phòng', width: 200, sortable: false, description: 'Mã phòng' },
{ field: 'name', headerName: 'Tên phòng', width: 250, sortable: false, description: 'Tên phòng' },
{ field: 'nameTypeRoom', headerName: 'Loại phòng', width: 200, sortable: false, description: 'Loại phòng' },
{ field: 'nameBranch', headerName: 'Chi nhánh', width: 200, sortable: false, description: 'Chi nhánh' },
{ field: 'address', headerName: 'Địa chỉ', width: 250, sortable: false, description: 'Địa chỉ' },
{ field: 'soChoNgoi', headerName: 'Phòng chứa tối đa', width: 150, sortable: false, description: 'Phòng chứa tối đa' },
// { field: 'data_start', headerName: 'Ngày tạo', width: 150, sortable: false, description: 'Thời gian bắt đầu sử dụng phòng' },
// { field: 'date_stop', headerName: 'Ngày ngừng', width: 150, sortable: false, description: 'Thời gian ngừng sử dụng phòng' },
{ field: 'description', headerName: 'Ghi chú', width: 300, sortable: false, description: 'Ghi chú' },
]
});<file_sep>import React, {useEffect, useState} from 'react';
import PropTypes from 'prop-types';
import {useQuery} from 'react-query';
import {useRecoilState} from 'recoil';
import {getListBook} from '../../../../service/bookAnOffices/bookAnOffices';
import {orderBookFilterParamsState} from '../../../../store/actom/orderBook/orderBook';
import SelectInput from '../../../base/input/SelectInput';
const CardBranch = () => {
// const [ branch, setBranch ] = useState([]);
// const branchSearch = useSetRecoilState(filterParams);
// console.log(branchSearch);
const [filterState, setFilterState] = useRecoilState(orderBookFilterParamsState);
//useSetRecoilState
const {data} = useQuery(
['BRANCH_LIST'],
() => getListBook().getListBranch(),
{
keepPreviousData: true, staleTime: 5000,
}
);
const [valueBranch, setValueBranch] = useState(data[0].id);
const onChageBranch = (e) => {
setValueBranch(e.target.value);
};
useEffect(() => {
setFilterState({
...filterState,
branch: valueBranch
}
);
}, [valueBranch]);
return (
<>
<SelectInput title='Chi nhánh' dataArr={ data } className='w-full' value={ valueBranch }
onChange={ e => onChageBranch(e) }/>
</>
);
};
CardBranch.propTypes = {
filterParams: PropTypes.object,
value: PropTypes.object,
onChange: PropTypes.func
};
export default CardBranch;<file_sep>import React, {useState} from 'react';
import DateFromTo_V2 from '../../../../base/dateTime/DateFromTo_V2';
import SelectInput from '../../../../base/input/SelectInput';
const dataBranch = [{id: 1, name: 'Chi nhánh Thanh Xuân'}, {id: 2, name: '<NAME>'}];
const TableFilter = () => {
const [valueBranch, setValueBranch] = useState(dataBranch[0].id);
const onChageBranch = (e) => {
setValueBranch(e.target.value);
};
const [valueTo, setValueTo] = useState(new Date());
const [valueFrom, setValueFrom] = useState(new Date());
return (
<>
<div className=' border-dashed my-4'>
<div className='grid grid-cols-2 gap-x-4 mx-3 mt-3 mb-2'>
<DateFromTo_V2 title={ 'Từ ngày' } value={ valueFrom }
onChange={ setValueFrom } classNameTitle='w-96'/>
<DateFromTo_V2 title={ 'Đến ngày' } value={ valueTo } onChange={ setValueTo }
classNameTitle='w-64' disabledDays={ valueFrom }/>
<SelectInput title='Chi nhánh' dataArr={ dataBranch } className='w-full' value={ valueBranch }
classNameItem='w-full' disabled={ false } onChange={ e => onChageBranch(e) }/>
</div>
</div>
</>
);
};
export default TableFilter;<file_sep>import React from 'react';
import TamChinh from '../../component/place/tamChinh';
const ComponentCenter = () => {
return (
<>
<TamChinh />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Button from '@material-ui/core/Button';
// import IconButton from '@material-ui/core/IconButton';
import { makeStyles } from '@material-ui/core/styles';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import {
ArrowRightAlt, Add, MailOutline,
Phone, YouTube, Twitter, Facebook,
Instagram, Pinterest, AccountCircle
} from '@material-ui/icons';
// import MenuIcon from '@material-ui/icons/Menu';
import { NavLink } from 'react-router-dom';
import { router } from '../../router';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
const Hearder = () => {
const classes = useStyles();
return (
<>
<div>
<div className={ classes.root }>
<AppBar position="static" color="inherit">
<Toolbar>
<Typography variant="h6" className={ classes.title }>
<div className="flex">
<div className="cursor-pointer">
<img className="w-64 h-10 mx-auto " src="https://hanoioffice.vn/wp-content/uploads/2021/02/logo-black.png" />
</div>
<div className="cursor-pointer">
<span ><Phone className="mb-1 mr-3" /></span>
<span className="text-base">085 339 4567 - 0904 388 909</span>
</div>
<div className="px-4 cursor-pointer">
<span ><MailOutline className="mb-1 mr-3" /></span>
<span className="text-base"><EMAIL></span>
</div>
<span className="text-red-500 cursor-pointer">Hanoi Office ứng phó với Covid-19</span>
</div>
</Typography>
<Typography variant="h6" >
<div className="pr-8">
<span className="text-base mx-2 cursor-pointer text-gray-500 hover:text-blue-500 mx-2">English</span>
<YouTube className="text-gray-500 hover:text-blue-500 mx-2" />
<Twitter className="text-gray-500 hover:text-blue-500 mx-2" />
<Pinterest className="text-gray-500 hover:text-blue-500 mx-2" />
<Facebook className="text-gray-500 hover:text-blue-500 mx-2" />
<Instagram className="text-gray-500 hover:text-blue-500 mx-2" />
<AccountCircle className="text-gray-500 hover:text-blue-500 ml-16 mr-4" />
</div>
</Typography>
</Toolbar>
</AppBar>
</div>
<div className={ classes.root }>
<AppBar position="static">
<Toolbar>
<Typography variant="h6" className={ classes.title } >
<ul className="flex pl-8">
{
router.map((item, index) => {
return (
<li key={ index } className="cursor-pointer hover:text-yellow-500 px-4 text-sm dropdown uppercase">
{ item.title }
{
item.subMenu.length > 0 &&
<ul className="dropdown-content">
{
item.subMenu.map((i, x) => {
return (
<NavLink key={ x } to={ i.subItem?.length > 0 ? '#' : i.subPath || '#' } >
<li className="py-2 text-white hover:text-yellow-500 text-sm hover-item dropdown-item w-full block">
<span className="hover-Icon"><ArrowRightAlt /></span>
<span>{ i.subTitle }</span>
{/* {
i.subItem?.length > 0 &&
<ul className="dropdown-content-item">
{
i.subItem.map((d, y) => {
return (
// <NavLink key={ y } to={ i.subPath || '#' } >
<li key={ y } className="py-2 text-white hover:text-yellow-500 text-sm hover-item-item">
<span className="hover-Icon-item"><ArrowRightAlt /></span>
<span>{ d.itemTitle }</span>
</li>
// </NavLink>
);
})
}
</ul>
} */}
</li>
</NavLink>
);
})
}
</ul>
}
</li>
);
})
}
</ul>
</Typography>
<Button variant="outlined" color="inherit" startIcon={ <Add /> }>Nhân tư vấn</Button>
</Toolbar>
</AppBar>
</div>
</div>
</>
);
};
export default Hearder;<file_sep>import React from 'react';
const EconomicNews = () => {
return (
<>
<h1>{ 'Viết code cho trang "Tin tức kinh tế" tại đây' }</h1>
</>
);
};
export default EconomicNews;<file_sep>import React from 'react';
import VirtualOffice from '../../component/service/VirtualOffice';
const ComponentCenter = () => {
return (
<>
<VirtualOffice />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
const ElectronicBill = () => {
return (
<>
<h1>{ 'Viết code cho trang "Hóa đơn điện tử" ở đây' }</h1>
</>
);
};
export default ElectronicBill;<file_sep>import React from 'react';
import {useRecoilValue} from 'recoil';
import {totalNumberDate, toThousandFilter, formatCurrency} from '../../../../helpers/helper';
import {orderBookFilterParams} from '../../../../store/actom/orderBook/orderBook';
const PaymentContinuous = () => {
const filterData = useRecoilValue(orderBookFilterParams);
const dataItemNew = filterData.listService.filter(i => i.checked);
console.log(filterData);
// const totalPaymentRoom = () => {
// if (filterData.startDate && filterData.endDate && filterData.listTime.length > 0) {
// return (filterData.valueType[0] ? filterData.valueType[0].priceTypeRoom : 0) * totalNumberDate(filterData.startDate, filterData.endDate) * filterData.listTime.length;
// }
// return 0;
// };
const total = () => {
if (filterData.startDate && filterData.endDate && filterData.listTime.length > 0) {
return (filterData.valueType.length > 0 ? filterData.valueType[0].priceTypeRoom : 0) * totalNumberDate(filterData.startDate, filterData.endDate) * filterData.listTime.length;
}
return 0;
};
const totalSetvice = () => {
if (filterData.startDate && filterData.endDate) {
return totalNumberDate(filterData.startDate, filterData.endDate) * (filterData.listService.filter(i => i.checked).length > 0 ? (filterData.listService.reduce((total, i) => {
return total += i.priceService;
}, 0)) : 0);
}
return 0;
};
return (
<>
<div className='mx-2 test-xs border-b-1 pb-8 mt-5'>
<h3 className='font-medium'>Giá phòng: </h3>
<div className='mx-6 mt-3'>
<div className='flex justify-between my-1'>
<p>{filterData.valueType.length > 0 ? filterData.valueType[0].name : ''}</p>
<p>{toThousandFilter(filterData.valueType[0] ? filterData.valueType[0].priceTypeRoom : 0)}</p>
</div>
<div className='flex justify-between my-1'>
<p>Số ca</p>
<p>x <span>{filterData.listTime.length}</span></p>
</div>
<div className='flex justify-between my-1'>
<p>Số ngày</p>
<p>x <span>{filterData.startDate && filterData.endDate ? totalNumberDate(filterData.startDate, filterData.endDate) : 0}</span>
</p>
</div>
<p className='border-b-1 mt-4 ml-36'></p>
<div className='flex justify-between mt-1'>
<p></p>
<p>=<span className='pl-6 font-medium'>{formatCurrency(total())}</span></p>
</div>
</div>
</div>
<div className='mx-2 test-xs pb-8 mt-8'>
<h3 className='font-medium'>Giá dịch vụ: </h3>
<div className='mx-6 mt-3'>
{
dataItemNew.map((item, index) => {
return (
<div className='flex justify-between my-1' key={ index }>
<p>{item.name}</p>
<p>{toThousandFilter(item.priceService)}</p>
</div>
);
})
}
<p className='border-b-1 mt-4 ml-36'></p>
<div className='flex justify-between mt-1'>
<p></p>
<p>x <span
className='pl-2 pr-4'>{filterData.startDate && filterData.endDate ? totalNumberDate(filterData.startDate, filterData.endDate) : 0} (ngày)</span> =<span
className='pl-2 font-medium'> {formatCurrency(totalSetvice())}</span></p>
</div>
</div>
</div>
</>
);
};
export default PaymentContinuous;<file_sep>import React from 'react';
import Box from '@material-ui/core/Box';
import PropTypes from 'prop-types';
const TabPanel = (props) => {
const { children, value, index, nav: Nav, ...other } = props;
return (
<div
role="tabpanel"
hidden={ value !== index }
id={ `full-width-tabpanel-${index}` }
aria-labelledby={ `full-width-tab-${index}` }
{ ...other }
>
<div>
{ <Nav /> }
</div>
{ value === index &&
<Box p={ 3 }>
<div>{ children }</div>
</Box>
}
</div>
);
};
TabPanel.propTypes = {
children: PropTypes.object,
index: PropTypes.any.isRequired,
value: PropTypes.any.isRequired,
nav: PropTypes.func
};
export default TabPanel;<file_sep>import React from 'react';
import Contact from '../../component/bookAnOffices/bookAnOffice';
const ComponentCenter = () => {
return (
<>
<Contact />
</>
);
};
export default ComponentCenter;<file_sep>import React from 'react';
import FormControl from '@material-ui/core/FormControl';
// import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import { makeStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
const useStyles = makeStyles((theme) => ({
button: {
display: 'block',
marginTop: theme.spacing(2),
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
}));
const day = new Date();
const thisYear = Number(day.getFullYear());
const listYears = () => {
const listArr = [];
for (let i = thisYear - 5; i < thisYear + 6; i++) {
listArr.push(i);
}
return listArr;
};
const DateYear = () => {
const classes = useStyles();
const [ year, setYear ] = React.useState(thisYear);
const [ open, setOpen ] = React.useState(false);
const handleChange = (event) => {
setYear(event.target.value);
};
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 4;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
width: 150,
},
},
};
return (
<>
<div className="flex items-center">
<p>Năm: </p>
<FormControl className={ classes.formControl }>
<Select
labelId="demo-controlled-open-select-label"
id="demo-controlled-open-select"
open={ open }
onClose={ handleClose }
onOpen={ handleOpen }
value={ year }
onChange={ handleChange }
MenuProps={ MenuProps }
>
{
listYears().map((item, index) => {
return (
<MenuItem key={ index } value={ item }>{ item }</MenuItem>
);
})
}
</Select>
</FormControl>
</div>
</>
);
};
DateYear.propTypes = {
filterParams: PropTypes.object,
title: PropTypes.string
};
export default DateYear;<file_sep>import React from 'react';
import Button from '@material-ui/core/Button';
import Step from '@material-ui/core/Step';
// import StepConnector from '@material-ui/core/StepConnector';
import StepLabel from '@material-ui/core/StepLabel';
import Stepper from '@material-ui/core/Stepper';
import {
makeStyles
} from '@material-ui/core/styles';
import Check from '@material-ui/icons/Check';
import GroupAddIcon from '@material-ui/icons/GroupAdd';
import SettingsIcon from '@material-ui/icons/Settings';
import VideoLabelIcon from '@material-ui/icons/VideoLabel';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import CustomerInfo from './CustomerInfo';
import RoomInfo from './RoomInfo';
import Rules from './Rules';
const useQontoStepIconStyles = makeStyles({
root: {
color: '#eaeaf0',
display: 'flex',
height: 22,
alignItems: 'center',
},
active: {
color: '#784af4',
},
circle: {
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: 'currentColor',
},
completed: {
color: '#784af4',
zIndex: 1,
fontSize: 18,
},
});
const QontoStepIcon = (props) => {
const classes = useQontoStepIconStyles();
const {active, completed} = props;
return (
<div
className={ clsx(classes.root, {
[classes.active]: active,
}) }
>
{completed ? <Check className={ classes.completed }/> : <div className={ classes.circle }/>}
</div>
);
};
QontoStepIcon.propTypes = {
/**
* Whether this step is active.
*/
active: PropTypes.bool,
/**
* Mark the step as completed. Is passed to child components.
*/
completed: PropTypes.bool,
};
const useColorlibStepIconStyles = makeStyles({
root: {
backgroundColor: '#ccc',
zIndex: 1,
color: '#fff',
width: 50,
height: 50,
display: 'flex',
borderRadius: '50%',
justifyContent: 'center',
alignItems: 'center',
},
active: {
backgroundImage:
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
boxShadow: '0 4px 10px 0 rgba(0,0,0,.25)',
},
completed: {
backgroundImage:
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
},
});
const ColorlibStepIcon = (props) => {
const classes = useColorlibStepIconStyles();
const {active, completed, handleNext} = props;
const icons = {
1: <SettingsIcon/>,
2: <GroupAddIcon/>,
3: <VideoLabelIcon/>,
};
return (
<div
className={ clsx(classes.root, {
[classes.active]: active,
[classes.completed]: completed,
}) }
onClick={ handleNext }
>
{icons[String(props.icon)]}
</div>
);
};
ColorlibStepIcon.propTypes = {
/**
* Whether this step is active.
*/
active: PropTypes.bool,
/**
* Mark the step as completed. Is passed to child components.
*/
completed: PropTypes.bool,
/**
* The label displayed in the step icon.
*/
icon: PropTypes.node,
handleNext: PropTypes.func
};
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
// textAlign: 'center'
margin: '0px 0 140px',
},
button: {
marginRight: theme.spacing(1),
},
instructions: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
},
}));
const getSteps = () => {
return ['Thông tin phòng chi tiết', 'Cập nhật thông tin cá nhân', 'Chấp nhận yêu cầu và chính sách'];
};
const CustomizedSteppers = ({setState}) => {
const getStepContent = (step) => {
switch (step) {
case 0:
return (<RoomInfo/>);
case 1:
return (<CustomerInfo/>);
case 2:
return (<Rules/>);
default:
return 'Unknown step';
}
};
const classes = useStyles();
const [activeStep, setActiveStep] = React.useState(0);
const steps = getSteps();
const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
};
const handleClick = (index) => {
setActiveStep(index);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
const handleReset = () => {
setActiveStep(0);
};
return (
<>
<div className='mt-4 pl-24 cursor-pointer hover:text-blue-800 text-blue-500' onClick={ () => setState('detail') }>
<p>{'<< Quay lại tìm kiếm'}</p>
</div>
<div className={ classes.root }>
<div className="flex justify-center">
<Stepper alternativeLabel activeStep={ activeStep }>
{steps.map((label, index) => (
<Step key={ index }>
<StepLabel onClick={ () => handleClick(index) } className='cursor-pointer'>{label}</StepLabel>
</Step>
))}
</Stepper>
</div>
<div>
{activeStep === steps.length ?
(<div>
<div>
{
'Tiến hành đăng ký'
}
</div>
<Button onClick={ handleReset } className={ classes.button }>
Đặt lại
</Button>
</div>
) : (<div>
<div>
{getStepContent(activeStep)}
<div className="flex justify-end">
<Button disabled={ activeStep === 0 } onClick={ handleBack } className={ classes.button }>
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={ handleNext }
className={ classes.button }
>
{activeStep === steps.length - 1 ? 'Tiến hành đặt' : 'Tiếp'}
</Button>
</div>
</div>
</div>)}
</div>
</div>
</>
);
};
CustomizedSteppers.propTypes = {
setState: PropTypes.func
};
export default CustomizedSteppers;
| 7cabbee88a6659349169b3309d4c4972b13fd512 | [
"JavaScript"
] | 179 | JavaScript | PhiHung226/hanoioffice_fontend | 74395440b13e0104ab1e56577730f20287b955bb | 4283b39950cb100157016aaedb1616767f0ad007 |
refs/heads/develop | <file_sep>// feature
import React from "react";
import data from "./data.json";
import Products from "./components/Products";
import Filter from "./components/Filter";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
products: data.products,
size: "",
sort: "",
};
}
sortProducts(event) {
let products = this.state.products;
if (this.state.sort === "lowest") {
products.sort((a, b) => a.price - b.price);
} else if (this.state.sort === "highest") {
products.sort((a, b) => b.price - a.price);
}
this.setState({ products });
}
filterProducts = (event) => {
};
render() {
return (
<div className="App">
<div className="grid-container">
<header>
<a href="/">Lusama Shop</a>
</header>
<main>
<div className="content">
<div className="main">
<Filter
count={this.state.products.length}
size={this.state.size}
sort={this.state.sort}
filterProducts={this.filterProducts}
sortProducts={this.sortProducts}
/>
<Products products={this.state.products} />
</div>
<div className="sidebar">Cart Items</div>
</div>
</main>
<footer>Alll rights reserved.</footer>
</div>
</div>
);
}
}
export default App;
| d593496a8d23cad3af1b4eb7ba0778f258334f69 | [
"JavaScript"
] | 1 | JavaScript | tnyandoro/react-lusama-app | e882f33a791ad938d5b706f3f3a70caa3d04eefa | a5474a210145a03fe7bfe2ef14b6f23507580ff8 |
refs/heads/master | <repo_name>crazy653555/ToDoList2<file_sep>/src/app/data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/do'
import { NotifyService } from './notify.service';
@Injectable()
export class DataService {
constructor(
private http: HttpClient,
private notifySvc: NotifyService
) { }
private apiBase = 'http://localhost:3000/todos';
getTodos() {
return this.http.get<any[]>(this.apiBase);
}
addTodo(todo) {
return this.http.post(this.apiBase, todo)
.do(data => {
this.notifySvc.notify(`已經 ${todo.text} 新增到 DB`);
});
}
removeTodo(todo) {
return this.http.delete(`${this.apiBase}/${todo.id}`)
.do(data => {
this.notifySvc.notify(`已將 ${todo.text} 從 DB 刪除`);
});
}
updateTodo(todo) {
return this.http.put(`${this.apiBase}/${todo.id}`, todo)
.do(data => {
this.notifySvc.notify(`已將 ${todo.text} 從 DB 更新`);
});
}
}
<file_sep>/src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
inputHint = 'What needs to be done?';
colspan = 3;
todos: any[] = [];
todo = '';
filterType = 'All';
isToggleAll = true;
constructor(private dataSvc: DataService
) {
}
ngOnInit(): void {
this.dataSvc.getTodos()
.subscribe(data => {
this.todos = data;
});
}
addTodo() {
if (this.todo) {
const newTodo = {
text: this.todo,
done: false
};
this.dataSvc.addTodo(newTodo)
.subscribe(data => {
console.log(data);
this.todos = this.todos.concat(data);
this.todo = '';
});
}
}
clearCompleted() {
this.todos.filter(item => item.done).forEach(item => this.removeTodo(item));
}
updateFilterType($event) {
this.filterType = $event;
}
toggleAll() {
this.todos.forEach(item => {
item.done = this.isToggleAll;
this.updateTodo(item);
});
}
removeTodo(todo) {
console.log('select:' + todo.id);
this.dataSvc.removeTodo(todo)
.subscribe(data => {
this.todos = this.todos.filter(item => item !== todo);
});
}
z
updateTodo(todo) {
this.dataSvc.updateTodo(todo)
.subscribe(data => {
this.todos = [...this.todos];
});
}
enterEditMode(todo) {
console.log(todo);
todo.editText = todo.text;
todo.isEditMode = true;
}
leaveEditMode(todo) {
delete todo.editText;
delete todo.isEditMode;
this.updateTodo(todo);
}
saveEdit(todo) {
todo.text = todo.editText;
this.leaveEditMode(todo);
}
}
| d52435949bc0ef06294d3f63b7c63a801adf9c01 | [
"TypeScript"
] | 2 | TypeScript | crazy653555/ToDoList2 | ca9607a637ec614a5cc21b195544dd259bdd5d70 | 550d45822e39cf165b232aa3db917dfb163474f7 |
refs/heads/master | <repo_name>mirkokroese/AoDemoGame<file_sep>/server/gameobjects/Player.js
'use strict';
var Player = function (_userName)
{
this.userName = _userName;
this.xPos = 0;
this.yPos = 0;
}
// getters and setters
Player.prototype.getUserName = function ()
{
return this.userName;
}
Player.prototype.setUserName = function (_userName)
{
this.userName = _userName;
}
Player.prototype.setYPos = function(_yPos)
{
this.Ypos =_Ypos;
}
Player.prototype.getYPos = function(_yPos)
{
return this.yPos;
}
Player.prototype.setXPos = function(_xPos)
{
this.xPos =_xPos;
}
Player.prototype.getXPos = function(_xPos)
{
return this.xPos;
}
// Export the whole player object
module.exports.Player = Player;<file_sep>/public/client/clientHelpers.js
// Element getters
function getID(id) {
return document.getElementById(id);
}
// function getClass(class) {
// return document.getElementByClass(class);
// }
// HTML setters
function addHTML(element, html) {
element.innerHTML += html;
}
function setHTML(element, html) {
element.innerHTML = html;
}
// Element displaying
function showElement(element) {
element.style.display = "block";
}
function removeElement(element) {
element.style.display = "none";
}<file_sep>/server/queue/QueueHandler.js
'use strict';
var QueueHandler = function ()
{
this.queuedPlayers = [];
}
QueueHandler.prototype.addPlayer = function (player)
{
this.queuedPlayers.push(player);
}
QueueHandler.prototype.removePlayer = function (position)
{
this.queuedPlayers.splice(position, 1);
}
QueueHandler.prototype.getQueue = function ()
{
return this.queuedPlayers;
}
QueueHandler.prototype.moveQueue = function ()
{
}
// Export the whole queueHandler
module.exports.QueueHandler = QueueHandler;<file_sep>/server/connection/ConnectionHandler.js
'use strict';
var ConnectionHandler = function (_socket, _server, _player)
{
// Store parameters in object properties
this.server = _server;
this.player = _player;
// Create a global variable for the socket so it can be used everywhere in this object
var socket = _socket;
// Add player object to the queue
this.server.queueHandler.addPlayer(this.player);
// Send a message to all clients with the joined player object and the amound of clients in the queue
socket.broadcast.emit('player_joined_queue', this.player, this.server.queueHandler.getQueue().length);
var queueLength = this.server.queueHandler.getQueue().length;
for (var i = 0; i < queueLength; i++) {
if (this.player == this.server.queueHandler.getQueue()[i]) {
var position = i+1;
}
}
socket.emit('reveice_waiting_time', this.server.queueHandler.countWaitingTime(position, this.server.gameTime, this.server.playersInGame));
// socket.broadcast.emit('reveice_waiting_time', this.server.queueHandler.countWaitingTime(i+1, this.server.gameTime, this.server.playersInGame));
var that = this; // create a global variable for the ConnectionHandler object
socket.on('disconnect', function () {
var queue = that.server.queueHandler.getQueue(); // Put the queue array in a variable
var queueLength = queue.length;
// Loop through the queue to find the disconnected user
for (var i = 0; i < queueLength; i++) {
if (queue[i] == that.player) {
console.log("disconnected user:", queue[i].userName); // Log the disconnected user to the server console
that.server.queueHandler.removePlayer(i);
// Player left queue
socket.broadcast.emit('player_left_queue', that.server.queueHandler.getQueue().length); // Broadcast a message to all clients with the new amount of players in the queue
}
}
});
}
// Export the whole ConnectionHandler object
module.exports.ConnectionHandler = ConnectionHandler;<file_sep>/public/client/monitor/client.js
window.onload = function () {
var socket = io.connect('http://192.168.127.12:80');
var queue_count = getID('queue_count');
socket.on('player_joined_queue', function(player, queueCount) {
var playerUsername = player.userName;
console.log(playerUsername, 'connected');
queue_count.innerHTML = queueCount;
});
socket.on('player_left_queue', function(queueCount) {
queue_count.innerHTML = queueCount;
});
}<file_sep>/public/client/controller/client.js
window.onload = function () {
/*-- ELEMENTS --*/
// Welcome
var inp_username = getID('inp_username');
var btn_join_queue = getID('btn_join_queue');
// Queue
var span_timer = getID('timer');
var span_queuecount = getID('queuecount');
// Message
var error_box = getID('error_box');
/*-- CLIENT LOGIC --*/
// On button click
btn_join_queue.onclick = function () {
// Retrieve the clients username
var username = inp_username.value;
// @TODO: validate user input
if(username.length < 3) {
addError('Username does not have a valid length');
}
// Connect to the server
var socket = io.connect('http://172.16.58.3:80');
// Send a message to the server that a client has joined the queue
socket.emit('client_join_queue', username);
// Load the queue elements
loadQueueView();
var timerValue = 0;
span_timer.innerHTML = timerValue;
// When a client joins the queue
socket.on('player_entered_queue', function (queueCount) {
span_queuecount.innerHTML = "Players in queue:" + queueCount;
});
// Receiving the waiting time
socket.on('receive_waiting_time', function (waitingTime) {
timerValue = waitingTime;
var _timing = setInterval(function () {
timerValue -= 1;
span_timer.innerHTML = timerValue;
}, 1000);
});
}
// functions
function loadQueueView() {
removeElement(inp_username);
removeElement(btn_join_queue);
showElement(span_timer);
showElement(span_queuecount);
}
function addError(errorMessage)
{
error_box.innerHTML = "Error: " + errorMessage;
}
} | c0d9bba1874ea3f87ad4df863d5ac98380d28090 | [
"JavaScript"
] | 6 | JavaScript | mirkokroese/AoDemoGame | 5fe40549d9a2c90679afff252ffb2b68751beb56 | bdf83d30fe14abf3108842893aea7993c5918892 |
refs/heads/master | <file_sep>using System;
using ConformingContainerAntipattern._3_ConformingContainer.Core;
using ConformingContainerAntipattern._3_ConformingContainer.InMessages;
using ConformingContainerAntipattern._3_ConformingContainer.Inbound;
using ConformingContainerAntipattern._3_ConformingContainer.Outbound;
using ConformingContainerAntipattern._3_ConformingContainer.Services;
namespace ConformingContainerAntipattern._3_ConformingContainer
{
public static class ApplicationRoot
{
static ApplicationRoot()
{
Context.For<IProcessingWorkflow>().UseAlwaysTheSame<AcmeProcessingWorkflow>();
Context.For<IInbound>().UseAlwaysTheSame<BinaryUdpInbound>();
Context.For<IInputSocket>().UseAlwaysTheSame<UdpSocket>();
Context.For<IOutputSocket>().UseAlwaysTheSame<TcpSocket>();
Context.For<IPacketParsing>().UseAlwaysTheSame<BinaryParsing>();
Context.For<IOutbound>().UseAlwaysTheSame<Outbound.Outbound>();
Context.For<IAuthorization>().UseAlwaysTheSame<ActiveDirectoryBasedAuthorization>();
Context.For<IRepository>().UseAlwaysTheSame<MsSqlBasedRepository>();
Context.For<IMarshalling>().UseAlwaysTheSame<XmlMarshalling>();
Context.UseAlwaysTheSame<SqlDataDestination>();
//not container controlled
Context.For<IOutboundMessage>().UseEachTimeNew<OutboundMessage>();
Context.For<Random>().UseInstancesCreatedWith(container => new Random());
Context.UseEachTimeNew<NullMessage>();
Context.UseEachTimeNew<StartMessage>();
Context.UseEachTimeNew<StopMessage>();
}
public static void Main(string[] args)
{
try
{
var sys = new TeleComSystem(); //uses container inside, but should be resolved itself!
sys.Start();
}
finally
{
Context.Dispose();
}
}
//simplified
public static readonly ConformingContainer Context = new ConformingContainer();
}
}
<file_sep>using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Interfaces;
namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Services
{
internal interface IRepository
{
void Save(AcmeMessage message);
}
class MsSqlBasedRepository : IRepository
{
private readonly DataDestination _sqlDataDestination;
public MsSqlBasedRepository(DataDestination sqlDataDestination)
{
_sqlDataDestination = sqlDataDestination;
}
public void Save(AcmeMessage message)
{
message.WriteTo(_sqlDataDestination);
}
}
}<file_sep>using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Core;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Inbound;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Interfaces;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Outbound;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Services;
using Microsoft.Practices.Unity;
namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection
{
public class ApplicationRoot
{
public void Main_BareConstructors()
{
var sys = new TeleComSystem(
new MessageInbound(
new UdpSocket(),
new BinaryParsing()),
new MessageOutbound(
new TcpSocket(),
new XmlOutboundMessageFactory()),
new AcmeProcessingWorkflow(
new ActiveDirectoryBasedAuthorization(),
new MsSqlBasedRepository(
new SqlDataDestination())));
sys.Start();
}
public void Main_FluentInterfaceWay()
{
//Growing Object Oriented Software Guided By Tests
//Building on SOLID Foundations
var sys = ASystemThat(
ReceivesMessages(
ViaUdp(),
InBinaryFormat()),
AndThen(
AuthenticatesThemViaActiveDirectory(),
PersistsInSqlDatabase()),
AndSendsThem(ViaTcp(), AsXml()));
sys.Start();
}
public void Main_IoC_Container()
{
using (var container = new UnityContainer())
{
//Register
container
.RegisterType<DataDestination, SqlDataDestination>(
new ContainerControlledLifetimeManager()
)
.RegisterType<IRepository, MsSqlBasedRepository>()
.RegisterType<IAuthorization, ActiveDirectoryBasedAuthorization>()
.RegisterType<IAcmeProcessingWorkflow, AcmeProcessingWorkflow>()
.RegisterType<IOutboundMessageFactory, XmlOutboundMessageFactory>()
.RegisterType<ISocket, TcpSocket>()
.RegisterType<IOutbound, MessageOutbound>()
.RegisterType<IParsing, BinaryParsing>()
.RegisterType<IInboundSocket, UdpSocket>()
.RegisterType<IInbound, MessageInbound>()
.RegisterType<TeleComSystem>();
//////// Only one Resolve() call after this line! ////////////
//Resolve
var system = container.Resolve<TeleComSystem>();
system.Start();
} //Release
}
private static MsSqlBasedRepository PersistsInSqlDatabase()
{
return new MsSqlBasedRepository(
new SqlDataDestination());
}
private static ActiveDirectoryBasedAuthorization AuthenticatesThemViaActiveDirectory()
{
return new ActiveDirectoryBasedAuthorization();
}
private AcmeProcessingWorkflow AndThen(ActiveDirectoryBasedAuthorization activeDirectoryBasedAuthorization, MsSqlBasedRepository msSqlBasedRepository)
{
return new AcmeProcessingWorkflow(activeDirectoryBasedAuthorization, msSqlBasedRepository);
}
private static XmlOutboundMessageFactory AsXml()
{
return new XmlOutboundMessageFactory();
}
private static TcpSocket ViaTcp()
{
return new TcpSocket();
}
private MessageOutbound AndSendsThem(TcpSocket tcpSocket, XmlOutboundMessageFactory xmlOutboundMessageFactory)
{
return new MessageOutbound(tcpSocket, xmlOutboundMessageFactory);
}
private static BinaryParsing InBinaryFormat()
{
return new BinaryParsing();
}
private static UdpSocket ViaUdp()
{
return new UdpSocket();
}
private MessageInbound ReceivesMessages(UdpSocket udpSocket, BinaryParsing binaryParsing)
{
return new MessageInbound(udpSocket, binaryParsing);
}
private TeleComSystem ASystemThat(MessageInbound messageInbound, AcmeProcessingWorkflow acmeProcessingWorkflow, MessageOutbound messageOutbound)
{
return new TeleComSystem(messageInbound, messageOutbound, acmeProcessingWorkflow);
}
}
}
<file_sep>using System;
namespace NullAsFlagRefactored
{
class Program2
{
static void Main2(string[] args)
{
var myNotificationsEngine = new MyNotificationsEngine();
var localDataCenter = new DataCenter();
var remoteDataCenter = new DataCenter();
var myController = new MyController(
myNotificationsEngine,
localDataCenter,
remoteDataCenter);
//somewhere
myController.HandleMessageFromUser("message1");
//somewhere else
myController.HandleReplicatedMessage("message2");
}
}
internal class MyController
{
private readonly MyNotificationsEngine _myNotificationsEngine;
private readonly IDataCenter _localDataCenter;
private readonly IDataCenter _remoteDataCenter;
public MyController(
MyNotificationsEngine myNotificationsEngine,
IDataCenter localDataCenter,
IDataCenter remoteDataCenter)
{
_myNotificationsEngine = myNotificationsEngine;
_localDataCenter = localDataCenter;
_remoteDataCenter = remoteDataCenter;
}
public void HandleMessageFromUser(string message)
{
_myNotificationsEngine.NotifyNewData(_localDataCenter, _remoteDataCenter, message);
}
public void HandleReplicatedMessage(string message)
{
_myNotificationsEngine.NotifyNewData(
_localDataCenter,
new IgnoreThisDataCenter(),
message);
}
}
internal class IgnoreThisDataCenter : IDataCenter
{
public void Send(string message)
{
//EMPTY
}
}
public interface IDataCenter
{
void Send(string message);
}
public class DataCenter : IDataCenter
{
public void Send(string message)
{
Console.WriteLine(message);
}
}
internal class MyNotificationsEngine
{
public void NotifyNewData(
IDataCenter localDataCenter,
IDataCenter remoteDataCenter,
string message)
{
localDataCenter.Send(message);
remoteDataCenter.Send(message);
}
}
}
<file_sep>using DependencyInjectionBefore._1_ControlFreak.Interfaces;
namespace DependencyInjectionBefore._1_ControlFreak.Outbound
{
class XmlTcpOutbound
{
private readonly TcpSocket _outputSocket;
public XmlTcpOutbound()
{
_outputSocket = new TcpSocket();
}
public void Send(AcmeMessage message)
{
var outboundMessage = new XmlOutboundMessage();
message.WriteTo(outboundMessage);
outboundMessage.SendVia(_outputSocket);
}
}
}<file_sep>namespace View.Ports
{
public interface IDomainLogic
{
void HandleAddEmployeeRequest();
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public interface Train
{
void Reserve(in uint seatCount, SearchEngine searchEngine, ReservationInProgress reservationInProgress);
bool HasCapacityForReservationsInAdvance();
}
}<file_sep>using System;
using NSubstitute;
using TddXt.AnyRoot.Numbers;
using TddXt.AnyRoot.Strings;
using Xunit;
using static TddXt.AnyRoot.Root;
namespace KataTrainReservationTddEbook
{
public class TrainReservationCommand : ReservationCommand
{
private readonly string _trainId;
private readonly uint _seatCount;
private readonly Trains _trains;
private readonly SearchEngine _searchEngine;
private readonly ReservationInProgress _reservationInProgress;
public TrainReservationCommand(string trainId, uint seatCount, Trains trains, SearchEngine searchEngine,
ReservationInProgress reservationInProgress)
{
_trainId = trainId;
_seatCount = seatCount;
_trains = trains;
_searchEngine = searchEngine;
_reservationInProgress = reservationInProgress;
}
public void Execute()
{
var train = _trains.RetrieveBy(_trainId);
if (train.HasCapacityForReservationsInAdvance())
{
train.Reserve(_seatCount, _searchEngine, _reservationInProgress);
_trains.Update(train);
}
else
{
_reservationInProgress.NoRoomInTrainFor(_seatCount);
}
}
}
public class TrainReservationCommandSpecification
{
[Fact]
public void ShouldDOWHAT1()
{
//GIVEN
var reservationInProgress = Any.Instance<ReservationInProgress>();
var seatCount = Any.UnsignedInt();
var train = Substitute.For<Train>();
var trains = Substitute.For<Trains>();
var trainId = Any.String();
var searchEngine = Substitute.For<SearchEngine>();
var command = new TrainReservationCommand(
trainId,
seatCount,
trains,
searchEngine,
reservationInProgress);
trains.RetrieveBy(trainId).Returns(train);
train.HasCapacityForReservationsInAdvance().Returns(true);
//WHEN
command.Execute();
//THEN
Received.InOrder(() =>
{
train.Reserve(seatCount, searchEngine, reservationInProgress);
trains.Update(train);
});
}
[Fact]
public void ShouldDOWHAT2()
{
//GIVEN
var reservationInProgress = Substitute.For<ReservationInProgress>();
var seatCount = Any.UnsignedInt();
var train = Substitute.For<Train>();
var trains = Substitute.For<Trains>();
var trainId = Any.String();
var searchEngine = Substitute.For<SearchEngine>();
var command = new TrainReservationCommand(
trainId,
seatCount,
trains,
searchEngine,
reservationInProgress);
trains.RetrieveBy(trainId).Returns(train);
train.HasCapacityForReservationsInAdvance().Returns(false);
//WHEN
command.Execute();
//THEN
reservationInProgress.Received(1).NoRoomInTrainFor(seatCount);
}
}
}<file_sep>using System;
using Microsoft.Practices.Unity;
namespace ConformingContainerAntipattern._3_ConformingContainer
{
public class ConformingContainer : IDisposable
{
readonly IUnityContainer _container = new UnityContainer();
public For<T> For<T>()
{
return new For<T>(_container, this);
}
public void UseAlwaysTheSame<T>()
{
For<T>().UseAlwaysTheSame<T>();
}
public void UseEachTimeNew<T>()
{
For<T>().UseEachTimeNew<T>();
}
public void Dispose()
{
_container.Dispose();
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
public class For<T>
{
private readonly IUnityContainer _container;
private readonly ConformingContainer _conformingContainer;
public For(IUnityContainer container, ConformingContainer conformingContainer)
{
_container = container;
_conformingContainer = conformingContainer;
}
public void UseAlwaysTheSame<U>() where U : T
{
_container.RegisterType<T, U>(new ContainerControlledLifetimeManager());
}
public void UseEachTimeNew<U>() where U : T
{
_container.RegisterType<T, U>();
}
public void UseInstancesCreatedWith(Func<ConformingContainer, T> factory)
{
_container.RegisterType<T>(new InjectionFactory(container => factory(_conformingContainer)));
}
public void Use(T instance)
{
_container.RegisterInstance(instance);
}
}
}<file_sep>using System;
using DependencyInjectionBefore._1_ControlFreak.Interfaces;
namespace DependencyInjectionBefore._1_ControlFreak.Services
{
class SqlDataDestination : DataDestination
{
public void Add(string s)
{
throw new NotImplementedException();
}
}
}<file_sep>using ServiceLocatorDIAntipattern._2_ServiceLocator.InMessages;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Interfaces;
using Microsoft.Practices.Unity;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.Inbound
{
internal interface IPacketParsing
{
AcmeMessage ResultFor(byte[] frameData);
}
class BinaryParsing : IPacketParsing
{
public AcmeMessage ResultFor(byte[] frameData)
{
if (frameData == null)
{
return ApplicationRoot.Context.Resolve<NullMessage>();
}
else if (frameData[0] == 1)
{
return ApplicationRoot.Context.Resolve<StartMessage>();
}
else
{
return ApplicationRoot.Context.Resolve<StopMessage>();
}
}
}
}<file_sep>using System;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Interfaces;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Services;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.InMessages
{
class StopMessage : AcmeMessage
{
public void AuthorizeUsing(IAuthorization authorizationRules)
{
Console.WriteLine("Authorizing Stop with " + authorizationRules);
}
public void WriteTo(DataDestination dataDestination)
{
Console.WriteLine("Writing Stop to " + dataDestination);
}
}
}<file_sep>using System;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Interfaces;
namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Services
{
class SqlDataDestination : DataDestination
{
public void Add(string s)
{
throw new NotImplementedException();
}
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public interface ReservationInProgress
{
ReservationDto ToDto();
void NoRoomInTrainFor(in uint seatCount);
void NoMatchingCoachFoundFor(in uint seatCount);
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.Core;
namespace DependencyInjectionBefore._1_ControlFreak
{
public class ApplicationRoot
{
public void Main()
{
var sys = new TeleComSystem();
sys.Start();
}
public void Main_IoC_Container()
{
//TODO mention RRR pattern
var sys = new TeleComSystem();
sys.Start();
}
}
}
<file_sep>using System;
using Autofac;
using NUnit.Framework;
namespace IoCContainerCons
{
public class EventsAndOnActivatedOnReleased
{
[Test]
public void ShouldShowHandMadeHandlingOfEvents()
{
//GIVEN
var builder = new ContainerBuilder();
builder.RegisterType<MyObserver>().SingleInstance();
builder.RegisterType<MyDependency>().InstancePerDependency()
.OnActivated(args =>
args.Instance.SomeKindOfEvent += args.Context.Resolve<MyObserver>().Notify);
using var container = builder.Build();
//WHEN
var observer = container.Resolve<MyObserver>();
var dependency1 = container.Resolve<MyDependency>();
var dependency2 = container.Resolve<MyDependency>();
var dependency3 = container.Resolve<MyDependency>();
//THEN
dependency1.DoSomething();
Assert.AreEqual(dependency1.InstanceId, observer.LastReceived);
dependency2.DoSomething();
Assert.AreEqual(dependency2.InstanceId, observer.LastReceived);
dependency3.DoSomething();
Assert.AreEqual(dependency3.InstanceId, observer.LastReceived);
}
[Test]
public void ShouldShowHandMadeHandlingOfEventsWithManualComposition()
{
//GIVEN
var observer = new MyObserver();
var dependency1 = new MyDependency();
var dependency2 = new MyDependency();
var dependency3 = new MyDependency();
//WHEN
dependency1.SomeKindOfEvent += observer.Notify;
dependency2.SomeKindOfEvent += observer.Notify;
dependency3.SomeKindOfEvent += observer.Notify;
//THEN
dependency1.DoSomething();
Assert.AreEqual(dependency1.InstanceId, observer.LastReceived);
dependency2.DoSomething();
Assert.AreEqual(dependency2.InstanceId, observer.LastReceived);
dependency3.DoSomething();
Assert.AreEqual(dependency3.InstanceId, observer.LastReceived);
}
}
public class MyObserver
{
public void Notify(int value)
{
LastReceived = value;
}
public int LastReceived { get; set; }
}
public class MyDependency
{
private static int _lastInstanceId = 0;
public int InstanceId { get; }
public MyDependency()
{
InstanceId = _lastInstanceId++;
}
public event Action<int> SomeKindOfEvent;
public void DoSomething()
{
SomeKindOfEvent?.Invoke(InstanceId);
}
}
}
<file_sep>namespace DependencyInjectionBefore._1_ControlFreak.Interfaces
{
interface DataDestination
{
void Add(string s);
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChangingBehaviorThroughComposition
{
public class Building
{
private readonly Alarm _alarm;
public Building(Alarm alarm)
{
_alarm = alarm;
}
public void SomeoneCameIn()
{
_alarm.Trigger();
}
public void SituationIsClear()
{
_alarm.Disable();
}
}
}
<file_sep>using System;
namespace KataTrainReservationTddEbook
{
public class DtoBasedReservationInProgress : ReservationInProgress
{
public ReservationDto ToDto()
{
throw new NotImplementedException();
}
public void NoRoomInTrainFor(in uint seatCount)
{
throw new NotImplementedException();
}
public void NoMatchingCoachFoundFor(in uint seatCount)
{
throw new NotImplementedException();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Domain;
namespace Gui
{
public class Window
{
private readonly DomainLogic _logic = new DomainLogic();
public void OnSubmitClicked()
{
_logic.HandleAddEmployeeRequest();
}
}
}
<file_sep>using BastardInjection._4_BastardInjection.Interfaces;
namespace BastardInjection._4_BastardInjection.Services
{
public interface IRepository
{
void Save(AcmeMessage message);
}
public class MsSqlBasedRepository : IRepository
{
private readonly DataDestination _dataDestination;
public MsSqlBasedRepository() : this(new SqlDataDestination())
{
}
//for tests
public MsSqlBasedRepository(DataDestination dataDestination)
{
_dataDestination = dataDestination;
}
public void Save(AcmeMessage message)
{
message.WriteTo(_dataDestination);
}
}
}<file_sep>using System;
using System.IO;
using System.Linq;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Castle.DynamicProxy;
using NUnit.Framework;
namespace IoCContainerPros
{
public class Interception
{
[Test]
public void ShouldEnableInterception()
{
var containerBuilder = new ContainerBuilder();
containerBuilder
.RegisterType<Lol2>().As<ILol2>()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(CallLogger));
containerBuilder.RegisterType<CallLogger>();
using (var container = containerBuilder.Build())
{
var lol2 = container.Resolve<ILol2>();
lol2.DoSomething();
}
}
}
public interface ILol2
{
void DoSomething();
}
public class Lol2 : ILol2
{
public void DoSomething()
{
}
}
public class CallLogger : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Called " + invocation.Method.Name);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
namespace IoCContainerCons
{
public class Lol
{
public void DoWork()
{
var yearlyReport = new YearlyReport();
yearlyReport.Setup();
yearlyReport.Print();
var monthlyReport = new MonthlyReport();
monthlyReport.Setup();
monthlyReport.Print();
}
}
public abstract class AbstractReport
{
private readonly List<string> _lines = new List<string>();
public void Setup()
{
AddLine($"This is a {Period()} report");
FillTheRestOfTheReport();
}
public void Print()
{
Console.WriteLine(Period().ToUpperInvariant() + string.Join(Environment.NewLine, _lines));
}
protected void AddLine(string line)
{
Console.WriteLine($"Added {line}");
_lines.Add(line);
}
protected abstract void FillTheRestOfTheReport();
protected abstract string Period();
}
public class YearlyReport : AbstractReport
{
protected override void FillTheRestOfTheReport()
{
AddLine("We're not on the market a full year yet.");
}
protected override string Period()
{
return "yearly";
}
}
public class MonthlyReport : AbstractReport
{
protected override void FillTheRestOfTheReport()
{
var incomes = MonthlyIncomes.PullDataForLastMonth();
foreach (var income in incomes)
{
AddLine(income);
}
}
protected override string Period()
{
return "monthly for" + DateTime.Now.Month;
}
}
public static class MonthlyIncomes
{
public static List<string> PullDataForLastMonth()
{
return new List<string>() {"1", "2"};
}
}
}
<file_sep>using ConformingContainerAntipattern._3_ConformingContainer.Interfaces;
namespace ConformingContainerAntipattern._3_ConformingContainer.Outbound
{
public interface IOutbound
{
void Send(AcmeMessage message);
}
public class Outbound : IOutbound
{
private readonly IOutputSocket _outputOutputSocket;
public Outbound()
{
_outputOutputSocket = ApplicationRoot.Context.Resolve<IOutputSocket>();
}
public void Send(AcmeMessage message)
{
var outboundMessage = ApplicationRoot.Context.Resolve<IOutboundMessage>();
message.WriteTo(outboundMessage);
outboundMessage.SendVia(_outputOutputSocket);
}
}
}<file_sep>using BastardInjection._4_BastardInjection.Interfaces;
using BastardInjection._4_BastardInjection.Outbound;
using BastardInjection._4_BastardInjection.Services;
namespace BastardInjection._4_BastardInjection.Core
{
internal interface IProcessingWorkflow
{
void SetOutbound(IOutbound outbound);
void ApplyTo(AcmeMessage message);
}
class AcmeProcessingWorkflow : IProcessingWorkflow
{
private readonly IRepository _repository;
private readonly IAuthorization _authorizationRules;
private IOutbound _outbound;
public AcmeProcessingWorkflow() : this(new ActiveDirectoryBasedAuthorization(), new MsSqlBasedRepository())
{
}
//for tests
private AcmeProcessingWorkflow(IAuthorization authorization, IRepository repository)
{
_authorizationRules = authorization;
_repository = repository;
}
public void SetOutbound(IOutbound outbound)
{
_outbound = outbound;
}
public void ApplyTo(AcmeMessage message)
{
message.AuthorizeUsing(_authorizationRules);
_repository.Save(message);
_outbound.Send(message);
}
}
}<file_sep>using Functional.Maybe;
namespace NullAsNothingRefactored
{
class Program
{
static void Main(string[] args)
{
var mySystem = new MySystem(
new UsersCache(),
new RadioCache(),
new GroupCache());
Maybe<QueryResult> maybeResult = mySystem.QueryWith(WhateverQuery());
if (maybeResult.HasValue)
{
maybeResult.Value.SendToUser();
}
}
private static QueryForData WhateverQuery()
{
return new QueryForData()
{
EntityId = "trolololo",
EntityType = EntityTypes.Radio
};
}
}
internal class QueryForData
{
public EntityTypes EntityType { get; set; }
public string EntityId { get; set; }
}
}
<file_sep>namespace DependencyInjectionBefore._1_ControlFreak.Services
{
class ActiveDirectoryBasedAuthorization
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Autofac;
using Autofac.Core.Registration;
using NUnit.Framework;
namespace IoCContainerPros
{
public class AssemblyScanning
{
[Test]
public void ShouldBeAbleToResolveBasedOnConvention()
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().SingleInstance();
using (var container = builder.Build())
{
var i1 = container.Resolve<Interface1>();
var i2 = container.Resolve<Interface2>();
Assert.IsInstanceOf<MyRepository>(i1);
Assert.IsInstanceOf<MyRepository>(i2);
Assert.AreEqual(i2, i1);
Assert.Throws<ComponentNotRegisteredException>(
() => container.Resolve<MyRepository2>()); //not following convention
}
}
}
public interface Interface1
{
}
public interface Interface2
{
}
public class MyRepository : Interface1, Interface2
{
}
public class MyRepository2 : Interface1, Interface2
{
}
}
<file_sep>using DataAccess.Ports;
namespace Gui
{
public class Window
{
readonly IDomainLogic _logic;
public Window(IDomainLogic domainLogic)
{
_logic = domainLogic;
}
public void OnSubmitClicked()
{
_logic.HandleAddEmployeeRequest();
}
}
}
<file_sep>using ConformingContainerAntipattern._3_ConformingContainer.Core;
namespace ConformingContainerAntipattern._3_ConformingContainer.Inbound
{
internal interface IInbound
{
void SetDomainLogic(IProcessingWorkflow processingWorkflow);
void StartListening();
}
class BinaryUdpInbound : IInbound
{
private IProcessingWorkflow _processingWorkflow;
private readonly IInputSocket _socket;
private readonly IPacketParsing _parsing;
public BinaryUdpInbound()
{
_socket = ApplicationRoot.Context.Resolve<IInputSocket>();
_parsing = ApplicationRoot.Context.Resolve<IPacketParsing>();
}
public void SetDomainLogic(IProcessingWorkflow processingWorkflow)
{
_processingWorkflow = processingWorkflow;
}
public void StartListening()
{
byte[] frameData;
while (_socket.Receive(out frameData))
{
var message = _parsing.ResultFor(frameData);
if (message != null)
{
if (_processingWorkflow != null)
{
_processingWorkflow.ApplyTo(message);
}
}
}
}
}
}<file_sep>using System;
using Microsoft.Practices.Unity;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Core;
using ServiceLocatorDIAntipattern._2_ServiceLocator.InMessages;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Inbound;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Outbound;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Services;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator
{
public class ApplicationRoot
{
static ApplicationRoot()
{
Context.RegisterType<IProcessingWorkflow, AcmeProcessingWorkflow>(new ContainerControlledLifetimeManager());
Context.RegisterType<IInbound, BinaryUdpInbound>(new ContainerControlledLifetimeManager());
Context.RegisterType<IInputSocket, UdpSocket>(new ContainerControlledLifetimeManager());
Context.RegisterType<IOutputSocket, TcpSocket>(new ContainerControlledLifetimeManager());
Context.RegisterType<IPacketParsing, BinaryParsing>(new ContainerControlledLifetimeManager());
Context.RegisterType<IOutbound, Outbound.Outbound>(new ContainerControlledLifetimeManager());
Context.RegisterType<IAuthorization, ActiveDirectoryBasedAuthorization>(new ContainerControlledLifetimeManager());
Context.RegisterType<IRepository, MsSqlBasedRepository>(new ContainerControlledLifetimeManager());
// forgot about this... Context.RegisterType<IMarshalling, XmlMarshalling>(new ContainerControlledLifetimeManager());
Context.RegisterType<SqlDataDestination>(new ContainerControlledLifetimeManager());
//not container controlled
Context.RegisterType<IOutboundMessage, OutboundMessage>();
Context.RegisterType<Random>(new InjectionFactory(container => new Random()));
Context.RegisterType<NullMessage>();
Context.RegisterType<StartMessage>();
Context.RegisterType<StopMessage>();
}
public static void Main(string[] args)
{
try
{
var sys = new TeleComSystem(); //uses container inside, but should be resolved itself!
sys.Start();
}
finally
{
Context.Dispose();
}
}
//simplified
public static readonly UnityContainer Context = new UnityContainer();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Database;
namespace Domain
{
public class DomainLogic
{
private readonly DatabaseObject _database = new DatabaseObject();
public void HandleAddEmployeeRequest()
{
_database.SaveEmployee();
}
}
}
<file_sep>package _07_picking_test_values;
import lombok.val;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class _03_ExampleValues {
@DataProvider
public static Object[][] shouldCorrectlyCheckNamesData() {
return new Object[][]{
{"aaaaa", false}, //must start with capital letter
{"A" , false}, //cannot be a one-letter name
{"Aa" , true }, //valid input
{"0" , false}, //cannot have digits
{"&" , false} //cannot have special chars
};
}
@Test(dataProvider = "shouldCorrectlyCheckNamesData")
public void shouldCorrectlyCheckNames(
String nameString,
boolean expectedResult) {
//GIVEN
val userNameCheck = new UserNameCheck();
//WHEN
val isUserNameValid = userNameCheck.applyTo(nameString);
//THEN
assertThat(isUserNameValid).isEqualTo(expectedResult);
}
}
<file_sep>using System;
using BastardInjection._4_BastardInjection.Inbound;
using BastardInjection._4_BastardInjection.Outbound;
namespace BastardInjection._4_BastardInjection.Core
{
class TeleComSystem : IDisposable
{
private readonly IProcessingWorkflow _processingWorkflow;
private readonly IInbound _inbound;
private readonly IOutbound _outbound;
public TeleComSystem()
: this(new AcmeProcessingWorkflow(), new BinaryUdpInbound(), new Outbound.Outbound())
{
}
//for tests
public TeleComSystem(
IProcessingWorkflow processingWorkflow,
IInbound inbound,
IOutbound outbound)
{
_processingWorkflow = processingWorkflow;
_inbound = inbound;
_outbound = outbound;
}
public void Start()
{
_inbound.SetDomainLogic(_processingWorkflow);
_processingWorkflow.SetOutbound(_outbound);
_inbound.StartListening();
}
public void Dispose()
{
_inbound.Dispose();
}
}
}<file_sep>using System.Collections.Generic;
namespace KataTrainReservationTddEbook
{
public class ReservationDto
{
public readonly string trainId;
public readonly string reservationId;
public readonly List<TicketDto> perSeatTickets;
public ReservationDto(
string trainId,
List<TicketDto> perSeatTickets,
string reservationId)
{
this.trainId = trainId;
this.perSeatTickets = perSeatTickets;
this.reservationId = reservationId;
}
}
}<file_sep>using DataAccess.Ports;
namespace Domain
{
public class DomainLogic : IDomainLogic
{
readonly IPersistentStorage _storage;
public DomainLogic(IPersistentStorage persistentStorage)
{
_storage = persistentStorage;
}
public void HandleAddEmployeeRequest()
{
_storage.SaveEmployee();
}
}
}
<file_sep>using System.Collections.Generic;
using Functional.Maybe;
namespace KataTrainReservationTddEbook
{
public class PercentageBasedSearchEngine : SearchEngine
{
public Maybe<Coach> FindCoachForReservation(IEnumerable<Coach> coaches, in uint seatCount)
{
throw new System.NotImplementedException();
}
}
}<file_sep>using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.InMessages;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Interfaces;
namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Inbound
{
internal interface IParsing
{
AcmeMessage ResultFor(byte[] frameData);
}
class BinaryParsing : IParsing
{
public AcmeMessage ResultFor(byte[] frameData)
{
if (frameData == null)
{
return new NullMessage();
}
else if (frameData[0] == 1)
{
return new StartMessage();
}
else
{
return new StopMessage();
}
}
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public class TicketOffice
{
private readonly ReservationInProgressFactory _reservationInProgressFactory;
private readonly CommandFactory _commandFactory;
public TicketOffice(ReservationInProgressFactory reservationInProgressFactory, CommandFactory commandFactory)
{
_reservationInProgressFactory = reservationInProgressFactory;
_commandFactory = commandFactory;
}
public ReservationDto MakeReservation(ReservationRequestDto requestDto)
{
var reservationInProgress = _reservationInProgressFactory.FreshInstance();
var reservationCommand = _commandFactory.CreateReservationCommand(requestDto, reservationInProgress);
reservationCommand.Execute();
return reservationInProgress.ToDto();
}
}
}<file_sep>using ConformingContainerAntipattern._3_ConformingContainer.Interfaces;
using ConformingContainerAntipattern._3_ConformingContainer.Services;
namespace ConformingContainerAntipattern._3_ConformingContainer.InMessages
{
class NullMessage : AcmeMessage
{
public void AuthorizeUsing(IAuthorization authorizationRules)
{
}
public void WriteTo(DataDestination dataDestination)
{
}
}
}<file_sep>namespace Domain
{
public interface IDomainLogic
{
void HandleAddEmployeeRequest();
}
}<file_sep>using System;
using Autofac;
using NUnit.Framework;
namespace IoCContainerPros
{
public class LifetimeManagement
{
[Test]
public void ShouldDisposeOfCreatedDependencies()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<Lol>();
using (var container = containerBuilder.Build())
{
var lol1 = container.Resolve<Lol>();
var lol2 = container.Resolve<Lol>();
Console.WriteLine("opening scope");
using (var nested = container.BeginLifetimeScope("nested"))
{
var lol3 = nested.Resolve<Lol>();
var lol4 = nested.Resolve<Lol>();
Console.WriteLine("closing scope");
}
Console.WriteLine("closed scope");
var lol5 = container.Resolve<Lol>();
}
}
}
public class Lol : IDisposable
{
private static int _counter = 0;
private readonly int _currentId;
public Lol()
{
_currentId = _counter++;
Console.WriteLine("_____CREATED______" + _currentId);
}
public void Dispose()
{
Console.WriteLine("_____DISPOSED______" + _currentId);
}
}
}<file_sep>using System;
using BastardInjection._4_BastardInjection.Interfaces;
using BastardInjection._4_BastardInjection.Services;
namespace BastardInjection._4_BastardInjection.InMessages
{
class StopMessage : AcmeMessage
{
public void AuthorizeUsing(IAuthorization authorizationRules)
{
Console.WriteLine("Authorizing Stop with " + authorizationRules);
}
public void WriteTo(DataDestination dataDestination)
{
Console.WriteLine("Writing Stop to " + dataDestination);
}
}
}<file_sep>using System;
using View.Ports;
namespace Gui
{
public class Window
{
private readonly IDomainLogic _logic;
public Window(IDomainLogic domainLogic)
{
_logic = domainLogic;
}
public void OnSubmitClicked()
{
_logic.HandleAddEmployeeRequest();
}
}
}
<file_sep>using ServiceLocatorDIAntipattern._2_ServiceLocator.Outbound;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.Interfaces
{
public interface DataDestination
{
void Add(string s);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Autofac;
using Autofac.Core;
using NUnit.Framework;
namespace IoCContainerCons
{
public class CircularDependencies
{
[Test]
//9.3.3 Constructor/Constructor dependencies
public void ShouldFailWhenCircularDependencyIsDiscovered()
{
//GIVEN
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<One>();
containerBuilder.RegisterType<Two>();
using var container = containerBuilder.Build();
//WHEN
//THEN
//TODO uncomment to see the exception
Assert.Throws<DependencyResolutionException>(() =>
{
var one = container.Resolve<One>();
});
}
}
public class One
{
public One(Two two)
{
}
}
public class Two
{
public Two(One one)
{
}
}
}
<file_sep>using System;
namespace DependencyInjectionBefore._1_ControlFreak.Inbound
{
class UdpSocket
{
public bool Receive(out byte[] frameData)
{
frameData = new byte[100];
new Random().NextBytes(frameData);
return true;
}
}
}<file_sep>using System;
using Autofac;
using NUnit.Framework;
namespace IoCContainerCons
{
public class CaptiveDependency
{
[Test]
public void ShouldShowCaptiveDependencyIssue()
{
var i = 0;
//GIVEN
var builder = new ContainerBuilder();
builder.Register(ctr => "Lol" + i++).InstancePerLifetimeScope();
builder.RegisterType<Captor>().SingleInstance();
using var container = builder.Build();
//WHEN
using(var scope = container.BeginLifetimeScope())
{
var text1 = scope.Resolve<string>();
var text2 = scope.Resolve<string>();
var captor1 = scope.Resolve<Captor>();
var captor2 = scope.Resolve<Captor>();
//THEN
Assert.AreEqual("Lol0", text1);
Assert.AreEqual("Lol0", text2);
Assert.AreEqual("Lol1", captor1.Str);
Assert.AreEqual("Lol1", captor2.Str);
}
using(var scope = container.BeginLifetimeScope())
{
var text1 = scope.Resolve<string>();
var text2 = scope.Resolve<string>();
var captor1 = scope.Resolve<Captor>();
var captor2 = scope.Resolve<Captor>();
//THEN
Assert.AreEqual("Lol2", text1);
Assert.AreEqual("Lol2", text2);
Assert.AreEqual("Lol1", captor1.Str);
Assert.AreEqual("Lol1", captor2.Str);
}
using(var scope = container.BeginLifetimeScope())
{
var text1 = scope.Resolve<string>();
var text2 = scope.Resolve<string>();
var captor1 = scope.Resolve<Captor>();
var captor2 = scope.Resolve<Captor>();
//THEN
Assert.AreEqual("Lol3", text1);
Assert.AreEqual("Lol3", text2);
Assert.AreEqual("Lol1", captor1.Str);
Assert.AreEqual("Lol1", captor2.Str);
}
}
}
public class Captor
{
public string Str { get; }
public Captor(string str)
{
Str = str;
}
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public interface Coach
{
void Reserve(in uint seatCount, ReservationInProgress reservationInProgress);
uint GetPercentageReserved();
}
public class ReservableCoach : Coach
{
public void Reserve(in uint seatCount, ReservationInProgress reservationInProgress)
{
throw new System.NotImplementedException();
}
public uint GetPercentageReserved()
{
throw new System.NotImplementedException();
}
}
}<file_sep>package _02_MethodsAndParameters;
//TODO encapsulate fields of message (encapsulate fields)
//TODO assume the encapsulated type is third party. Copy type -> generate delegating members
//TODO deal with unclear responsibility in CreateFriendlyMessageFrom() (inline method)
//TODO remove duplication of title casing (extract both methods, make one delegate to other, inline method)
//TODO in this order, content, recipient and sender as parameters (introduce parameters)
//TODO allow using different formattings in Send (extract method => introduce field => introduce parameter)
// optionally: get to Format(from, to, content), make method non static, extract again to make Format(message), non static again, extract class
//TODO get rid of destination dependency and inline Send() method (introduce field, inline field, introduce parameter, inline method)
//TODO rearrange ProcessInvitationMessage() signature parameters in from-to-what fashion
import org.apache.commons.lang3.StringUtils;
public class MethodsAndParameters {
private final MessageDestination destination = new ConsoleDestination();
public void processInvitationMessage() {
final String sender = "zenek";
final String recipient = "jasiek";
FriendlyMessage message = createFriendlyMessageFrom(sender);
message.To = Character.isLowerCase(recipient.charAt(0)) ?
StringUtils.capitalize(recipient.toLowerCase()) : recipient;
message.Content = "Hey, dude, let's hit the streets!";
send(message);
}
private FriendlyMessage createFriendlyMessageFrom(String sender) {
final FriendlyMessage message = new FriendlyMessage();
message.From = Character.isLowerCase(sender.charAt(0))
? StringUtils.capitalize(sender.toLowerCase())
: sender;
return message;
}
private void send(FriendlyMessage message) {
destination.send("From: " + message.From + System.lineSeparator() +
"To: " + message.To + System.lineSeparator() +
"Content: " + message.Content);
}
public void main() {
processInvitationMessage();
}
public static void fitsSomewhereElse() {
}
}
//TODO add example with if statement
<file_sep>using System;
namespace NullAsErrorRefactored
{
//exceptions have 2 things nulls do not:
//1. A name
//2. A stack trace
class Program
{
public static void Main(string[] args)
{
var database = new Database();
var userDto = new UserDto();
try
{
database.Save(userDto);
}
catch (DatabaseConnectionException e)
{
LogError(
$"Could not connect to db to save user {userDto}");
}
}
private static void LogError(string s)
{
Console.WriteLine(s);
}
}
internal class DatabaseConnectionException : Exception
{
}
internal class ResourceId
{
}
public class UserDto
{
}
internal class Database
{
public void Save(UserDto userDto)
{
}
}
}
<file_sep>using ConformingContainerAntipattern._3_ConformingContainer.Inbound;
using ConformingContainerAntipattern._3_ConformingContainer.Outbound;
namespace ConformingContainerAntipattern._3_ConformingContainer.Core
{
class TeleComSystem
{
private readonly IProcessingWorkflow _processingWorkflow;
private readonly IInbound _inbound;
private readonly IOutbound _outbound;
public TeleComSystem()
{
_inbound = ApplicationRoot.Context.Resolve<IInbound>();
_outbound = ApplicationRoot.Context.Resolve<IOutbound>();
_processingWorkflow = ApplicationRoot.Context.Resolve<IProcessingWorkflow>();
}
public void Start()
{
_inbound.SetDomainLogic(_processingWorkflow);
_processingWorkflow.SetOutbound(_outbound);
_inbound.StartListening();
}
}
}<file_sep>using System;
namespace KataTrainReservationTddEbook
{
public class TodoReservationInProgressFactory : ReservationInProgressFactory
{
public ReservationInProgress FreshInstance()
{
throw new NotImplementedException();
}
}
}<file_sep>using ConformingContainerAntipattern._3_ConformingContainer.Services;
namespace ConformingContainerAntipattern._3_ConformingContainer.Interfaces
{
public interface AcmeMessage
{
void AuthorizeUsing(IAuthorization authorizationRules);
void WriteTo(DataDestination dataDestination);
}
}<file_sep>using BastardInjection._4_BastardInjection.Core;
namespace BastardInjection._4_BastardInjection
{
public class ApplicationRoot
{
public static void Main(string[] args)
{
var sys = new TeleComSystem(); //bastard injected - look at output socket which is disposable in this example!
sys.Start();
sys.Dispose(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!! error!!!!
}
}
}
<file_sep>using ServiceLocatorDIAntipattern._2_ServiceLocator.Interfaces;
using Microsoft.Practices.Unity;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.Outbound
{
public interface IOutboundMessage : DataDestination
{
void SendVia(IOutputSocket outputOutputSocket);
}
class OutboundMessage : IOutboundMessage
{
private readonly IMarshalling _marshalling;
private string _content = string.Empty;
public OutboundMessage()
{
_marshalling = ApplicationRoot.Context.Resolve<IMarshalling>();
}
public void SendVia(IOutputSocket outputOutputSocket)
{
var marshalledContent = _marshalling.Of(_content);
outputOutputSocket.Open();
outputOutputSocket.Send(marshalledContent);
outputOutputSocket.Close();
}
public void Add(string s)
{
_content += s;
}
}
}<file_sep>using System;
using ConformingContainerAntipattern._3_ConformingContainer;
using ConformingContainerAntipattern._3_ConformingContainer.Core;
using ConformingContainerAntipattern._3_ConformingContainer.Services;
using NSubstitute;
using NUnit.Framework;
using Microsoft.Practices.Unity;
namespace ConformingContainerAntipattern
{
namespace ServiceLocatorDIAntipattern
{
public class Class1
{
[Test]
public void ShouldStartProperly___DUMMY___()
{
var mockRepository = Substitute.For<IRepository>();
ApplicationRoot.Context.For<IRepository>().Use(mockRepository);
var telecom = new TeleComSystem();
}
[Test]
public void ShouldDisposeOfDisposableDependencies()
{
//GIVEN
Assume.That(Disposable._disposed, Is.EqualTo(false));
//WHEN
using (var container = new ConformingContainer())
{
container.For<IEmpty>().UseAlwaysTheSame<Disposable>();
container.Resolve<IEmpty>();
} // release
//THEN
Assert.AreEqual(true, Disposable._disposed);
}
public class Disposable : IDisposable, IEmpty
{
public static bool _disposed = false;
public void Dispose()
{
_disposed = true;
}
}
}
public interface IEmpty
{
}
}
}
<file_sep>buildscript {
ext {
lombok_dep = 'org.projectlombok:lombok:1.18.0'
}
}
plugins {
id "net.ltgt.apt" version "0.17"
}
group 'xunit-test-patterns'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
apply plugin: 'java'
sourceCompatibility = 1.8
dependencies {
compileOnly lombok_dep
testCompileOnly lombok_dep
annotationProcessor lombok_dep
testCompile 'com.github.grzesiek-galezowski:tdd-toolkit-java:1.2.5'
}
task wrapper(type: Wrapper) {
gradleVersion = '4.7'
}
<file_sep>using BastardInjection._4_BastardInjection.Interfaces;
namespace BastardInjection._4_BastardInjection.Outbound
{
public interface IOutboundMessage : DataDestination
{
void SendVia(IOutputSocket outputOutputSocket);
}
class OutboundMessage : IOutboundMessage
{
private readonly IMarshalling _marshalling;
private string _content = string.Empty;
public OutboundMessage() : this(new XmlMarshalling())
{
}
public OutboundMessage(IMarshalling marshalling)
{
_marshalling = marshalling;
}
public void SendVia(IOutputSocket outputOutputSocket)
{
var marshalledContent = _marshalling.Of(_content);
outputOutputSocket.Open();
outputOutputSocket.Send(marshalledContent);
outputOutputSocket.Close();
}
public void Add(string s)
{
_content += s;
}
}
}<file_sep>package _03_parameterized_tests;
import lombok.val;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class Ex04ParameterizedTest_PersonSpecification {
@DataProvider
public static Object[][] shouldBeAdultDependingOnAgeData() {
return new Object[][]{
{17, false},
{18, true},
};
}
@Test(dataProvider = "shouldBeAdultDependingOnAgeData")
public void shouldBeAdultDependingOnAge(int age, boolean expectedIsAdult) {
//GIVEN
val person = new Person(age);
//WHEN
val isAdult = person.isAdult();
//THEN
assertThat(isAdult).isEqualTo(expectedIsAdult);
}
}
<file_sep>using DependencyInjectionBefore._1_ControlFreak.Interfaces;
namespace DependencyInjectionBefore._1_ControlFreak.Outbound
{
class XmlOutboundMessage : DataDestination
{
private readonly XmlMarshalling _xmlMarshalling;
private string _content = string.Empty;
public XmlOutboundMessage()
{
_xmlMarshalling = new XmlMarshalling();
}
public void SendVia(TcpSocket outputSocket)
{
var marshalledContent = _xmlMarshalling.Of(_content);
outputSocket.Open();
outputSocket.Send(marshalledContent);
outputSocket.Close();
}
public void Add(string s)
{
_content += s;
}
}
}<file_sep>using System;
namespace BastardInjection._4_BastardInjection.Inbound
{
internal interface IInputSocket : IDisposable //first error - do not implement disposabled in interfaces
{
bool Receive(out byte[] frameData);
}
class UdpSocket : IInputSocket
{
public bool Receive(out byte[] frameData)
{
frameData = new byte[100];
new Random().NextBytes(frameData);
return true;
}
public void Dispose()
{
Console.WriteLine("Disposed");
}
}
}<file_sep>using System;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Interfaces;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.Services
{
class SqlDataDestination : DataDestination
{
public void Add(string s)
{
throw new NotImplementedException();
}
}
}<file_sep>using System;
using Persistence.Ports;
using View.Ports;
namespace Domain
{
public class DomainLogic : IDomainLogic
{
private readonly IPersistentStorage _storage;
public DomainLogic(
IPersistentStorage persistentStorage)
{
_storage = persistentStorage;
}
public void HandleAddEmployeeRequest()
{
_storage.SaveEmployee();
}
}
}
<file_sep>namespace KataTrainReservationTddEbook
{
public interface CommandFactory
{
ReservationCommand CreateReservationCommand(ReservationRequestDto requestDto, ReservationInProgress reservationInProgress);
}
}<file_sep>using BastardInjection._4_BastardInjection.InMessages;
using BastardInjection._4_BastardInjection.Interfaces;
namespace BastardInjection._4_BastardInjection.Inbound
{
internal interface IPacketParsing
{
AcmeMessage ResultFor(byte[] frameData);
}
class BinaryParsing : IPacketParsing
{
public AcmeMessage ResultFor(byte[] frameData)
{
if (frameData == null)
{
return new NullMessage();
}
else if (frameData[0] == 1)
{
return new StartMessage();
}
else
{
return new StopMessage();
}
}
}
}<file_sep>using Autofac;
using NUnit.Framework;
//CONS:
//1. containers take time to learn (every special case -> new feature)
//2. containers hide the dependency graph
//3. containers do not yield themselves to refactoring
//4. containers give away some of the compile time checks
namespace IoCContainerCons
{
public class Decorators
{
//TODO passing part of the chain to one object and full chain to another
[Test]
public void ShouldAssembleDecoratorsByHand()
{
var answer = new SynchronizedAnswer(
new TracedAnswer(
new Answer()));
Assert.IsInstanceOf<SynchronizedAnswer>(answer);
Assert.IsInstanceOf<TracedAnswer>(answer.NestedAnswer);
Assert.IsInstanceOf<Answer>(answer.NestedAnswer.NestedAnswer);
}
[Test]
public void ShouldAssembleDecoratorsUsingContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<Answer>().As<IAnswer>();
builder.RegisterDecorator<TracedAnswer, IAnswer>();
builder.RegisterDecorator<SynchronizedAnswer, IAnswer>();
//nothing more that can be done with it, e.g. cannot pass NamedParameter -> .WithParameter()
using var container = builder.Build();
var answer = container.Resolve<IAnswer>();
Assert.IsInstanceOf<SynchronizedAnswer>(answer);
Assert.IsInstanceOf<TracedAnswer>(answer.NestedAnswer);
Assert.IsInstanceOf<Answer>(answer.NestedAnswer.NestedAnswer);
}
}
public class TracedAnswer : IAnswer
{
public IAnswer NestedAnswer { get; }
public TracedAnswer(IAnswer answer)
{
NestedAnswer = answer;
}
}
public class SynchronizedAnswer : IAnswer
{
public IAnswer NestedAnswer { get; }
public SynchronizedAnswer(IAnswer answer)
{
NestedAnswer = answer;
}
}
public interface IAnswer
{
IAnswer NestedAnswer { get; }
}
public class Answer : IAnswer
{
public IAnswer NestedAnswer => null;
}
}
<file_sep>namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Services
{
public interface IAuthorization
{
}
class ActiveDirectoryBasedAuthorization : IAuthorization
{
}
}<file_sep>namespace NullAsNothingRefactored2
{
public enum EntityTypes
{
User,
Radio,
Group
}
}<file_sep>using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Interfaces;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Outbound;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Services;
namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Core
{
internal interface IAcmeProcessingWorkflow
{
void SetOutbound(IOutbound outbound);
void ApplyTo(AcmeMessage message);
}
class AcmeProcessingWorkflow : IAcmeProcessingWorkflow
{
private readonly IRepository _repository;
private readonly IAuthorization _authorizationRules;
private IOutbound _outbound;
public AcmeProcessingWorkflow(
IAuthorization activeDirectoryBasedAuthorization,
IRepository msSqlBasedRepository)
{
_authorizationRules = activeDirectoryBasedAuthorization;
_repository = msSqlBasedRepository;
}
public void SetOutbound(IOutbound outbound)
{
_outbound = outbound;
}
public void ApplyTo(AcmeMessage message)
{
message.AuthorizeUsing(_authorizationRules);
_repository.Save(message);
_outbound.Send(message);
}
}
}<file_sep>using System;
using NSubstitute;
using NUnit.Framework;
using ServiceLocatorDIAntipattern._2_ServiceLocator;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Core;
using Microsoft.Practices.Unity;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Services;
namespace ServiceLocatorDIAntipattern
{
public class Class1
{
[Test]
public void ShouldStartProperly___DUMMY___()
{
var mockRepository = Substitute.For<IRepository>();
ApplicationRoot.Context.RegisterInstance(mockRepository);
var telecom = new TeleComSystem();
//fails on purpose - lost dependency
telecom.Start();
}
[Test]
public void ShouldDisposeOfDisposableDependencies()
{
//GIVEN
Assume.That(Disposable._disposed, Is.EqualTo(false));
//WHEN
using (var container = new UnityContainer())
{
container.RegisterType<IEmpty, Disposable>(new ContainerControlledLifetimeManager());
container.Resolve<IEmpty>();
} // release
//THEN
Assert.AreEqual(true, Disposable._disposed);
}
public class Disposable : IDisposable, IEmpty
{
public static bool _disposed = false;
public void Dispose()
{
_disposed = true;
}
}
}
public interface IEmpty
{
}
}
<file_sep>using System;
namespace DependencyInjectionBefore._1_ControlFreak.Outbound
{
class TcpSocket
{
public void Open()
{
Console.WriteLine("open");
}
public void Close()
{
Console.WriteLine("closing");
}
public void Send(string lol)
{
Console.WriteLine(lol);
}
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public class TicketDto
{
public readonly string coach;
public readonly int seatNumber;
public TicketDto(string coach, int seatNumber)
{
this.coach = coach;
this.seatNumber = seatNumber;
}
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public interface ReservationCommand
{
void Execute();
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.Core;
namespace DependencyInjectionBefore._1_ControlFreak.Inbound
{
class BinaryUdpInbound
{
private AcmeProcessingWorkflow _processingWorkflow;
private readonly UdpSocket _socket;
private readonly BinaryParsing _parsing;
public BinaryUdpInbound()
{
_socket = new UdpSocket();
_parsing = new BinaryParsing();
}
public void SetDomainLogic(AcmeProcessingWorkflow processingWorkflow)
{
_processingWorkflow = processingWorkflow;
}
public void StartListening()
{
byte[] frameData;
while (_socket.Receive(out frameData))
{
var message = _parsing.ResultFor(frameData);
if (message != null)
{
if (_processingWorkflow != null)
{
_processingWorkflow.ApplyTo(message);
}
}
}
}
}
}<file_sep>using ServiceLocatorDIAntipattern._2_ServiceLocator.Interfaces;
using ServiceLocatorDIAntipattern._2_ServiceLocator.Services;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.InMessages
{
class NullMessage : AcmeMessage
{
public void AuthorizeUsing(IAuthorization authorizationRules)
{
}
public void WriteTo(DataDestination dataDestination)
{
}
}
}<file_sep>namespace ChangingBehaviorThroughComposition
{
public class NoAlarm : Alarm
{
public void Trigger()
{
}
public void Disable()
{
}
}
}<file_sep>using System.Collections.Generic;
using Functional.Maybe;
namespace KataTrainReservationTddEbook
{
public interface SearchEngine
{
Maybe<Coach> FindCoachForReservation(IEnumerable<Coach> coaches, in uint seatCount);
}
}<file_sep>using DataAccess.Ports;
using DataAccess.Ports.Primary;
namespace Gui
{
public class Window
{
private readonly IDomainLogic _logic;
public Window(IDomainLogic domainLogic)
{
_logic = domainLogic;
}
public void OnSubmitClicked()
{
_logic.HandleAddEmployeeRequest();
}
}
}
<file_sep>namespace KataTrainReservationTddEbook
{
public interface Trains
{
Train RetrieveBy(string trainId);
void Update(Train train);
}
}<file_sep>using System;
using BastardInjection._4_BastardInjection.Core;
namespace BastardInjection._4_BastardInjection.Inbound
{
internal interface IInbound : IDisposable //TODO error! forced by the UdpSocket
{
void SetDomainLogic(IProcessingWorkflow processingWorkflow);
void StartListening();
}
class BinaryUdpInbound : IInbound
{
private IProcessingWorkflow _processingWorkflow;
private readonly IInputSocket _socket;
private readonly IPacketParsing _parsing;
public BinaryUdpInbound() : this(new UdpSocket(), new BinaryParsing())
{
}
//for tests
public BinaryUdpInbound(IInputSocket socket, IPacketParsing parsing)
{
_socket = socket;
_parsing = parsing;
}
public void SetDomainLogic(IProcessingWorkflow processingWorkflow)
{
_processingWorkflow = processingWorkflow;
}
public void StartListening()
{
byte[] frameData;
while (_socket.Receive(out frameData))
{
var message = _parsing.ResultFor(frameData);
if (message != null)
{
if (_processingWorkflow != null)
{
_processingWorkflow.ApplyTo(message);
}
}
}
}
public void Dispose()
{
_socket.Dispose(); //error!
}
}
}<file_sep>using System;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.Outbound
{
public interface IOutputSocket
{
void Open();
void Close();
void Send(string lol);
}
class TcpSocket : IOutputSocket
{
public void Open()
{
Console.WriteLine("open");
}
public void Close()
{
Console.WriteLine("closing");
}
public void Send(string lol)
{
Console.WriteLine(lol);
}
}
}<file_sep>using FluentAssertions;
using TddXt.AnyRoot;
using Xunit;
using static TddXt.AnyRoot.Root;
namespace KataTrainReservationTddEbook
{
public class TicketOfficeCommandFactory : CommandFactory
{
public ReservationCommand CreateReservationCommand(ReservationRequestDto requestDto,
ReservationInProgress reservationInProgress)
{
return new TrainReservationCommand(
requestDto.trainId,
requestDto.seatCount,
new ReferenceService(),
new PercentageBasedSearchEngine(),
reservationInProgress);
}
}
public class TicketOfficeCommandFactorySpecification
{
[Fact]
public void ShouldDOWHAT()
{
//GIVEN
var factory = new TicketOfficeCommandFactory();
var dto = Any.Instance<ReservationRequestDto>();
var reservationInProgress = Any.Instance<ReservationInProgress>();
//WHEN
var command = factory.CreateReservationCommand(dto, reservationInProgress);
//THEN
command.Should().BeOfType<TrainReservationCommand>();
}
}
}<file_sep>using Functional.Maybe;
namespace NullAsNothingRefactored2
{
public interface ICache
{
Maybe<QueryResult> GetBy(string entityId);
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public class ReservationRequestDto
{
public readonly string trainId;
public readonly uint seatCount;
public ReservationRequestDto(string trainId, uint seatCount)
{
this.trainId = trainId;
this.seatCount = seatCount;
}
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.Interfaces;
namespace DependencyInjectionBefore._1_ControlFreak.Services
{
class MsSqlBasedRepository
{
private readonly DataDestination _sqlDataDestination = new SqlDataDestination();
public void Save(AcmeMessage message)
{
message.WriteTo(_sqlDataDestination);
}
}
}<file_sep>using FluentAssertions;
using Xunit;
namespace KataTrainReservationTddEbook
{
public interface ReservationInProgressFactory
{
ReservationInProgress FreshInstance();
}
public class DtoBasedReservationInProgressFactory : ReservationInProgressFactory
{
public ReservationInProgress FreshInstance()
{
return new DtoBasedReservationInProgress();
}
}
public class DtoBasedReservationInProgressFactorySpecification
{
[Fact]
public void ShouldDOWHAT()
{
//GIVEN
var factory = new DtoBasedReservationInProgressFactory();
//WHEN
var instance = factory.FreshInstance();
//THEN
instance.Should().BeOfType<DtoBasedReservationInProgress>();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Functional.Maybe;
using Functional.Maybe.Just;
using NSubstitute;
using TddXt.AnyRoot;
using TddXt.AnyRoot.Collections;
using TddXt.AnyRoot.Numbers;
using Xunit;
using static TddXt.AnyRoot.Root;
namespace KataTrainReservationTddEbook
{
public class ReservableTrain : Train
{
private readonly IEnumerable<Coach> _coaches;
public ReservableTrain(IEnumerable<Coach> coaches)
{
_coaches = coaches;
}
public const uint UpperBound = 10; //bug
public void Reserve(in uint seatCount, SearchEngine searchEngine, ReservationInProgress reservationInProgress)
{
var chosenCoach = searchEngine.FindCoachForReservation(_coaches, seatCount);
if (chosenCoach.HasValue)
{
chosenCoach.Value.Reserve(seatCount, reservationInProgress);
}
else
{
reservationInProgress.NoMatchingCoachFoundFor(seatCount);
}
}
public bool HasCapacityForReservationsInAdvance()
{
var percentages = _coaches.Select(c => c.GetPercentageReserved());
if (percentages.Average(p => p) <= UpperBound)
{
return true;
}
return false;
}
}
public class ReservableTrainSpecification
{
[Fact]
public void ShouldDOWHAT()
{
//GIVEN
var coaches = Any.Enumerable<Coach>();
var train = new ReservableTrain(coaches);
var seatCount = Any.UnsignedInt();
var searchEngine = Substitute.For<SearchEngine>();
var reservationInProgress = Any.Instance<ReservationInProgress>();
var matchingCoach = Substitute.For<Coach>();
searchEngine.FindCoachForReservation(coaches, seatCount).Returns(matchingCoach.Just());
//WHEN
train.Reserve(seatCount, searchEngine, reservationInProgress);
//THEN
matchingCoach.Received(1).Reserve(seatCount, reservationInProgress); //bug XReceived.Only()
}
[Fact]
public void ShouldDOWHAT2()
{
//GIVEN
var coaches = Any.Enumerable<Coach>();
var train = new ReservableTrain(coaches);
var seatCount = Any.UnsignedInt();
var searchEngine = Substitute.For<SearchEngine>();
var reservationInProgress = Substitute.For<ReservationInProgress>();
searchEngine.FindCoachForReservation(coaches, seatCount).Returns(Maybe<Coach>.Nothing);
//WHEN
train.Reserve(seatCount, searchEngine, reservationInProgress);
//THEN
reservationInProgress.Received(1).NoMatchingCoachFoundFor(seatCount); //bug XReceived.Only()
}
[Theory]
[InlineData(ReservableTrain.UpperBound, ReservableTrain.UpperBound+1, ReservableTrain.UpperBound, false)]
[InlineData(ReservableTrain.UpperBound, ReservableTrain.UpperBound, ReservableTrain.UpperBound, true)]
[InlineData(ReservableTrain.UpperBound-1, ReservableTrain.UpperBound+1, ReservableTrain.UpperBound, true)]
public void ShouldDecideWhetherItHasCapacityBasedOnCapacityBeingOverTheUpperBound(
uint percentage1,
uint percentage2,
uint percentage3,
bool expectedResult)
{
//GIVEN
var coach1 = Substitute.For<Coach>();
var coach2 = Substitute.For<Coach>();
var coach3 = Substitute.For<Coach>();
var coaches = new List<Coach>
{
coach1,
coach2,
coach3,
};
var train = new ReservableTrain(coaches);
coach1.GetPercentageReserved().Returns(percentage1);
coach2.GetPercentageReserved().Returns(percentage2);
coach3.GetPercentageReserved().Returns(percentage3);
//bug value objects
//WHEN
var result = train.HasCapacityForReservationsInAdvance();
//THEN
result.Should().Be(expectedResult);
}
}
}<file_sep>using BastardInjection._4_BastardInjection.Services;
namespace BastardInjection._4_BastardInjection.Interfaces
{
public interface AcmeMessage
{
void AuthorizeUsing(IAuthorization authorizationRules);
void WriteTo(DataDestination dataDestination);
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.Services;
namespace DependencyInjectionBefore._1_ControlFreak.Interfaces
{
interface AcmeMessage
{
void AuthorizeUsing(ActiveDirectoryBasedAuthorization authorizationRules);
void WriteTo(DataDestination dataDestination);
}
}<file_sep>using System;
using Microsoft.Practices.Unity;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.Inbound
{
internal interface IInputSocket
{
bool Receive(out byte[] frameData);
}
class UdpSocket : IInputSocket
{
public bool Receive(out byte[] frameData)
{
frameData = new byte[100];
ApplicationRoot.Context.Resolve<Random>().NextBytes(frameData); //stable dependency!
return true;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Autofac;
using NUnit.Framework;
namespace IoCContainerPros
{
public class AutoWiring
{
[Test]
public void ShouldAutoWireDependencies()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<Person>().SingleInstance();
containerBuilder.RegisterType<Kitchen>().SingleInstance();
containerBuilder.RegisterType<Knife>().SingleInstance();
using (var container = containerBuilder.Build())
{
var person = container.Resolve<Person>();
}
}
}
public class Person
{
public Person(Kitchen kitchen)
{
}
}
public class Kitchen
{
public Kitchen(Knife knife)
{
}
}
public class Knife
{
}
}
<file_sep>using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Interfaces;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Services;
namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.InMessages
{
class NullMessage : AcmeMessage
{
public void AuthorizeUsing(IAuthorization authorizationRules)
{
}
public void WriteTo(DataDestination dataDestination)
{
}
}
}<file_sep>namespace KataTrainReservationTddEbook
{
public class ReferenceService : Trains
{
public Train RetrieveBy(string trainId)
{
throw new System.NotImplementedException();
}
public void Update(Train train)
{
throw new System.NotImplementedException();
}
}
}<file_sep>namespace ConformingContainerAntipattern._3_ConformingContainer.Services
{
public interface IAuthorization
{
}
class ActiveDirectoryBasedAuthorization : IAuthorization
{
}
}<file_sep>using System;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Interfaces;
using DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.Services;
namespace DependencyInjectionAfter._1_ControlFreakRefactoredToDependencyInjection.InMessages
{
class StartMessage : AcmeMessage
{
public void AuthorizeUsing(IAuthorization authorizationRules)
{
Console.WriteLine("Authorizing Start with " + authorizationRules);
}
public void WriteTo(DataDestination dataDestination)
{
dataDestination.Add("Writing Start to " + dataDestination);
}
}
}<file_sep>using Functional.Maybe;
namespace NullAsNothingRefactored2
{
internal class RadioCache : ICache
{
public Maybe<QueryResult> GetBy(string entityId)
{
return Maybe<QueryResult>.Nothing;
}
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.InMessages;
using DependencyInjectionBefore._1_ControlFreak.Interfaces;
namespace DependencyInjectionBefore._1_ControlFreak.Inbound
{
class BinaryParsing
{
public AcmeMessage ResultFor(byte[] frameData)
{
if (frameData == null)
{
return new NullMessage();
}
else if (frameData[0] == 1)
{
return new StartMessage();
}
else
{
return new StopMessage();
}
}
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.Interfaces;
using DependencyInjectionBefore._1_ControlFreak.Outbound;
using DependencyInjectionBefore._1_ControlFreak.Services;
namespace DependencyInjectionBefore._1_ControlFreak.Core
{
class AcmeProcessingWorkflow
{
private readonly MsSqlBasedRepository _repository;
private readonly ActiveDirectoryBasedAuthorization _authorizationRules;
private XmlTcpOutbound _outbound;
public AcmeProcessingWorkflow()
{
_authorizationRules = new ActiveDirectoryBasedAuthorization();
_repository = new MsSqlBasedRepository();
}
public void SetOutbound(XmlTcpOutbound outbound)
{
_outbound = outbound;
}
public void ApplyTo(AcmeMessage message)
{
message.AuthorizeUsing(_authorizationRules);
_repository.Save(message);
_outbound.Send(message);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Functional.Maybe;
namespace MaybeAsMonad
{
class Program
{
static void Main(string[] args)
{
var database = new Database();
var userOfFirstContact = GetAddressBook()
.Select(b => b.Contacts)
.SelectMany(c => c.FirstOrDefault().ToMaybe())
.Select(c => c.Name)
.Select(name => database.LoadByName(name))
.OrElse(() => new Person("Zenek"));
Console.WriteLine(userOfFirstContact.Name);
}
private static Maybe<AddressBook> GetAddressBook()
{
return Maybe<AddressBook>.Nothing;
}
}
public class AddressBook
{
public List<Contact> Contacts { get; set; }
}
public class Contact
{
public string Name { get; set; }
}
public class Database
{
public Person LoadByName(string name)
{
return null;
}
}
public class Person
{
public Person(string zenek)
{
Name = zenek;
}
public string Name { get; set; }
}
}
<file_sep>using System;
using Autofac;
using Autofac.Core;
using Autofac.Features.AttributeFilters;
using NUnit.Framework;
//bug object encapsulation (check if this is possible in a container)
//it is to some extent by using child scopes(?) but that makes these places dependent on the container
/// <summary>
/// "Note that some relationships are based on types that are in Autofac (e.g., IIndex<X, B>).
/// Using those relationship types do tie you to at least having a reference to Autofac, even
/// if you choose to use a different IoC container for the actual resolution of services."
/// </summary>
namespace IoCContainerCons
{
public class TwoImplementationsOfTheSameInterface
{
[Test]
public void HandMadeComposition()
{
var archiveService = new ArchiveService(
new LocalDataStorage(),
new RemoteDataStorage());
Console.WriteLine(archiveService);
}
[Test]
//also: keyed (below) and indexed (and named parameters for constants)
public void ContainerCompositionWithNamed()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<LocalDataStorage>().Named<IDataStorage>("local");
containerBuilder.RegisterType<RemoteDataStorage>().Named<IDataStorage>("remote");
containerBuilder.Register(c =>
new ArchiveService(
c.ResolveNamed<IDataStorage>("local"),
c.ResolveNamed<IDataStorage>("remote")));
using var container = containerBuilder.Build();
var archiveService = container.Resolve<ArchiveService>();
Assert.IsInstanceOf<LocalDataStorage>(archiveService.LocalStorage);
Assert.IsInstanceOf<RemoteDataStorage>(archiveService.RemoteStorage);
}
[Test]
public void ContainerCompositionThroughResolveKeyedComponents()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<LocalDataStorage>().Keyed<IDataStorage>("localStorage");
containerBuilder.RegisterType<RemoteDataStorage>().Keyed<IDataStorage>("remoteStorage");
containerBuilder.RegisterType<ArchiveService>().WithAttributeFiltering();
using var container = containerBuilder.Build();
var archiveService = container.Resolve<ArchiveService>(
new ResolvedParameter(
(info, context) => info.Name == "localStorage",
(info, context) => context.ResolveKeyed<IDataStorage>("localStorage")),
new ResolvedParameter(
(info, context) => info.Name == "remoteStorage",
(info, context) => context.ResolveKeyed<IDataStorage>("remoteStorage"))
);
Assert.IsInstanceOf<LocalDataStorage>(archiveService.LocalStorage);
Assert.IsInstanceOf<RemoteDataStorage>(archiveService.RemoteStorage);
}
[Test]
public void ContainerCompositionThroughRegistrationOfResolvedParameters()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<LocalDataStorage>().Keyed<IDataStorage>("localStorage");
containerBuilder.RegisterType<RemoteDataStorage>().Keyed<IDataStorage>("remoteStorage");
containerBuilder.RegisterType<ArchiveService>()
.WithParameter(new ResolvedParameter(
(info, context) => info.Name == "localStorage",
(info, context) => context.ResolveKeyed<IDataStorage>("localStorage")))
.WithParameter(new ResolvedParameter(
(info, context) => info.Name == "remoteStorage",
(info, context) => context.ResolveKeyed<IDataStorage>("remoteStorage")));
using var container = containerBuilder.Build();
var archiveService = container.Resolve<ArchiveService>();
Assert.IsInstanceOf<LocalDataStorage>(archiveService.LocalStorage);
Assert.IsInstanceOf<RemoteDataStorage>(archiveService.RemoteStorage);
}
[Test]
public void ContainerCompositionWithAttributes()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<LocalDataStorage>().Keyed<IDataStorage>("local");
containerBuilder.RegisterType<RemoteDataStorage>().Keyed<IDataStorage>("remote");
containerBuilder.RegisterType<ArchiveServiceAttributed>().WithAttributeFiltering();
using var container = containerBuilder.Build();
var archiveService = container.Resolve<ArchiveServiceAttributed>();
Assert.IsInstanceOf<LocalDataStorage>(archiveService.LocalStorage);
Assert.IsInstanceOf<RemoteDataStorage>(archiveService.RemoteStorage);
}
[Test]
public void ContainerCompositionThroughNamedParameters()
{
//only for up-front known values and constants - cannot resolve from container each time
//prone to name change(?)
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ArchiveService>()
.WithParameter("localStorage", new LocalDataStorage())
.WithParameter("remoteStorage", new RemoteDataStorage());
using var container = containerBuilder.Build();
var archiveService = container.Resolve<ArchiveService>();
Assert.IsInstanceOf<LocalDataStorage>(archiveService.LocalStorage);
Assert.IsInstanceOf<RemoteDataStorage>(archiveService.RemoteStorage);
}
}
public class LocalDataStorage : IDataStorage
{
}
public class ArchiveService
{
public IDataStorage LocalStorage { get; }
public IDataStorage RemoteStorage { get; }
public ArchiveService(IDataStorage localStorage, IDataStorage remoteStorage)
{
LocalStorage = localStorage;
RemoteStorage = remoteStorage;
}
}
public class ArchiveServiceAttributed
{
public IDataStorage LocalStorage { get; }
public IDataStorage RemoteStorage { get; }
public ArchiveServiceAttributed(
[KeyFilter("local")] IDataStorage localStorage,
[KeyFilter("remote")] IDataStorage remoteStorage)
{
LocalStorage = localStorage;
RemoteStorage = remoteStorage;
}
}
public class RemoteDataStorage : IDataStorage
{
}
public interface IDataStorage
{
}
}<file_sep>using Functional.Maybe;
namespace NullAsNothingRefactored
{
internal interface ICache
{
Maybe<QueryResult> GetBy(string entityId);
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.Inbound;
using DependencyInjectionBefore._1_ControlFreak.Outbound;
namespace DependencyInjectionBefore._1_ControlFreak.Core
{
class TeleComSystem
{
private readonly AcmeProcessingWorkflow _processingWorkflow;
private readonly BinaryUdpInbound _inbound;
private readonly XmlTcpOutbound _outbound;
public TeleComSystem()
{
_inbound = new BinaryUdpInbound();
_outbound = new XmlTcpOutbound();
_processingWorkflow = new AcmeProcessingWorkflow();
}
public void Start()
{
_inbound.SetDomainLogic(_processingWorkflow);
_processingWorkflow.SetOutbound(_outbound);
_inbound.StartListening();
}
}
}<file_sep>namespace BastardInjection._4_BastardInjection.Outbound
{
internal interface IMarshalling
{
string Of(string arg);
}
class XmlMarshalling : IMarshalling
{
public string Of(string arg)
{
return "<" + arg + ">";
}
}
}<file_sep>using DependencyInjectionBefore._1_ControlFreak.Interfaces;
using DependencyInjectionBefore._1_ControlFreak.Services;
namespace DependencyInjectionBefore._1_ControlFreak.InMessages
{
class NullMessage : AcmeMessage
{
public void AuthorizeUsing(ActiveDirectoryBasedAuthorization authorizationRules)
{
}
public void WriteTo(DataDestination dataDestination)
{
}
}
}<file_sep>using BastardInjection._4_BastardInjection.Interfaces;
namespace BastardInjection._4_BastardInjection.Outbound
{
public interface IOutbound
{
void Send(AcmeMessage message);
}
public class Outbound : IOutbound
{
private readonly IOutputSocket _outputSocket;
public Outbound() : this(new TcpSocket())
{
}
//for tests
public Outbound(IOutputSocket outputSocket)
{
_outputSocket = outputSocket;
}
public void Send(AcmeMessage message)
{
var outboundMessage = new OutboundMessage();
message.WriteTo(outboundMessage);
outboundMessage.SendVia(_outputSocket);
}
}
}<file_sep>using ServiceLocatorDIAntipattern._2_ServiceLocator.Interfaces;
using Microsoft.Practices.Unity;
namespace ServiceLocatorDIAntipattern._2_ServiceLocator.Services
{
public interface IRepository
{
void Save(AcmeMessage message);
}
public class MsSqlBasedRepository : IRepository
{
private readonly DataDestination _sqlDataDestination = ApplicationRoot.Context.Resolve<SqlDataDestination>();
public void Save(AcmeMessage message)
{
message.WriteTo(_sqlDataDestination);
}
}
}<file_sep>using BastardInjection._4_BastardInjection.Interfaces;
using BastardInjection._4_BastardInjection.Services;
namespace BastardInjection._4_BastardInjection.InMessages
{
class NullMessage : AcmeMessage
{
public void AuthorizeUsing(IAuthorization authorizationRules)
{
}
public void WriteTo(DataDestination dataDestination)
{
}
}
}<file_sep>using ConformingContainerAntipattern._3_ConformingContainer.Interfaces;
using ConformingContainerAntipattern._3_ConformingContainer.Outbound;
using ConformingContainerAntipattern._3_ConformingContainer.Services;
namespace ConformingContainerAntipattern._3_ConformingContainer.Core
{
internal interface IProcessingWorkflow
{
void SetOutbound(IOutbound outbound);
void ApplyTo(AcmeMessage message);
}
class AcmeProcessingWorkflow : IProcessingWorkflow
{
private readonly IRepository _repository;
private readonly IAuthorization _authorizationRules;
private IOutbound _outbound;
public AcmeProcessingWorkflow()
{
_authorizationRules = ApplicationRoot.Context.Resolve<IAuthorization>();
_repository = ApplicationRoot.Context.Resolve<IRepository>();
}
public void SetOutbound(IOutbound outbound)
{
_outbound = outbound;
}
public void ApplyTo(AcmeMessage message)
{
message.AuthorizeUsing(_authorizationRules);
_repository.Save(message);
_outbound.Send(message);
}
}
} | b0929af8fa43f48e372a5dc0df2cf2fc5cd0bb65 | [
"Java",
"C#",
"Gradle"
] | 109 | C# | Yurishama/TrainingExamples | d0d98e3cabb9f497397d4d405501792a7cf61c60 | 0c3661e2a7709e7dad8782e4d632c96fc3f1be28 |
refs/heads/master | <repo_name>playautokimchan/promotion-creator<file_sep>/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace PromotionCreator
{
/// <summary>
/// MainWindow.xaml에 대한 상호 작용 논리
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GetScreen();
}
private void GetScreen()
{
string dir = Directory.GetCurrentDirectory();
this.PromotionScreen.Navigate(new Uri(String.Format("file:///{0}/index.html", dir)));
}
private void Renewal_Click(object sender, RoutedEventArgs e)
{
this.GetScreen();
}
private void CreateInputBox_Click(object sender, RoutedEventArgs e)
{
}
}
}
| 3e34cdc41b6d9b273045c1212d38bd68a20556ff | [
"C#"
] | 1 | C# | playautokimchan/promotion-creator | eac9ee06ef329dce86cb7c0db9bbcbb3b0f5bc8d | 762776a64110a6eaa6e6b95edaadc09a3f458274 |
refs/heads/master | <repo_name>mortalis13/mod_menu_login<file_sep>/README.md
# Menu With Login
A **Joomla 3** module extension.
This is a combination of the default **mod_menu** and **mod_login** modules.
Requires the **Bootstrap** framefork or its `nav, nav-pills` styles.
The **mod_menu** integration allows to select site menu which will be displayed in the module.
The **mod_login** module gives an option of login/logout redirect menu items.
### Usage:
1. Download the **.zip** from the *releases* section of the repository.
2. Go to the *Extensions -> Extension Manager* in the admin Joomla part.
3. Drag the zip onto the upload field and **Upload & Install**.
4. Go to the *Extensions -> Module Manager -> Site*.
5. Click on the **Menu With Login**.
6. Select the **Navigation** position for your site theme.
7. Select **Published** in **Status**.
8. Select **On all pages** in the *Menu Assignment -> Module Assignment* block.
9. Press **Save**.
10. The menu should appear on the main site below the page title.
<file_sep>/tmpl/login_form.php
<?php
defined('_JEXEC') or die;
?>
<form action="<?php echo JRoute::_('index.php', true, $params->get('usesecure')); ?>" method="post" id="login-form" class="pull-right menu-form-inline">
<div class="userdata">
<?php $usersConfig = JComponentHelper::getParams('com_users'); ?>
<div class="controls">
<?php if ($usersConfig->get('allowUserRegistration')) :
$link=JRoute::_('index.php?option=com_users&view=registration&Itemid=' . UsersHelperRoute::getRegistrationRoute());
?>
<a href="<?php echo $link ?>" class="btn btn-primary register-button">
<?php echo JText::_('MOD_MENU_LOGIN_REGISTER') ?>
</a>
<?php endif; ?>
<div class="input-prepend">
<span class="add-on">
<span class="icon-user"></span>
<label for="modlgn-username" class="element-invisible"><?php echo JText::_('MOD_MENU_LOGIN_FORM_USERNAME'); ?></label>
</span>
<input id="modlgn-username" type="text" name="username" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('MOD_MENU_LOGIN_FORM_USERNAME') ?>" />
</div>
<div class="input-prepend">
<span class="add-on">
<span class="icon-lock">
</span>
<label for="modlgn-passwd" class="element-invisible"><?php echo JText::_('JGLOBAL_PASSWORD'); ?>
</label>
</span>
<input id="modlgn-passwd" type="password" name="password" class="input-small" tabindex="0" size="18" placeholder="<?php echo JText::_('JGLOBAL_PASSWORD') ?>" />
</div>
<button type="submit" tabindex="0" name="Submit" class="btn btn-primary login-button"><?php echo JText::_('JLOGIN') ?></button>
</div>
<input type="hidden" name="option" value="com_users" />
<input type="hidden" name="task" value="user.login" />
<input type="hidden" name="return" value="<?php echo $return; ?>" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form><file_sep>/language/en-GB/en-GB.mod_menu_login.ini
; Joomla! Project
; Copyright (C) 2005 - 2014 Open Source Matters. All rights reserved.
; License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php
; Note : All ini files need to be saved as UTF-8 - No BOM
MOD_MENU_LOGIN="Menu With Login"
MOD_MENU_LOGIN_FIELD_ACTIVE_DESC="Select a menu item to always be used as the base for the menu display. You must set the Start Level to the same level or higher than the level of the base item. This will cause the module to be displayed on all assigned pages. If Current is selected the currently active item is used as the base. This causes the module to only display when the parent menu item is active."
MOD_MENU_LOGIN_FIELD_ACTIVE_LABEL="Base Item"
MOD_MENU_LOGIN_FIELD_ALLCHILDREN_DESC="Expand the menu and make its sub-menu items always visible."
MOD_MENU_LOGIN_FIELD_ALLCHILDREN_LABEL="Show Sub-menu Items"
MOD_MENU_LOGIN_FIELD_CLASS_DESC="A suffix to be applied to the CSS class of the menu items"
MOD_MENU_LOGIN_FIELD_CLASS_LABEL="Menu Class Suffix"
MOD_MENU_LOGIN_FIELD_ENDLEVEL_DESC="Level to stop rendering the menu at. If you choose 'All', all levels will be shown depending on 'Show Sub-menu Items' setting."
MOD_MENU_LOGIN_FIELD_ENDLEVEL_LABEL="End Level"
MOD_MENU_LOGIN_FIELD_MENUTYPE_DESC="Select a menu in the list"
MOD_MENU_LOGIN_FIELD_MENUTYPE_LABEL="Select Menu"
MOD_MENU_LOGIN_FIELD_STARTLEVEL_DESC="Level to start rendering the menu at. Setting the start and end levels to the same # and setting 'Show Sub-menu Items' to yes will only display that single level."
MOD_MENU_LOGIN_FIELD_STARTLEVEL_LABEL="Start Level"
MOD_MENU_LOGIN_FIELD_TAG_ID_DESC="An ID attribute to assign to the root UL tag of the menu (optional)"
MOD_MENU_LOGIN_FIELD_TAG_ID_LABEL="Menu Tag ID"
MOD_MENU_LOGIN_FIELD_TARGET_DESC="JavaScript values to position a popup window, e.g. top=50,left=50,width=200,height=300"
MOD_MENU_LOGIN_FIELD_TARGET_LABEL="Target Position"
MOD_MENU_LOGIN_XML_DESCRIPTION="This module displays a menu on the frontend."
MOD_MENU_LOGIN_FORM_USERNAME="Username"
MOD_MENU_LOGIN_FIELD_LOGIN_REDIRECTURL_LABEL="Login Redirection Page"
MOD_MENU_LOGIN_FIELD_LOGOUT_REDIRECTURL_DESC="Select the page the user will be redirected to after successfully ending their current session by logging out. Select from all the pages listed in the dropdown menu. Choosing "_QQ_"Default"_QQ_" will return to the same page."
MOD_MENU_LOGIN_FIELD_LOGOUT_REDIRECTURL_LABEL="Logout Redirection Page"
MOD_MENU_LOGIN_FIELD_LOGIN_REDIRECTURL_DESC="Select the page the user will be redirected to after a successful login. Select from all the pages listed in the dropdown menu. Choosing "_QQ_"Default"_QQ_" will return to the same page."
MOD_MENU_LOGIN_REGISTER="Register"
MOD_MENU_LOGIN_USER_GREETING="Welcome"
| 391167050b0ddc2d7845018a1b072e261c780eec | [
"Markdown",
"PHP",
"INI"
] | 3 | Markdown | mortalis13/mod_menu_login | e35449afc9ad47136e478d844d7e5e9eefa2d2c5 | 2dbf286464a83fdeec00cdab9ccd740f7612c0ea |
refs/heads/master | <repo_name>samlimbu/mlabmongo<file_sep>/server.js
var express = require('express');
var bodyParser =require('body-parser');
var cors = require('cors'); //to use differenct domain name, CORS Module
var mongoose = require('mongoose');
var config = require('./config/database');
var path = require('path');
var categoryRouter = require('./routes/category');
mongoose.connect(config.database);
//on connection
mongoose.connection.on('connected',()=>{
console.log('Connected to databse ' + config.database);
})
var app=express(config.database);
app.use(cors());
app.use(express.static(path.join(__dirname,'static')));
app.use(bodyParser.json());
app.get('/', categoryRouter);
var ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP ||'localhost';
var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 3000;
app.listen(port, ip);
console.log('Server running on http://%s:%s', ip, port); | fcd661100e661d220ba04204dbf8a5c830506c60 | [
"JavaScript"
] | 1 | JavaScript | samlimbu/mlabmongo | 55c32530e7742bba7ed2472636e51da8dd9315d7 | 8b297ff4d0a72dbfabc432a67c42e051ff81021c |
refs/heads/main | <repo_name>tjdoc/Friday-algorithm<file_sep>/Friday-algorithm/leetcode_TwoSum.swift
//
// leetcode_TwoSum.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/27.
//
/*
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
*/
import Foundation
class LeetTwoSum {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for ii in 0..<nums.count-1 {
if let jj = nums.lastIndex(of: target-nums[ii]) {
if ii != jj {return [ii, jj]}
}
}
// since the problem says there is one valid answer, the loop should not reach here
return [-1,-1]
}
}
//Runtime: 36 ms, faster than 57.13% of Swift online submissions for Two Sum.
//Memory Usage: 14 MB, less than 90.04% of Swift online submissions for Two Sum.
<file_sep>/Friday-algorithm/leetcode_RomanToInteger.swift
//
// leetcode_RomanToInteger.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/27.
//
/*
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
*/
import Foundation
class Roman {
func romanToInt_v1(_ s: String) -> Int {
var out = 0
var romanStr = s
let dicSpecial = ["CM": 900, "CD": 400, "XC": 90, "XL": 40, "IX": 9, "IV": 4]
let dic = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
dicSpecial.keys.forEach {
if romanStr.contains($0) {
out += dicSpecial[$0]!
romanStr = romanStr.replacingOccurrences(of:$0, with:"")
}
}
romanStr.forEach {
out += dic[String($0)]!
}
return out
}
func romanToInt(_ s: String) -> Int {
let dic = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
var idx = 0, out = 0
while idx <= s.count-1 {
let v0 = dic[String(s[s.index(s.startIndex, offsetBy: idx)])]!
let v1 = idx < s.count-1 ? dic[String(s[s.index(s.startIndex, offsetBy: idx+1)])]! : 0
out += v0 < v1 ? v1 - v0 : v0
idx += v0 < v1 ? 2 : 1
}
return out
}
}
// v1
//Runtime: 76 ms, faster than 5.22% of Swift online submissions for Roman to Integer.
//Memory Usage: 15.9 MB, less than 10.22% of Swift online submissions for Roman to Integer.
// final version
//Runtime: 24 ms, faster than 73.70% of Swift online submissions for Roman to Integer.
//Memory Usage: 14.3 MB, less than 80.22% of Swift online submissions for Roman to Integer.
<file_sep>/Friday-algorithm/programmers_12901.swift
//
// programmers_12901.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/13.
//
// https://programmers.co.kr/learn/courses/30/lessons/12901
import Foundation
// from stackoverflow
func getDayOfWeek(today:String) -> String {
let weekdays = ["SUN","MON","TUE","WED","THU","FRI","SAT"]
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let todayDate = formatter.date(from: today) else { return "ERROR" }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekdays[weekDay-1] // weekDay uses 1 based index
}
func solution12901_general(_ a:Int, _ b:Int) -> String {
let month = a < 10 ? "0"+String(a) : String(a)
let day = b < 10 ? "0"+String(b) : String(b)
return getDayOfWeek(today:"2016-\(month)-\(day)")
}
// this works for 2016 only
func solution12901_2016(_ month:Int, _ day:Int) -> String {
let weekdays = ["SUN","MON","TUE","WED","THU","FRI","SAT"]
let monthDays = [31,29,31,30,31,30,31,31,30,31,30,31] // 2016 윤년
let startIdx = 5 // 2016-01-01 is Friday
let dayofYear2016 = monthDays[..<(month-1)].reduce(0,+) + day - 1
return weekdays[(dayofYear2016+startIdx)%7]
}
func test12901() -> Bool {
// print(solution12901_general(5,24))
// print(solution12901_2016(5,24))
// print(solution12901_2016(1,1))
return solution12901_2016(5,24) == "TUE"
}
<file_sep>/Friday-algorithm/programmers_12910.swift
//
// programmers_12910.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/13.
//
// https://programmers.co.kr/learn/courses/30/lessons/12910
import Foundation
func solution12910_old(_ arr:[Int], _ divisor:Int) -> [Int] {
var out = [Int]()
for num in arr {
if num%divisor == 0 {
out.append(num)
}
}
out.sort()
return out.count == 0 ? [-1] : out
}
func solution12910(_ arr:[Int], _ divisor:Int) -> [Int] {
let out = arr.sorted().filter{$0%divisor == 0}
return out.count == 0 ? [-1] : out
}
func test12910() -> Bool {
let testArr = [[[5,9,7,10],5, [5,10]],
[[2,36,1,3],1, [1,2,3,36]],
[[3,2,6], 10, [-1]]]
for ii in 0..<testArr.count {
guard testArr[ii][2] as! [Int] == solution12910(testArr[ii][0] as! [Int], testArr[ii][1] as! Int) else {
return false
}
}
return true
}
<file_sep>/Friday-algorithm/hackerrank_aVeryBigSum.swift
//
// hackerrank_aVeryBigSum.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/20.
//
import Foundation
func aVeryBigSum(ar: [Int]) -> Int {
return ar.reduce(0, +)
}
<file_sep>/Friday-algorithm/main.swift
//
// main.swift
// algorithm_main
//
// Created by <NAME> on 2020/11/06.
//
import Foundation
/// 20201106
//p1000()
//p1008()
//p2438()
//p2920()
//p8958()
//p11654()
/// 20201113
//print(test12910())
//print(test64061())
//print(test68644())
//print(test42840())
//print(test12901())
//print(test12928())
/// 20201120
//print(solveMeFirst(1, 2) == 3 ? "PASS" : "FAIL")
//
//let originalGrade = [73, 67, 38, 33]
//print(gradingStudents(grades: originalGrade))
//print(gradingStudents(grades: originalGrade) == [75, 67, 40, 33] ? "PASS" : "FAIL")
//
//let a = [17, 28, 30]
//let b = [99, 16, 8]
//print(compareTriplets(a: a, b: b) == [2, 1] ? "PASS" : "FAIL")
//
//let arr = [1000000001, 1000000002, 1000000003, 1000000004, 1000000005]
//print(aVeryBigSum(ar: arr) == 5000000015 ? "PASS" : "FAIL")
//
//print(timeConversion(s: "07:05:45PM") == "19:05:45" ? "PASS" : "FAIL")
//
//print(kangaroo(x1: 0, v1: 3, x2: 4, v2: 2) == "YES" ? "PASS" : "FAIL")
//print(kangaroo(x1: 0, v1: 2, x2: 5, v2: 3) == "NO" ? "PASS" : "FAIL")
/// 20201127
print("Two Sum")
let mysol1 = LeetTwoSum()
print(mysol1.twoSum([3,2,4], 6) == [1,2] ? "PASS" : "FAILED")
print("\nReverse Number")
let mysol2 = LeetReverseInteger()
print(mysol2.reverse(123) == 321 ? "PASS" : "FAILED")
print(mysol2.reverse(-123) == -321 ? "PASS" : "FAILED")
print(mysol2.reverse(120) == 21 ? "PASS" : "FAILED")
print(mysol2.reverse(123) == 321 ? "PASS" : "FAILED")
print("\nPalindrome")
let mysol3 = PalindromeNumber()
print(mysol3.isPalindrome(1234321) == true ? "PASS" : "FAILED")
print(mysol3.isPalindrome(121) == true ? "PASS" : "FAILED")
print(mysol3.isPalindrome(-121) == false ? "PASS" : "FAILED")
print(mysol3.isPalindrome(10) == false ? "PASS" : "FAILED")
print(mysol3.isPalindrome(-101) == false ? "PASS" : "FAILED")
print(mysol3.isPalindrome(1001) == true ? "PASS" : "FAILED")
print("\nRoman To Int")
let mysol4 = Roman()
print(mysol4.romanToInt("III") == 3 ? "PASS" : "FAILED")
print(mysol4.romanToInt("IV") == 4 ? "PASS" : "FAILED")
print(mysol4.romanToInt("IX") == 9 ? "PASS" : "FAILED")
print(mysol4.romanToInt("LVIII") == 58 ? "PASS" : "FAILED")
print(mysol4.romanToInt("MCMXCIV") == 1994 ? "PASS" : "FAILED")
print(mysol4.romanToInt("MDCXCV") == 1695 ? "PASS" : "FAILED")
print(mysol4.romanToInt("D") == 500 ? "PASS" : "FAILED")
print("\nLongest Common Prefix")
let mysol5 = LongestCP()
print(mysol5.longestCommonPrefix(["flower","flow","flight"]) == "fl" ? "PASS" : "FAILED")
print(mysol5.longestCommonPrefix(["dog","racecar","car"]) == "" ? "PASS" : "FAILED")
print(mysol5.longestCommonPrefix(["",""]) == "" ? "PASS" : "FAILED")
print(mysol5.longestCommonPrefix(["ab","a"]) == "a" ? "PASS" : "FAILED")
print("\nMerge Two Sorted Lists")
let mlist = MergeTwoSortedLists()
let list0 = mlist.genNode([1,2,4,5,5,6,20])
let list1 = mlist.genNode([1,3,5,9,10])
let outNode = mlist.mergeTwoLists(list0, list1)
mlist.printNode(outNode)
<file_sep>/Friday-algorithm/programmers_64061.swift
//
// programmers_64061.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/13.
//
// https://programmers.co.kr/learn/courses/30/lessons/64061
import Foundation
func solution64061(_ board:[[Int]], _ moves:[Int]) -> Int {
var boardCopy = board
var basket = [Int]()
var numDisappeared = 0
for move in moves {
let col = move - 1
if let row = boardCopy.firstIndex(where: { $0[...][col] != 0 }) {
basket.append(boardCopy[row][col])
boardCopy[row][col] = 0
if basket.count >= 2 && basket[basket.count - 1] == basket[basket.count - 2] {
numDisappeared += 2
_ = basket.popLast()
_ = basket.popLast()
}
}
}
return numDisappeared
}
func test64061() -> Bool {
let out = solution64061([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]],
[1,5,3,5,1,2,1,4])
return out == 4 ? true : false
}
<file_sep>/Friday-algorithm/p11654.swift
//
// p11654.swift
// algorithm_main
//
// Created by <NAME> on 2020/11/06.
//
// https://www.acmicpc.net/problem/11654
// ascii code
import Foundation
func p11654() {
let inStr = readLine()!
let s = inStr.unicodeScalars
print(Int(s[s.startIndex].value))
}
<file_sep>/Friday-algorithm/p1000.swift
//
// p1000.swift
// algorithm_main
//
// Created by <NAME> on 2020/11/06.
//
// https://www.acmicpc.net/problem/1000
import Foundation
func p1000(msg:Bool = false) {
if msg {print("Input two positive integers less than 10, separated with a space")}
let inStr = readLine()!
if msg {
guard inStr.contains(" ") && inStr.split(separator:" ").count == 2 else {
print("Error, must input two positive integers less than 10, separated by a space")
return p1000()
}
}
var out = 0
for ii in inStr.split(separator: " ") {
if msg {
guard Int(ii) != nil && Int(ii)! > 0 && Int(ii)! < 10 else {
print("Error, must input two positive integers less than 10, separated by a space")
return p1000()
}
}
out += Int(ii)!
}
print(out)
}
<file_sep>/Friday-algorithm/hackerrank_numberLineJumps.swift
//
// hackerrank_numberLineJumps.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/20.
//
import Foundation
func kangaroo(x1: Int, v1: Int, x2: Int, v2: Int) -> String {
return v2 >= v1 || (x2-x1)%(v1-v2) != 0 ? "NO" : "YES"
}
<file_sep>/Friday-algorithm/p8958.swift
//
// p8958.swift
// algorithm_main
//
// Created by <NAME> on 2020/11/06.
//
// https://www.acmicpc.net/problem/8958
// OX quiz
import Foundation
func score(testStr:String) -> Int {
var total = 0
var streak = 0
for ox in testStr {
if ox == "O" {
streak += 1
total += streak
} else {
streak = 0
}
}
return total
}
func p8958(check:Bool = false) {
if check {
print("Input number of test cases")
}
let numTest = Int(readLine()!)!
for _ in 0..<numTest {
print(score(testStr: readLine()!))
}
}
<file_sep>/Friday-algorithm/hackerrank_compareTheTriplets.swift
//
// hackerrank_compareTheTriplets.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/20.
//
import Foundation
func compareTriplets(a: [Int], b: [Int]) -> [Int] {
var asum = 0, bsum = 0
for (ascore, bscore) in zip(a, b) {
asum += ascore > bscore ? 1 : 0
bsum += ascore < bscore ? 1 : 0
}
return [asum, bsum]
}
<file_sep>/Friday-algorithm/hackerrank_grading_students.swift
//
// hackerrank_grading_students.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/20.
//
import Foundation
func gradingStudents_old(grades: [Int]) -> [Int] {
var out = [Int]()
for grade in grades {
if grade < 38 {
out.append(grade)
} else {
let rem = grade%5
switch rem {
case 3,4:
out.append(grade+5-rem)
default:
out.append(grade)
}
}
}
return out
}
// using closure, inspried by Hong
func gradingStudents(grades: [Int]) -> [Int] {
grades.map { $0 < 38 ? $0 : $0%5 >= 3 ? $0 + 5 - $0%5 : $0 }
}
<file_sep>/Friday-algorithm/programmers_12928.swift
//
// programmers_12928.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/13.
//
// https://programmers.co.kr/learn/courses/30/lessons/12928
import Foundation
func solution12928(_ n:Int) -> Int {
switch n {
case 0:
return 0
case 1:
return 1
case 2,3:
return n+1
default:
break
}
var factorSum = 1 + n
for ii in 2...n/2 {
factorSum += (n%ii == 0) ? ii : 0
}
return factorSum
}
func test12928() -> Bool {
let testArr = [[12, 28],
[5, 6]]
for test in testArr {
guard solution12928(test[0]) == test[1] else {
return false
}
}
return true
}
<file_sep>/Friday-algorithm/programmers_42840.swift
//
// programmers_42840.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/13.
//
// https://programmers.co.kr/learn/courses/30/lessons/42840
import Foundation
func supojaAnsScore(answers:[Int], method:Int) -> Int {
let counts = answers.count
var score = 0
switch method {
case 1:
for ii in 0..<counts {
score += answers[ii] == ii%5+1 ? 1 : 0
}
return score
case 2:
let choice = [1,3,4,5]
for ii in 0..<counts {
switch ii {
case ii where ii%2 == 0:
score += answers[ii] == 2 ? 1 : 0
case ii where ii%2 == 1:
score += answers[ii] == choice[((ii-1)/2)%4] ? 1 : 0
default:
break
}
}
return score
case 3:
let choice = [3,3,1,1,2,2,4,4,5,5]
for ii in 0..<counts {
score += answers[ii] == choice[ii%choice.count] ? 1 : 0
}
return score
default:
return -1
}
}
func solution42840(_ answers:[Int]) -> [Int] {
var scoreArr = [Int]()
for supoja in 1...3 {
scoreArr.append(supojaAnsScore(answers: answers, method: supoja))
}
let maxScore = scoreArr.max()
var out = [Int]()
for ii in 0..<3 {
if scoreArr[ii] == maxScore {
out.append(ii+1)
}
}
return out.sorted()
}
func test42840() -> Bool {
let testArr = [[[1,2,3,4,5], [1]],
[[1,3,2,4,2], [1,2,3]]]
for test in testArr {
guard solution42840(test[0]) == test[1] else {
return false
}
}
return true
}
<file_sep>/Friday-algorithm/hackerrank_SolveMeFirst.swift
//
// hackerrank_SolveMeFirst.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/20.
//
import Foundation
let solveMeFirst = { (a: Int, b: Int) in return a+b }
<file_sep>/Friday-algorithm/programmers_68644.swift
//
// programmers_68644.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/13.
//
// https://programmers.co.kr/learn/courses/30/lessons/68644
import Foundation
func solution68644(_ numbers:[Int]) -> [Int] {
let arrSize = numbers.count
var out = Set<Int>()
for ii in 0..<arrSize - 1 {
for jj in ii + 1..<arrSize {
out.update(with:numbers[ii] + numbers[jj])
}
}
return Array(out).sorted()
}
func test68644() -> Bool {
let testArr = [[[2,1,3,4,1], [2,3,4,5,6,7]],
[[5,0,2,7], [2,5,7,9,12]]]
for test in testArr {
guard solution68644(test[0]) == test[1] else {
return false
}
}
return true
}
<file_sep>/Friday-algorithm/leetcode_ReverseNumber.swift
//
// leetcode_ReverseNumber.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/27.
//
/*
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
*/
import Foundation
class LeetReverseInteger {
func reverse(_ x: Int) -> Int {
let out: Int
let limit = 2147483648 // 2**31
switch x {
case x where x > 0:
out = reversePositiveNum(x)
case x where x < 0:
out = -reversePositiveNum(-x)
default:
return 0
}
return out >= -limit && out <= limit-1 ? out : 0
}
func reversePositiveNum(_ x: Int) -> Int {
var no0 = x
while no0%10 == 0 {
no0 /= 10
}
return Int(String(String(no0).reversed()))!
}
}
//Runtime: 4 ms, faster than 91.24% of Swift online submissions for Reverse Integer.
//Memory Usage: 13.7 MB, less than 93.93% of Swift online submissions for Reverse Integer.
<file_sep>/Friday-algorithm/leetcode_LongestCommonPrefix.swift
//
// leetcode_LongestCommonPrefix.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/27.
//
/*
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
*/
import Foundation
class LongestCP {
func longestCommonPrefix(_ strs: [String]) -> String {
switch strs.count {
case 0:
return ""
case 1:
return strs[0]
default:
break
}
var minLen = strs.map{$0.count}.min()!
guard minLen != 0 else {return ""}
let str0 = strs[0]
for idx in 1..<strs.count {
for ii in 0 ..< minLen {
if str0[str0.index(str0.startIndex, offsetBy: ii)] !=
strs[idx][strs[idx].index(strs[idx].startIndex, offsetBy: ii)] {
minLen = min(minLen, ii)
guard minLen != 0 else {return ""}
break
}
}
}
return String(str0[str0.startIndex ..< str0.index(str0.startIndex, offsetBy: minLen)])
}
}
//Runtime: 40 ms, faster than 33.50% of Swift online submissions for Longest Common Prefix.
//Memory Usage: 14 MB, less than 94.12% of Swift online submissions for Longest Common Prefix.
<file_sep>/Friday-algorithm/p1008.swift
//
// p1008.swift
// algorithm_main
//
// Created by <NAME> on 2020/11/06.
//
// https://www.acmicpc.net/problem/1008
// A/B
import Foundation
func p1008(msg:Bool = false) {
if msg {
print("Input two positive integers less than 10, separated with a space")
}
let inStr = readLine()!
guard inStr.contains(" ") && inStr.split(separator:" ").count == 2 else {
print("Error, must input two positive integers less than 10, separated by a space")
return p1008()
}
let numArr = inStr.split(separator:" ")
for ii in 0...1 {
guard Int(numArr[ii]) != nil && Int(numArr[ii])! > 0 && Int(numArr[ii])! < 10 else {
print("Error, must input two positive integers less than 10, separated by a space")
return p1008()
}
}
print(Double(numArr[0])!/Double(numArr[1])!)
}
<file_sep>/Friday-algorithm/p2920.swift
//
// p2920.swift
// algorithm_main
//
// Created by <NAME> on 2020/11/06.
//
// https://www.acmicpc.net/problem/2920
// 음계
import Foundation
func p2920(msg:Bool = false) {
let inputMsg = "Input 8 integer notes separated by spaces. Each notes must be in the range 1 <= n <= 8"
let invalidMsg = "Error: Invalid input"
if msg {
print(inputMsg)
}
let inStr = readLine()!
// check input
if msg {
guard inStr.split(separator: " ").count == 8 else {
print(invalidMsg)
return p2920()
}
}
let inArr = inStr.split(separator: " ")
if msg {
for noteStr in inArr {
guard Int(noteStr) != nil && Int(noteStr)! >= 1 && Int(noteStr)! <= 8 else {
print(invalidMsg)
return p2920()
}
}
}
let ascendingArr = "1 2 3 4 5 6 7 8".split(separator: " ")
let descendingArr = "8 7 6 5 4 3 2 1".split(separator: " ")
switch inArr {
case ascendingArr:
print("ascending")
case descendingArr:
print("descending")
default:
print("mixed")
}
}
<file_sep>/Friday-algorithm/hackerrank_timeConversion.swift
//
// hackerrank_timeConversion.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/20.
//
import Foundation
func timeConversion(s: String) -> String {
let isPM = s.contains("PM")
var timeArr = s.replacingOccurrences(of: "PM", with: "")
.replacingOccurrences(of: "AM", with: "")
.split(separator: ":")
.compactMap { Int($0) }
timeArr[0] %= 12
timeArr[0] += isPM ? 12 : 0
return String(format: "%02d:%02d:%02d", timeArr[0], timeArr[1], timeArr[2])
}
<file_sep>/Friday-algorithm/leetcode_MergeTwoSortedLists.swift
//
// leet_MergeTwoSortedLists.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/27.
//
/*
Merge two sorted linked lists and return it as a new sorted list.
The new list should be made by splicing together the nodes of the first two lists.
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both l1 and l2 are sorted in non-decreasing order.
*/
import Foundation
public class ListNode {
public var val: Int
public var next: ListNode?
public init() { self.val = 0; self.next = nil; }
public init(_ val: Int) { self.val = val; self.next = nil; }
public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
}
// from Lia's code
class MergeTwoSortedLists {
var mergeNode: ListNode?
func genNode(_ arr: [Int]) -> ListNode {
var outNode = ListNode(arr[0])
if arr.count > 1 {
for ii in 1..<arr.count {
outNode = appendNode(outNode, ListNode(arr[ii]))
}
}
return outNode
}
func appendNode(_ originalNode: ListNode, _ appendNode: ListNode) -> ListNode {
var originalCopy = originalNode
while originalCopy.next != nil {
originalCopy = originalCopy.next!
}
originalCopy.next = appendNode
return originalNode
}
func insertNext(_ value: Int) {
if mergeNode == nil {
mergeNode = ListNode(value)
} else {
var copy1 = mergeNode
while copy1!.next != nil {
copy1 = copy1!.next
}
copy1!.next = ListNode(value)
}
}
func printNode(_ myNode: ListNode?) {
var nodeCopy = myNode
print("[", terminator: "")
while nodeCopy != nil {
print(nodeCopy!.val, terminator: ", ")
nodeCopy = nodeCopy!.next
}
print("nil]")
}
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil { return l2 }
if l2 == nil { return l1 }
var l1copy = l1
var l2copy = l2
while l1copy != nil && l2copy != nil {
if l1copy!.val <= l2copy!.val {
insertNext(l1copy!.val)
l1copy = l1copy!.next
} else {
insertNext(l2copy!.val)
l2copy = l2copy!.next
}
}
// if either one of the list is exhausted, append the other
switch (l1copy == nil, l2copy == nil) {
case (false, true):
mergeNode = appendNode(mergeNode!, l1copy!)
case (true, false):
mergeNode = appendNode(mergeNode!, l2copy!)
default:
break
}
return mergeNode
}
}
//Runtime: 24 ms, faster than 5.01% of Swift online submissions for Merge Two Sorted Lists.
//Memory Usage: 14 MB, less than 38.78% of Swift online submissions for Merge Two Sorted Lists.
<file_sep>/Friday-algorithm/p2438.swift
//
// p2438.swift
// algorithm_main
//
// Created by <NAME> on 2020/11/06.
//
// https://www.acmicpc.net/problem/2438
// 별찍기
import Foundation
func p2438(check:Bool = false) {
if check {
print("Input number of lines (1 <= N <= 100)")
}
let linesStr = readLine()!
if check {
guard Int(linesStr) != nil && Int(linesStr)! >= 1 && Int(linesStr)! <= 100 else {
print("Invalid input")
return p2438()
}
}
let lines = Int(linesStr)!
for line in 1...lines {
print(String(repeating: "*", count: line))
}
}
<file_sep>/Friday-algorithm/leetcode_PalindromeNumber.swift
//
// leetcode_PalindromeNumber.swift
// Friday-algorithm
//
// Created by <NAME> on 2020/11/27.
//
/*
Determine whether an integer is a palindrome.
An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
*/
import Foundation
class PalindromeNumber {
func isPalindrome(_ x: Int) -> Bool {
switch x {
case 0..<10:
return true
case x where x >= 10:
return isPalWithoutString(x)
// return isPalWithString(x)
default:
return false
}
}
func isPalWithoutString(_ x: Int) -> Bool {
var y = x
var digitArr = [Int]()
let digitNum = Int(log10(Float(x)))+1
var idx0 = digitNum/2 - 1
var idx1 = Int(ceil(Double(digitNum)/2))
var idx = 0
while y != 0 {
if idx >= idx1 {
guard digitArr[idx0] == y%10 else {return false}
idx0 -= 1
idx1 += 1
} else {
digitArr.append(y%10)
}
y /= 10
idx += 1
}
return true
}
func isPalWithString(_ x: Int) -> Bool {
let xStr = String(x)
let firstHalf = xStr[xStr.startIndex ..< xStr.index(xStr.startIndex, offsetBy: xStr.count/2)]
let otherHalfReveresd = String(String(xStr[xStr.index(xStr.startIndex, offsetBy: Int(ceil(Double(xStr.count)/2)))...]).reversed())
return firstHalf == otherHalfReveresd
}
}
// isPalWithoutString
//Runtime: 44 ms, faster than 67.74% of Swift online submissions for Palindrome Number.
//Memory Usage: 14.8 MB, less than 5.41% of Swift online submissions for Palindrome Number.
// isPalWithString
//Runtime: 52 ms, faster than 46.29% of Swift online submissions for Palindrome Number.
//Memory Usage: 14.3 MB, less than 32.87% of Swift online submissions for Palindrome Number.
| 52c6d02409cc027c4bc7da463ce0c22314333e9f | [
"Swift"
] | 25 | Swift | tjdoc/Friday-algorithm | 683fb2ebe68363df8855afb6a5b343677c91008b | e005e9d31c3f4e4d6b22b4731221d5c78ce1032f |
refs/heads/master | <file_sep># MIT Confessions analysis
I scraped all published posts from [MIT Confessions](https://www.facebook.com/beaverconfessions/) using [this scraper](https://github.com/minimaxir/facebook-page-post-scraper/blob/master/get_fb_posts_fb_page.py); that data is stored in [confessions_posts.csv](confessions_posts.csv).
[bulk.py](bulk.py) is for analyzing time series of all posts, reactions, etc.
[filtered.py](filtered.py) is for analyzing confessions filtered to contain a specific phrase, specified by "phrase" under "User Inputs."
Enable:
* "print_all" to have all posts containing the specified phrase printed to the console
* "output_file" for relevant post info be outputted to a new csv file
* either/both of the two "graph_..." variables (script has details) for a timeseries of responses (likes, comments, etc.) to those posts
## To Do:
* Scrape [MIT Timely Confessions](https://www.facebook.com/timelybeaverconfessions/) and [MIT Summer Confessions](https://www.facebook.com/MITSummerConfessions/)
* Better smoothing method, generally make plots better<file_sep>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from dateutil import parser
from scipy.signal import savgol_filter
from scipy.interpolate import interp1d
""" User Inputs """
# replace with weeks,months,or years
bin_by = 'months'
# enable which graphs?
posts = False
comments = False
total_reactions = False
reaction_breakdown = True
""" and so it begins """
# read data from csv into DataFrame
df = pd.read_csv("confessions_posts.csv",keep_default_na=False)
df['lowercase'] = df['status_message'].str.lower()
df['datetime'] = df['status_published'].apply(parser.parse)
days = (df.iloc[0]['datetime']-df.iloc[3448]['datetime']).days
binning = {'days':days,'weeks':days/7,'months':days/30.44,'years':days/365.2425}
title = ''
if posts:
title+='Posts' if title =='' else ' + Posts'
plt.hist(df['datetime'],bins=binning[bin_by],label='Posts')
if comments:
title+='Comments' if title =='' else ' + Comments'
plt.plot(df['datetime'],df['num_comments'],label='Comments')
if total_reactions:
title+='Reactions Aggregate' if title =='' else ' + Reactions Aggregate'
plt.plot(df['datetime'],df['num_reactions'],label='Reactions')
if reaction_breakdown:
if title == '':
plt.ylim(ymin=0,ymax=150)
title+='Reactions Breakdown' if title =='' else ' + Reactions Breakdown'
def prep_col(column_name,n):
array = np.array(df[column_name])
new_array = np.empty_like(array)
for i in range(len(array)):
newval = np.mean(array[0:i+n+1]) if n > i else np.mean(array[i-n:i+n+1])
new_array[i] = newval
result = new_array
return new_array
plt.stackplot(np.array(df['datetime']),
[prep_col(i,10) for i in ['num_angrys','num_loves','num_sads','num_hahas','num_likes']],
labels=['Angrys','Loves','Sads','Hahas','Likes'],baseline='zero',
colors=['#fc7616','#f4428c','#36aaf7','#ffe100','#00d8ff'])
n = 5
array = np.array(df['num_likes'])
new_array = np.empty_like(array)
for i in range(len(array)):
newval = np.mean(array[0:i+n+1]) if n > i else np.mean(array[i-n:i+n+1])
new_array[i] = newval
result = new_array
if posts or comments or total_reactions or reaction_breakdown:
plt.title(title)
plt.xlabel('Time')
plt.ylabel('Number')
plt.legend(loc=2)
plt.show()
<file_sep>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from dateutil import parser
""" User Inputs """
# filter by whether confessions include a specified phrase
phrase = 'hello'
# print all the confessions that contain your phrase?
print_all = False
# export all the confessions that contain your phrase to a text file?
output_file = False
# graph all reactions and comments over time?
reactions_comments = False
# graph likes vs. loves vs. etc over time?
reaction_breakdown = False
""" and so it begins """
# read data from csv into DataFrame
df = pd.read_csv("confessions_posts.csv",keep_default_na=False)
df['datetime'] = df['status_published'].apply(parser.parse)
df['lowercase'] = df['status_message'].str.lower()
# filter by posts that contain a specific phrase
filtered = df[df['lowercase'].str.contains(phrase)]
print('Total confessions containing "'+phrase+'": '+str(len(filtered)))
# print and/or write results
if output_file:
output = open("output.csv", "w")
for index,row in filtered.iterrows():
if print_all:
print(str(row['status_published'])+': '+str(row['status_message'])+'\n')
if output_file:
filtered.to_csv('output.csv')
if output_file:
output.close()
# plot responses
if reactions_comments:
plt.plot(filtered['datetime'],filtered['num_reactions'],label="All reactions")
plt.plot(filtered['datetime'],filtered['num_comments'],label="Comments")
if reaction_breakdown:
plt.plot(filtered['datetime'],filtered['num_likes'],label="Likes")
plt.plot(filtered['datetime'],filtered['num_loves'],label="Loves")
plt.plot(filtered['datetime'],filtered['num_hahas'],label="Hahas")
plt.plot(filtered['datetime'],filtered['num_sads'],label="Sads")
plt.plot(filtered['datetime'],filtered['num_angrys'],label="Angrys")
# uncomment this if you want shares, didn't put it as a user input because I thought people wouldn't care as much
# plt.plot(filtered['datetime'],filtered['num_shares'],label="Shares")
if reactions_comments or reaction_breakdown:
plt.title('Responses to confessions containing "'+phrase+'"')
plt.xlabel('Time')
plt.ylabel('Number')
plt.legend()
plt.show()
| 6abee65d3b34c43ca7f0b754d7662bbacfacfd86 | [
"Markdown",
"Python"
] | 3 | Markdown | cminsky/MIT-Confessions-analysis | b6bf7eae56e8f6cb7cd8ee12ff36e06604e99f5e | b7e8c17b9dfb458beb1c5373a6e4fbc291e28325 |
refs/heads/master | <repo_name>jackdempsey/find_rails<file_sep>/find_rails
#!/usr/bin/env ruby
require 'find'
require 'rubygems'
require 'thor'
# Take a directory, and a list of patterns to match, and a list of
# filenames to avoid
def recursive_search(dir,patterns, excludes=[/\.git/, /\.svn/, /,v$/, /\.cvs$/, /\.tmp$/, /^RCS$/, /^SCCS$/, /~$/])
results = Hash.new{|h,k| h[k] = ''}
Find.find(dir) do |path|
fb = File.basename(path)
next if excludes.any?{|e| fb =~ e}
if File.directory?(path)
if fb =~ /\.{1,2}/
Find.prune
else
next
end
else # file...
File.open(path, 'r') do |f|
ln = 1
while (line = f.gets)
patterns.each do |p|
if !line.scan(p).empty?
results[p] += "#{path}:#{ln}:#{line}"
end
end
ln += 1
end
end
end
end
return results
end
class FindRails < Thor
desc 'conversion [PATH_TO_APP]', "Checks your code and prints out which methods will need to change"
def conversion(path_to_app='.')
conversions = {
'before_filter' => 'Use before',
'after_filter' => 'Use after',
'render :partial' => 'Use partial',
'redirect_to' => 'Use redirect',
'url_for' => 'Use url',
/redirect.*?return/ => "You want to 'return redirect(...)' not 'redirect and return'"
}
dir_to_search = File.expand_path('app', path_to_app)
if !File.exists?(dir_to_search)
puts "#{dir_to_search} doesn't exist. Make sure you're in your merb app top level, or pass in a path to the app"
return
end
results = recursive_search(dir_to_search,conversions.keys)
conversions.each do |key, warning|
puts '--> ' + key.to_s.gsub('?-mix:','') # clean up what the regexp.to_s looks like
unless results[key] =~ /^$/
puts " !! " + warning + " !!"
puts ' ' + '.' * (warning.length + 6)
puts results[key]
else
puts " Clean! Cheers for you!"
end
puts
end
end
end
FindRails.new.conversion(ARGV.to_s) | 88b1537b42ccd75a8f4a640062bbf37df8646fd6 | [
"Ruby"
] | 1 | Ruby | jackdempsey/find_rails | a8569e1d113bf9d19686f7e80154ec3ab68911df | 1e92df73cc8643bd3faaf30db7dfa90bbbf5b1ed |
refs/heads/master | <file_sep>namespace SpriteKind {
export const house = SpriteKind.create()
export const villager = SpriteKind.create()
}
sprites.onOverlap(SpriteKind.house, SpriteKind.house, function (sprite, otherSprite) {
tiles.placeOnRandomTile(otherSprite, myTiles.tile2)
})
sprites.onOverlap(SpriteKind.Player, SpriteKind.villager, function (sprite, otherSprite) {
if (mySprite.vx < 0) {
mySprite.x += 10
} else if (mySprite.vx > 0) {
mySprite.x += -10
} else if (mySprite.vy > 0) {
mySprite.y += -10
} else if (mySprite.vy < 0) {
mySprite.y += 10
}
if (Math.percentChance(50)) {
game.showLongText("hi!", DialogLayout.Bottom)
} else if (Math.percentChance(50)) {
game.showLongText("how are you doing?", DialogLayout.Bottom)
} else if (Math.percentChance(50)) {
game.showLongText("what's up?", DialogLayout.Bottom)
} else if (Math.percentChance(50)) {
game.showLongText("have a good day!", DialogLayout.Bottom)
} else if (Math.percentChance(50)) {
game.showLongText("hello.", DialogLayout.Bottom)
} else {
game.showLongText("leave me alone.", DialogLayout.Bottom)
if (game.ask("ask whats going on?")) {
game.showLongText("my...", DialogLayout.Bottom)
game.showLongText("my...", DialogLayout.Bottom)
game.showLongText("my...", DialogLayout.Bottom)
game.showLongText("my fish is dead!", DialogLayout.Bottom)
game.showLongText("waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!", DialogLayout.Bottom)
}
}
})
let mySprite4: Sprite = null
let mySprite2: Sprite = null
let mySprite: Sprite = null
mySprite = sprites.create(img`
. . 2 f 2 f 2 f 2 f . .
. f f f f f f f f f f .
2 f 2 f 2 f 2 f 2 f 2 f
f f f f f f f f f f f f
2 f 2 f 2 f 2 f 2 f 2 f
2 2 2 2 2 2 2 2 2 2 2 2
f f f b f e e f b f f f
. f 4 1 f 4 4 f 1 4 f .
. f e 4 4 4 4 4 4 e f .
. f f f e e e e f f f .
f e f b 7 7 7 7 b f e f
e 4 f 7 7 7 7 7 7 f 4 e
e e f 6 6 6 6 6 6 f e e
. . . f f f f f f . . .
. . . f f . . f f . . .
`, SpriteKind.Player)
tiles.setTilemap(tiles.createTilemap(hex`1000100001010101030303030303010101010101010303030303050505030303030303010103050505030502050303050505030101030502050505050503030502050301010305050505030303030305050503010103030303030303030303030303030103030303030305050503030303030303030303030303050205030305050503030303030303030505050303050405030303030303030303030303030505050303030303030303050505030303030303030105050503030502050303050505030101050205030305050503030502050301010505050303050505030305050503010103030303030502050303030303030101010101030305050505030101010101`, img`
2 2 2 2 . . . . . . 2 2 2 2 2 2
2 . . . . . . . . . . . . . . 2
2 . . . . . 2 2 2 . . . . . . 2
2 . 2 2 2 . 2 2 2 . . 2 2 2 . 2
2 . 2 2 2 . . . . . . 2 2 2 . 2
2 . . . . . . . . . . . . . . 2
. . . . . . . . . . . . . . . .
. . . . . . 2 2 2 . . . . . . .
. . . . . . 2 2 2 . . 2 2 2 . .
. . . . . . . . . . . 2 2 2 . .
. . . . . . . . . . . . . . . .
2 . . . . . 2 2 2 . . . . . . 2
2 2 2 2 . . 2 2 2 . . 2 2 2 . 2
2 2 2 2 . . . . . . . 2 2 2 . 2
2 . . . . . 2 2 2 . . . . . . 2
2 2 2 2 . . 2 2 2 . . 2 2 2 2 2
`, [myTiles.transparency16,myTiles.tile1,myTiles.tile2,sprites.castle.tilePath5,myTiles.tile3,myTiles.tile4], TileScale.Sixteen))
controller.moveSprite(mySprite)
scene.cameraFollowSprite(mySprite)
scene.setBackgroundColor(9)
for (let index = 0; index < 8; index++) {
mySprite2 = sprites.create(img`
....................e2e22e2e....................
.................222eee22e2e222.................
..............222e22e2e22eee22e222..............
...........e22e22eeee2e22e2eeee22e22e...........
........eeee22e22e22e2e22e2e22e22e22eeee........
.....222e22e22eeee22e2e22e2e22eeee22e22e222.....
...22eeee22e22e22e22eee22eee22e22e22e22eeee22...
4cc22e22e22eeee22e22e2e22e2e22e22eeee22e22e22cc4
6c6eee22e22e22e22e22e2e22e2e22e22e22e22e22eee6c6
46622e22eeee22e22eeee2e22e2eeee22e22eeee22e22664
46622e22e22e22eeee22e2e22e2e22eeee22e22e22e22664
4cc22eeee22e22e22e22eee22eee22e22e22e22eeee22cc4
6c622e22e22eeee22e22e2e22e2e22e22eeee22e22e226c6
466eee22e22e22e22e22e2e22e2e22e22e22e22e22eee664
46622e22eeee22e22e22e2e22e2e22e22e22eeee22e22664
4cc22e22e22e22e22eeee2e22e2eeee22e22e22e22e22cc4
6c622eeee22e22eeee22eee22eee22eeee22e22eeee226c6
46622e22e22eeee22e22e2e22e2e22e22eeee22e22e22664
466eee22e22e22e22e22e2e22e2e22e22e22e22e22eee664
4cc22e22eeee22e22e22e2e22e2e22e22e22eeee22e22cc4
6c622e22e22e22e22e22eee22eee22e22e22e22e22e226c6
46622eeee22e22e22eeecc6666cceee22e22e22eeee22664
46622e22e22e22eeecc6666666666cceee22e22e22e22664
4cceee22e22eeecc66666cccccc66666cceee22e22eeecc4
6c622e22eeecc66666cc64444446cc66666cceee22e226c6
46622e22cc66666cc64444444444446cc66666cc22e22664
46622cc6666ccc64444444444444444446ccc6666cc22664
4ccc6666ccc6444bcc666666666666ccb4446ccc6666ccc4
cccccccc6666666cb44444444444444bc6666666cccccccc
64444444444446c444444444444444444c64444444444446
66cb444444444cb411111111111111114bc444444444bc66
666cccccccccccd166666666666666661dccccccccccc666
6666444444444c116eeeeeeeeeeeeee611c4444444446666
666e2222222e4c16e4e44e44e44e44ee61c4e2222222e666
666eeeeeeeee4c16e4e44e44e44e44ee61c4eeeeeeeee666
666eddddddde4c66f4e4effffffe44ee66c4eddddddde666
666edffdffde4c66f4effffffffff4ee66c4edffdffde666
666edccdccde4c66f4effffffffffeee66c4edccdccde666
666eddddddde4c66f4eeeeeeeeeeeeee66c4eddddddde666
c66edffdffde4c66e4e44e44e44e44ee66c4edffdffde66c
c66edccdccde4c66e4e44e44e44e44ee66c4edccdccde66c
cc66666666664c66e4e44e44e44feeee66c46666666666cc
.c66444444444c66e4e44e44e44ffffe66c44444444466c.
..c64eee4eee4c66f4e44e44e44f44fe66c4eee4eee46c..
...c4eee4eee4c66f4e44e44e44effee66c4eee4eee4c...
....644444444c66f4e44e44e44e44ee66c444444446....
.....64eee444c66f4e44e44e44e44ee66c444eee46.....
......6ccc666c66e4e44e44e44e44ee66c666ccc6......
`, SpriteKind.house)
tiles.placeOnRandomTile(mySprite2, myTiles.tile2)
}
let mySprite3 = sprites.create(img`
....................8a8aa8a8....................
.................aaa888aa8a8aaa.................
..............aaa8aa8a8aa888aa8aaa..............
...........8aa8aa8888a8aa8a8888aa8aa8...........
........8888aa8aa8aa8a8aa8a8aa8aa8aa8888........
.....aaa8aa8aa8888aa8a8aa8a8aa8888aa8aa8aaa.....
...aa8888aa8aa8aa8aa888aa888aa8aa8aa8aa8888aa...
dccaa8aa8aa8888aa8aa8a8aa8a8aa8aa8888aa8aa8aaccd
bcb888aa8aa8aa8aa8aa8a8aa8a8aa8aa8aa8aa8aa888bcb
dbbaa8aa8888aa8aa8888afaa8a8888aa8aa8888aa8aabbd
dbbaa8aa8aa8aa888faa8afaa8a8aa8888aa8aa8aa8aabbd
dccaaf8f8fffaf8faffa88faa8fffafaf8ff8afff88aaccd
bcbaafaf8faf8f8fafaa8afff8f8fafaf8f88af8fa8aabcb
dbb88fff8fffafffafaa8afaf8fffafff8ff8afffa888bbd
dbbaa8af8888aa8aa8aa8a8aa8a8aa8aa8af88f8aa8aabbd
dccaa8ff8aa8aa8aa8888a8aa8a8888aa8ff8afffa8aaccd
bcbaa8888aa8aa8888aa888aa888aa8888aa8aa8888aabcb
dbbaa8aa8aa8888aa8aa8a8aa8a8aa8aa8888aa8aa8aabbd
dbb888aa8aa8aa8aa8aa8a8aa8a8aa8aa8aa8aa8aa888bbd
dccaa8aa8888aa8aa8aa8a8aa8a8aa8aa8aa8888aa8aaccd
bcbaa8aa8aa8aa8aa8aa888aa888aa8aa8aa8aa8aa8aabcb
dbbaa8888aa8aa8aa888ccbbbbcc888aa8aa8aa8888aabbd
dbbaa8aa8aa8aa888ccbbbbbbbbbbcc888aa8aa8aa8aabbd
dcc888aa8aa888ccbbbbbccccccbbbbbcc888aa8aa888ccd
bcbaa8aa888ccbbbbbccbddddddbccbbbbbcc888aa8aabcb
dbbaa8aaccbbbbbccbddddddddddddbccbbbbbccaa8aabbd
dbbaaccbbbbcccbddddddddddddddddddbcccbbbbccaabbd
dcccbbbbcccbdddbccbbbbbbbbbbbbccbdddbcccbbbbcccd
ccccccccbbbbbbbcbddddddddddddddbcbbbbbbbcccccccc
bddddddddddddbcddddddddddddddddddcbddddddddddddb
bbcbdddddddddcbd1111111111111111dbcdddddddddbcbb
bbbcccccccccccd1bbbbbbbbbbbbbbbb1dcccccccccccbbb
bbbbdddddddddc11beeeeeeeeeeeeeeb11cdddddddddbbbb
bbb8aaaaaaa8dc1be3b33b33b33b33beb1cd8aaaaaaa8bbb
bbb888888888dc1be3b33b33b33b33beb1cd888888888bbb
bbb833333338dcbbf3b3effffffe33bebbcd833333338bbb
bbb83ff3ff38dcbbf3bffffffffff3bebbcd83ff3ff38bbb
bbb83cc3cc38dcbbf3effffffffffebebbcd83cc3cc38bbb
bbb833333338dcbbf3eeeeeeeeeeeebebbcd833333338bbb
cbb83ff3ff38dcbbe3b33b33b33b33bebbcd83ff3ff38bbc
cbb83cc3cc38dcbbe3b33b33b33b33bebbcd83cc3cc38bbc
ccbbbbbbbbbbdcbbe3b33b33b33feeeebbcdbbbbbbbbbbcc
.cbbdddddddddcbbe3b33b33b33ffffebbcdddddddddbbc.
..cbdbbbdbbbdcbbf3b33b33b33f33febbcdbbbdbbbdbc..
...cdbbbdbbbdcbbf3b33b33b33bffeebbcdbbbdbbbdc...
....bddddddddcbbf3b33b33b33b33bebbcddddddddb....
.....bdbbbdddcbbf3b33b33b33b33bebbcdddbbbdb.....
......bcccbbbcbbe3b33b33b33b33bebbcbbbcccb......
`, SpriteKind.house)
tiles.placeOnRandomTile(mySprite3, myTiles.tile3)
for (let index = 0; index < 4; index++) {
mySprite4 = sprites.create(img`
. f f f . f f f f . f f f .
f f f f f c c c c f f f f f
f f f f b c c c c b f f f f
f f f c 3 c c c c 3 c f f f
. f 3 3 c c c c c c 3 3 f .
. f c c c c 4 4 c c c c f .
. f f c c 4 4 4 4 c c f f .
. f f f b f 4 4 f b f f f .
. f f 4 1 f d d f 1 4 f f .
. . f f d d d d d d f f . .
. . e f e 4 4 4 4 e f e . .
. e 4 f b 3 3 3 3 b f 4 e .
. 4 d f 3 3 3 3 3 3 c d 4 .
. 4 4 f 6 6 6 6 6 6 f 4 4 .
. . . . f f f f f f . . . .
. . . . f f . . f f . . . .
`, SpriteKind.villager)
tiles.placeOnRandomTile(mySprite4, sprites.castle.tilePath5)
}
for (let index = 0; index < 4; index++) {
mySprite4 = sprites.create(img`
. . . . f f f f . . . .
. . f f f f f f f f . .
. f f f f f f c f f f .
f f f f f f c c f f f c
f f f c f f f f f f f c
c c c f f f e e f f c c
f f f f f e e f f c c f
f f f b f e e f b f f f
. f 4 1 f 4 4 f 1 4 f .
. f e 4 4 4 4 4 4 e f .
. f f f e e e e f f f .
f e f b 7 7 7 7 b f e f
e 4 f 7 7 7 7 7 7 f 4 e
e e f 6 6 6 6 6 6 f e e
. . . f f f f f f . . .
. . . f f . . f f . . .
`, SpriteKind.villager)
tiles.placeOnRandomTile(mySprite4, sprites.castle.tilePath5)
}
| 83aac247a57620ec3013471424635d92a41238be | [
"TypeScript"
] | 1 | TypeScript | rtator/village-talker | 08339e9922c92b685db574ec62a0303da7d44e2b | f880bc2a93a8ee10fb45b8cadb49af33bf4a73ee |
refs/heads/master | <repo_name>mlama007/1MadLibs<file_sep>/1MadLibs.py
"""This is a game of MadLibs. It will take the user's input and add it to out MadLibs story. ENJOY!"""
print "Let's get started with a gme of Mad Libs!!"
main_character = raw_input("What the name of your character? ")
adjective1 = raw_input("Give me an adjective: ")
adjective2 = raw_input("Give me an adjective: ")
adjective3 = raw_input("Give me an adjective: ")
verb1 = raw_input("Give me a verb: ")
verb2 = raw_input("Give me a verb: ")
verb3 = raw_input("Give me a verb: ")
noun1 = raw_input("Give me a noun: ")
noun2 = raw_input("Give me a noun: ")
noun3 = raw_input("Give me a noun: ")
noun4 = raw_input("Give me a noun: ")
animal = raw_input("Give me an animal: ")
food = raw_input("Give me a food: ")
fruit = raw_input("Give me a fruit: ")
number = raw_input("Give me a number: ")
superhero = raw_input("Give me a superhero name: ")
country = raw_input("Give me a country: ")
dessert = raw_input("Give me a dessert: ")
year = raw_input("Give me a year: ")
#The template for the story
STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to %s to the rythym of the %s, which made all of the %ss very %s. %s tried to %s into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping %s into a puddle of %s. %s then fell asleep and woke up in the year %s, in a world where %ss ruled the world." % (adjective1,main_character,verb1,adjective2,noun1,noun2,animal,food,verb2,noun3,fruit,adjective3,superhero,verb3,number,main_character,superhero,superhero,main_character,country,main_character,dessert,main_character,year,noun4)
print STORY
| 3ccf557054c36e6797352be29f5cebc59bdb2afb | [
"Python"
] | 1 | Python | mlama007/1MadLibs | 4fa8ccd5e18ac36890e66bbb1a10da99912adf7e | bff5ca2dca45cb09255c063185a737c931bfd1c1 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<Barcode> Get()
{
using (BarcodesEntities db = new BarcodesEntities())
{
return db.Barcodes.ToList();
}
}
// GET api/values/5
public Barcode Get(string id)
{
string code = id;
Barcode barcode = new Barcode();
using (BarcodesEntities db = new BarcodesEntities())
{
barcode = db.Barcodes.Where(x => x.Code.Equals(code)).FirstOrDefault();
}
return barcode;
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| c63a371768db429c0d2307bd4c20db5208eb32b7 | [
"C#"
] | 1 | C# | christmas96/BarcodesApi | 1e7afec311866688e405bb4c717d22b52e0c7ecb | 5192bc56b929ce759c3216c34e4e1956023b74b0 |
refs/heads/master | <file_sep>#!/bin/bash
if [ ! -f venv/bin/activate ]; then
python3 -m venv venv
fi
. venv/bin/activate
pip install -r requirements.txt
<file_sep># s3-sns-lambda-replay
A simple tool for replaying S3 file creation Lambda invocations. This is useful for backfill or replay on real-time ETL pipelines that run transformations in Lambdas triggered by S3 file creation events.
Steps:
1. Collect inputs from user
2. Scan S3 for filenames that need to be replayed
3. Batch S3 files into payloads for Lambda invocations
4. Spawn workers to handle individual Lambda invocations/retries
5. Process the work queue, keeping track of progress in a file in case of interrupts
## Getting Started
1. First step is to setup a python3 venv to hold our deps
```
./setup-venv.sh
```
2. Run the command and follow the prompts
```
python s3-lambda-replay.py
```
## Options
Run the help command for a full list of available command line options
```
python s3-lambda-replay.py --help
```
## Example Command Line Execution
Note that we must escape the `$`
This example is also included in the file `run_replay.sh`
```
python3 s3-lambda-replay.py \
-b gamesight-collection-pipeline-us-west-2-prod \
-p twitch/all/chatters/\$LATEST/objects/dt=2020-01-02-08-00/,twitch/all/chatters/\$LATEST/objects/dt=2020-01-02-09-00/ \
-l gstrans-prod-twitch-all-chatters
```
Using the command line also allows us to quickly include paths that aren't along `/` separation lines. For example, we can use the path `twitch/all/chatters/\$LATEST/objects/dt=2020-01-02-1` to look at all records between 10:00 and 20:00 on 2020-01-02, or `twitch/all/chatters/\$LATEST/objects/dt=2020-01-02` to just run all of the objects from that day.
<file_sep>"""s3-lambda-replay
A simple tool for replaying S3 file creation Lambda invocations. This is useful
for backfill or replay on real-time ETL pipelines that run transformations in
Lambdas triggered by S3 file creation events.
Steps:
1. Collect inputs from user
2. Scan S3 for filenames that need to be replayed
3. Batch S3 files into payloads for Lambda invocations
4. Spawn workers to handle individual Lambda invocations/retries
5. Process the work queue, keeping track of progesss in a file in case of interrupts
"""
from multiprocessing import Queue, Process
import boto3
import json
import questionary
import time
import sys
from util.config import ReplayConfig
s3 = boto3.client('s3')
lambda_client = boto3.client('lambda')
class LambdaWorker(Process):
def __init__(self, job_queue, result_queue, id, total_jobs):
super(LambdaWorker, self).__init__()
self.job_queue = job_queue
self.result_queue = result_queue
self.id = id
self.total_jobs = total_jobs
def run(self):
for job in iter(self.job_queue.get, None):
sys.stdout.write(f"\rWorker {self.id:02} - Job {job['id']+1}/{self.total_jobs} - {job['first_file']}")
if not sys.stdout.isatty(): # If we aren't attached to an interactive shell then write out newlines to show progress
sys.stdout.write("\n")
sys.stdout.flush()
if job['id'] + 1 == self.total_jobs:
print("\nAll jobs complete. Cleaning up...")
results = {
'id': job['id'],
'body': '',
'status': 500,
'retries': 0,
'error': '',
}
while True:
try:
response = lambda_client.invoke(
FunctionName=job['lambda'],
Payload=json.dumps(job['data']).encode('utf-8')
)
results['body'] = response['Payload'].read().decode('utf-8')
results['status'] = response['StatusCode']
results['error'] = response.get('FunctionError')
if not results['status'] == 200:
print(f"Worker {self.id} - Response {results['status']} {results['body']}")
break
except Exception as e:
print(f"Worker {self.id} - Exception caught {e}")
results['body'] = str(e)
if ( str(e).split(":")[0] == "Read timeout on endpoint URL"):
print(f"Read timeout on {job}")
#We need some additional handling here.
results['error'] = 'Read timeout'
break
if results['retries'] >= 5:
results['error'] = 'TooManyRetries'
break
results['retries'] += 1
# Exp Backoff, 200ms, 400ms, 800ms, 1600ms
time.sleep((2**results['retries']) * 0.1)
print(f"Worker {self.id} - Attempt {results['retries']}/5")
# Report the results back to the master process
self.result_queue.put(results)
# Sentinel to let the master know the worker is done
self.result_queue.put(None)
def s3_object_generator(bucket, prefix=''):
""" Generate objects in an S3 bucket."""
opts = {
'Bucket': bucket,
'Prefix': prefix,
}
fileSum = 0
while True:
resp = s3.list_objects_v2(**opts)
contents = resp.get('Contents',[])
fileSum += len(contents)
sys.stdout.write(f"\rAdded {fileSum} objects to the queue.")
sys.stdout.flush()
for obj in contents:
yield obj
try:
opts['ContinuationToken'] = resp['NextContinuationToken']
except KeyError:
break
print("\nAll objects added to the queue. Building batches...")
def generate_sns_lambda_payload(files):
return {'Records': [
{
'EventSource': 'aws:sns',
'EventVersion': '1.0',
'EventSubscriptionArn': 'arn:aws:sns:us-west-2:0000:s3-sns-lambda-replay-XXXX:1234-123-12-12',
'Sns': {
'SignatureVersion': "1",
'Timestamp': "1970-01-01T00:00:00.000Z",
'Signature': "replay",
'SigningCertUrl': "replay",
'MessageId': "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
'Message': json.dumps({"Records": files}),
'MessageAttributes': {},
'Type': "Notification",
'UnsubscribeUrl': "replay",
'TopicArn': "",
'Subject': "ReplayInvoke",
}
}
]}
def pull_jobs(config):
files = []
for path in config.s3_paths:
for obj in s3_object_generator(config.s3_bucket, path):
files.append({'s3': {
'bucket': {'name': config.s3_bucket},
'object': {'key': obj['Key']},
'size': obj['Size']
}})
#Sort the list by size ascending
files.sort(key=lambda x: x['s3']['size'], reverse=False)
jobs = []
while len(files) > 0:
#Greedily add files to batches, taking the smallest files
batch = [files[0]] #always add the biggest object
del files[0] #remove the first object
batch_total = batch[0]['s3']['size'] #set the batch size
for i,f in enumerate(files):
# if the next element will exceed the cap delete previous elements and break out
if f['s3']['size'] + batch_total > config.batch_size or len(batch) > 100:
del files[0:i]
break
# otherwise add the element to the batch and increment the size
else:
batch_total += f['s3']['size']
batch.append(f)
data = generate_sns_lambda_payload(batch)
for func in config.lambda_functions:
jobs.append({
'lambda': func,
'data': data,
'id': len(jobs),
'result': None,
'first_file': batch[0]['s3']['object']['key']
})
sys.stdout.write(f"\rCreated {len(jobs)} batches.")
sys.stdout.flush()
print("\nAll batches created. Starting execution...")
# Move on to the next batch
#files = files[config.batch_size:]
return jobs
def log_state(jobs, failed_jobs):
with open('jobs.json', 'w+') as fh:
fh.write(json.dumps(jobs))
with open('jobs-failed.json', 'w+') as fh:
fh.write(json.dumps(failed_jobs))
if __name__ == "__main__":
config = ReplayConfig()
print(config)
if not config.bypass:
if not questionary.confirm("Is this configuration correct?", default=False).ask():
exit()
jobs = pull_jobs(config)
failed_jobs = []
log_state(jobs, failed_jobs)
workers = []
job_queue = Queue()
result_queue = Queue()
for i in range(config.concurrency * len(config.lambda_functions)):
worker = LambdaWorker(job_queue, result_queue, i, len(jobs))
workers.append(worker)
worker.start()
for job in jobs:
job_queue.put(job)
# Add sentinels to the queue for each of our workers
for i in range(config.concurrency * len(config.lambda_functions)):
job_queue.put(None)
# Collect worker results
completed_workers = 0
while completed_workers < config.concurrency * len(config.lambda_functions):
result = result_queue.get()
if result is None:
completed_workers += 1
continue
jobs[result['id']]['result'] = result
if result['error'] != '' and result['error'] is not None:
failed_jobs.append(jobs[result['id']])
log_state(jobs, failed_jobs)
# Wait for processes to finish
for worker in workers:
worker.join()
print("Replay Complete!")
<file_sep>boto3~=1.9
botocore~=1.12
docutils~=0.14
jmespath~=0.9
prompt-toolkit~=2.0
python-dateutil~=2.7
questionary~=1.0
s3transfer~=0.1
six~=1.12
urllib3~=1.24
wcwidth~=0.1
<file_sep>import argparse
import boto3
import questionary
import json
s3 = boto3.client('s3')
lambda_client = boto3.client('lambda')
class ReplayConfig(object):
s3_bucket = None
s3_paths = None
lambda_functions = None
batch_size = 3_000_000
concurrency = 4
bypass = False
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bucket', help="S3 Bucket to use", default=None)
parser.add_argument('-p', '--paths', help="Paths to replay, comma separated", default=None)
parser.add_argument('-l', '--lambdas', help="Lambda arns to call", default=None)
parser.add_argument('-y', '--yes', action="store_const", help="Skip the verification",
dest="bypass", const=True, default=False)
args = parser.parse_args()
self.s3_bucket = self.get_s3_bucket(args)
self.s3_paths = self.get_s3_paths(args)
self.lambda_functions = self.get_lambda_functions(args)
self.bypass = args.bypass
def __str__(self):
lambda_str = '\n - '.join(self.lambda_functions)
return f"""
#################
# Replay Config #
#################
S3 Bucket: {self.s3_bucket}
S3 Paths :
- {self.s3_paths[0]}
- ({len(self.s3_paths)} total)
- {self.s3_paths[len(self.s3_paths) - 1]}
#################
Lambda Function(s):
- {lambda_str}
Batch Size : {self.batch_size}
Concurrency : {self.concurrency}
Bypass : {self.bypass}
"""
def get_s3_bucket(self, args):
if args.bucket:
return args.bucket
bucket_resp = s3.list_buckets()
while True:
selection = questionary.checkbox(
"Select the bucket which contains the files to be replayed:",
choices=[b['Name'] for b in bucket_resp['Buckets']]
).ask()
if len(selection) == 0:
print("No selection.. try again!")
elif len(selection) == 1:
bucket = selection[0]
break
else:
print("Invalid selection.. please select one item")
return bucket
def get_s3_paths(self, args):
if args.paths:
return args.paths.split(",")
paths = None
prefix = ''
while True:
choices = [b['Prefix'] for b in self.s3_prefix_generator(self.s3_bucket, prefix)]
# If there are no more common prefixes beneath this layer, use it as the prefix
if len(choices) == 0:
paths = [prefix]
break
selection = questionary.checkbox(
"Browse to the path containing the files to be replayed. When at the proper path select the first and last item to be replayed:",
choices=reversed(choices)
).ask()
if len(selection) == 0:
print("No selection.. try again!")
elif len(selection) == 1:
prefix = selection[0]
elif len(selection) == 2:
paths = [c for c in choices if c >= min(selection) and c <= max(selection)]
break
else:
print("Invalid selection.. please select the first and last item in the range to be replayed")
return paths
def get_lambda_functions(self, args):
if args.lambdas:
return args.lambdas.split(',')
lambda_list = list(self.lambda_function_generator())
while True:
selection = questionary.checkbox(
"Select the bucket which contains the files to be replayed:",
choices=sorted([f['FunctionArn'] for f in lambda_list])
).ask()
if len(selection) == 0:
print("No selection.. try again!")
elif len(selection) > 0:
lambdas = selection
break
return lambdas
def s3_prefix_generator(self, bucket, prefix):
opts = {
'Bucket': bucket,
'Prefix': prefix,
'Delimiter': '/',
}
while True:
resp = s3.list_objects_v2(**opts)
contents = resp.get('CommonPrefixes',[])
for obj in contents:
yield obj
try:
opts['ContinuationToken'] = resp['NextContinuationToken']
except KeyError:
break
def lambda_function_generator(self):
opts = {}
while True:
resp = lambda_client.list_functions(**opts)
contents = resp['Functions']
for obj in contents:
yield obj
try:
opts['Marker'] = resp['NextMarker']
except KeyError:
break
<file_sep>FROM python:3.7-alpine
WORKDIR /opt/app
RUN addgroup -S -g 61000 replayuser && adduser -S -u 61000 -G replayuser replayuser
RUN apk update && \
apk upgrade && \
apk add git gcc build-base libxslt-dev linux-headers
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN chown -R replayuser:replayuser .
USER replayuser:replayuser
<file_sep>#!/bin/bash
export AWS_DEFAULT_REGION=us-west-2
python3 s3-lambda-replay.py \
-b gamesight-collection-pipeline-us-west-2-prod \
-p mixer/all/channels/\$LATEST/objects/dt=2019-01-31 \
-l gstrans-prod-mixer-all-streams \
-y
# for i in `seq 1 9`;
# do
# python3 s3-lambda-replay.py \
# -b gamesight-collection-pipeline-us-west-2-prod \
# -p mixer/all/channels/\$LATEST/objects/dt=2019-0$i \
# -l gstrans-prod-mixer-all-streams,gstrans-prod-mixer-all-games,gstrans-prod-mixer-all-channels,gstrans-prod-mixer-all-game_tag \
# -y
# done
# for i in `seq 10 12`;
# do
# python3 s3-lambda-replay.py \
# -b gamesight-collection-pipeline-us-west-2-prod \
# -p mixer/all/channels/\$LATEST/objects/dt=2019-$i \
# -l gstrans-prod-mixer-all-streams,gstrans-prod-mixer-all-games,gstrans-prod-mixer-all-channels,gstrans-prod-mixer-all-game_tag \
# -y
# done
# for i in `seq 1 2`;
# do
# python3 s3-lambda-replay.py \
# -b gamesight-collection-pipeline-us-west-2-prod \
# -p mixer/all/channels/\$LATEST/objects/dt=2020-0$i \
# -l gstrans-prod-mixer-all-streams,gstrans-prod-mixer-all-games,gstrans-prod-mixer-all-channels,gstrans-prod-mixer-all-game_tag \
# -y
# done
| 4143556e6677079404e9a123a53f0dbc935894de | [
"Markdown",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 7 | Shell | Gamesight/s3-sns-lambda-replay | 7d2b639c3863f9ed379abd6150a0b0013736dda7 | 07ab05aff9591566779f56dbdc579104d93e9337 |
refs/heads/master | <repo_name>jackinf/Studying<file_sep>/Study.Sorting/SortingApps/QuicksortApp.cs
using System.Collections.Generic;
namespace Study.Algo.SortingApps
{
public class QuicksortApp
{
public static List<int> Sort(List<int> list)
{
SortInner(list, 0, list.Count - 1);
return list;
}
private static void SortInner(List<int> list, int lower, int upper)
{
if (upper <= lower)
return;
int pivot = list[lower];
int start = lower;
int stop = upper;
while (lower < upper)
{
while (list[lower] <= pivot && lower < upper)
lower++;
while (list[upper] > pivot && lower <= upper)
upper--;
if (lower < upper)
(list[lower], list[upper]) = (list[upper], list[lower]);
}
(list[upper], list[start]) = (list[start], list[upper]);
SortInner(list, start, upper - 1);
SortInner(list, upper + 1, stop);
}
}
}<file_sep>/Study.Sorting.Tests/ProblemSolvingInDataStructuresBook/Chapter05Tests.cs
using System.Collections.Generic;
using NUnit.Framework;
using Study.Algo.ProblemSolvingInDataStructuresBook;
namespace Study.Algo.Tests.ProblemSolvingInDataStructuresBook
{
public class Chapter05Tests
{
[Test]
public void FindMissingNumberTest()
{
var list = new List<int> {1, 2, 3, 5, 6, 7};
var result = Chapter05.FindMissingNumber(list, list.Count+1);
Assert.AreEqual(4, result);
}
}
}<file_sep>/Study.Websocket.Server/Extension/WebSocketExtension.cs
using System;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Study.Websocket.Common;
namespace Study.Websocket.Server.Extension
{
public static class WebSocketExtension
{
public static async Task Send<T>(this WebSocket ws, T data)
{
var message = new Message<T> {Data = data};
var json = JsonConvert.SerializeObject(message);
var bytes = Encoding.UTF8.GetBytes(json);
var buffer = new ArraySegment<byte>(bytes);
await ws.SendAsync(buffer.Array, WebSocketMessageType.Text, true, CancellationToken.None);
}
public static async Task<Message<T>> Receive<T>(this WebSocket ws)
{
var buffer = new ArraySegment<byte>(new byte[8192]);
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
result = await ws.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, buffer.Count);
} while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.CloseStatus.HasValue)
return null;
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var json = await reader.ReadToEndAsync();
return JsonConvert.DeserializeObject<Message<T>>(json);
}
}
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/LinkedListDeleteGreaterValueNodes.cs
using System.Collections.Generic;
namespace Study.Algo.AlgoChallenge
{
/// <summary>
/// Given an integer value and a pointer to the head of the linked list,
/// delete all the nodes from the list that are greater than the specified value.
/// </summary>
public class LinkedListDeleteGreaterValueNodes
{
public static void Run(LinkedList<int> list, int maxAllowedValue)
{
if (list.Count == 0)
return;
LinkedListNode<int> nextNode = list.First;
do
{
if (nextNode.Value > maxAllowedValue)
{
var temp = nextNode;
nextNode = nextNode.Next;
list.Remove(temp);
}
else
nextNode = nextNode.Next;
} while (nextNode != null);
}
}
}<file_sep>/Study.Sorting/Patterns/SingletonF.cs
using System;
namespace Study.Algo.Patterns
{
public class SingletonF
{
private static Lazy<SingletonF> lazy => new Lazy<SingletonF>(() => new SingletonF());
private SingletonF() { }
public static SingletonF Instance => lazy.Value;
}
}<file_sep>/Study.Sorting.Tests/SortingAppsTests.cs
using System.Collections.Generic;
using NUnit.Framework;
using Study.Algo.SortingApps;
namespace Study.Algo.Tests
{
public class SortingAppsTests
{
[Test]
public void BubbleSortTest()
{
var list = new List<int> {5, 4, 2, 3, 2, 1};
var result = BubbleSortApp.Sort(list);
Assert.AreEqual(new List<int> {1, 2, 2, 3, 4, 5}, result);
}
[Test]
public void MergeSortTest()
{
var list = new List<int> {5, 4, 2, 3, 2, 1};
var result = MergeSortApp.Sort(list);
Assert.AreEqual(new List<int> {1, 2, 2, 3, 4, 5}, result);
}
[Test]
public void QuickSortTest()
{
var list = new List<int> {3,4,2,1,6,5,7,8,1,1};
var result = QuicksortApp.Sort(list);
Assert.AreEqual(new List<int> {1,1,1,2,3,4,5,6,7,8}, result);
}
}
}<file_sep>/Study.Sorting/Patterns/SingletonE.cs
namespace Study.Algo.Patterns
{
public class SingletonE
{
private SingletonE() { }
public static SingletonE Instance => Nested.NestedInstance;
private class Nested
{
static Nested() { }
internal static readonly SingletonE NestedInstance = new SingletonE();
}
}
}<file_sep>/Study.Auth0/Filters/WithRolesAttribute.cs
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Study.Auth0.Server.Filters
{
public class WithRolesAttribute : ActionFilterAttribute
{
public List<string> Roles { get; set; }
public WithRolesAttribute(string roles)
{
Roles = roles.Split(',').ToList();
}
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
string roleClaimType = Startup.RolesNamespace;
if (!actionContext.HttpContext.User.HasClaim(c => c.Type == roleClaimType))
{
actionContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
var role = actionContext.HttpContext.User?.FindFirst(c => c.Type == roleClaimType)?.Value ?? "";
if (!Roles.Contains(role))
{
actionContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
base.OnActionExecuting(actionContext);
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/SortAlmostSortedArrayTests.cs
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class SortAlmostSortedArrayTests
{
[TestCase(new [] { 2, 8, 6, 4, 10 }, true, new[] { 2, 4, 6, 8, 10 })]
[TestCase(new [] { 2, 10, 6, 8, 4 }, true, new[] { 2, 4, 6, 8, 10 })]
[TestCase(new [] { 8, 4, 6, 2, 10 }, true, new[] { 2, 4, 6, 8, 10 })]
[TestCase(new [] { 10, 4, 6, 8, 2 }, true, new[] { 2, 4, 6, 8, 10 })]
public void Test1(int[] arr, bool expectedSuccess, int[] sortedArr)
{
var success = SortAlmostSortedArray.Run(arr);
Assert.AreEqual(expectedSuccess, success);
Assert.AreEqual(sortedArr, arr);
}
}
}<file_sep>/Study.EventSourcing/EventSourcing.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using MassTransit;
namespace Study.EventSourcing
{
public class EventSourcing
{
public async Task Replay(IBus bus, List<Event.Event> events)
{
foreach (var @event in events)
await bus.Publish(@event);
}
}
}<file_sep>/Study.EventSourcing/Consumer/UpdatePersonConsumer.cs
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MassTransit;
using Newtonsoft.Json;
using Study.EventSourcing.Command;
using Study.EventSourcing.DAL;
using Study.EventSourcing.DAL.EventSourcingHistory;
using Study.EventSourcing.DAL.Repository;
using Study.EventSourcing.Event;
namespace Study.EventSourcing.Consumer
{
public class UpdatePersonConsumer :
IConsumer<ChangePersonNameCommand>,
IConsumer<BatchedPersonNameChangedEvent>,
IConsumer<PersonNameChangedEvent>
{
private readonly object _lock = new object();
/*
* Commands
*/
public async Task Consume(ConsumeContext<ChangePersonNameCommand> context)
{
PersonNameChangedHistoryItem FromCommandToHistoryItem(PersonNameChangedEvent eventInner)
=> new PersonNameChangedHistoryItem { UpdatedOn = DateTime.UtcNow, Payload = JsonConvert.SerializeObject(eventInner) };
PersonNameChangedEvent FromCommandToEvent(ChangePersonNameCommand command)
=> new PersonNameChangedEvent { Id = command.Id, Name = command.NewName };
// store history item
var historyRepository = new EventSourcingRepository(new SqliteDbContext());
var @event = FromCommandToEvent(context.Message);
var item = FromCommandToHistoryItem(@event);
historyRepository.AddHistoryItem(item);
await context.Publish(@event);
}
/*
* Events
*/
public async Task Consume(ConsumeContext<BatchedPersonNameChangedEvent> context)
{
foreach (var personNameChangedEvent in context.Message.Events)
await OnPersonNameChangedEvent(personNameChangedEvent);
}
public async Task Consume(ConsumeContext<PersonNameChangedEvent> context)
{
await OnPersonNameChangedEvent(context.Message);
}
private async Task OnPersonNameChangedEvent(PersonNameChangedEvent personNameChangedEvent)
{
Console.WriteLine($"Thread id: {Thread.CurrentThread.ManagedThreadId}");
await Console.Out.WriteLineAsync($"Updating person with id {personNameChangedEvent.Id} to new name {personNameChangedEvent.Name}");
lock (_lock)
{
// db operation
var personRepository = new PersonRepository(new SqliteDbContext());
var person = personRepository.Get(personNameChangedEvent.Id);
person.Name = personNameChangedEvent.Name;
personRepository.Update(person);
}
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/IntervalMerge.cs
using System;
using System.Collections.Generic;
namespace Study.Algo.AlgoChallenge
{
public class IntervalMerge
{
public static List<(int Start, int End)> Run(List<(int Start, int End)> input)
{
var output = new List<(int Start, int End)>();
input.Sort((a, b) => a.Start.CompareTo(b.Start));
(int Start, int End)? mergedInterval = null;
foreach (var interval in input)
{
if (mergedInterval == null)
{
mergedInterval = interval;
}
else if (interval.Start > mergedInterval.Value.End)
{
output.Add(mergedInterval.Value);
mergedInterval = interval;
}
else
{
mergedInterval = (mergedInterval.Value.Start, Math.Max(mergedInterval.Value.End, interval.End));
}
}
if (mergedInterval != null)
output.Add(mergedInterval.Value);
return output;
}
}
}<file_sep>/Study.Sorting.Tests/Exersizes/ChapterOnSortingExersizesTests.cs
using NUnit.Framework;
using Study.Algo.ProblemSolvingInDataStructuresBook;
namespace Study.Algo.Tests.Exersizes
{
public class ChapterOnSortingExersizesTests
{
/// <summary>
/// Given a text file print the words with their frequency.
/// Now print the kth word in term of frequency
/// </summary>
[Test]
public void Exersize01Test()
{
const string words = @"
Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add.
You can also type a keyword to search online for the video that best fits your document. To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other.
For example, you can add a matching cover page, header, and sidebar. Click Insert and then choose the elements you want from the different galleries.
";
var wordsWithFrequencies = ChapterOnSortingExersize01.PrintWordsWithFrequency(words);
}
}
}<file_sep>/Study.Sorting.Tests/ProblemSolvingInDataStructuresBook/Chapter01ExersizesTests.cs
using System.Collections.Generic;
using NUnit.Framework;
using Study.Algo.ProblemSolvingInDataStructuresBook;
namespace Study.Algo.Tests.ProblemSolvingInDataStructuresBook
{
public class Chapter01ExersizesTests
{
[Test]
public void Exersize05Test()
{
var result = Chapter01Exersizes.Exersize05(new List<int> {4, 156, 2, 54, 34, 55, 77, 23, 111});
Assert.AreEqual(111, result);
}
}
}<file_sep>/Study.Sorting/ProblemSolvingInDataStructuresBook/Chapter01.cs
using System.Collections.Generic;
namespace Study.Algo.ProblemSolvingInDataStructuresBook
{
public class Chapter01
{
/// <summary>
/// Euclid: GDC(n, m) == GDC(m, n%m)
/// </summary>
public static int Gdc(int m, int n)
=> m < n ? Gdc(n, m) : m % n == 0 ? n : Gdc(n, m % n);
public static int Fibonacci(int n) => n <= 1 ? n : Fibonacci(n - 1) + Fibonacci(n - 2);
public static void Permutation(List<int> arr, int i, List<string> outputs)
{
if (arr.Count == i)
{
outputs.Add(string.Join(", ", arr));
return;
}
for (var j = i; j < arr.Count; j++)
{
(arr[i], arr[j]) = (arr[j], arr[i]);
Permutation(arr, i+1, outputs);
(arr[i], arr[j]) = (arr[j], arr[i]);
}
}
public static void RotateArray(List<int> list, int positions)
{
void ReverseArray(int start, int end)
{
for (int i = start, j = end; i < j; i++, j--)
(list[i], list[j]) = (list[j], list[i]);
}
ReverseArray(0, positions -1);
ReverseArray(positions, list.Count -1);
ReverseArray(0, list.Count -1);
}
}
}<file_sep>/Study.AkkaNet.Interview.Web.Tests/Baskets/BasketActorTests.cs
namespace Study.AkkaNet.Interview.Web.Tests.Baskets
{
public class BasketActorTests
{
}
}<file_sep>/Study.Sorting/ProblemSolvingInDataStructuresBook/Chapter05.cs
using System;
using System.Collections.Generic;
namespace Study.Algo.ProblemSolvingInDataStructuresBook
{
public class Chapter05
{
public static int FindMissingNumber(List<int> list, int range)
{
int xorSum = 0;
for (int j = 1; j <= range; j++)
xorSum = xorSum ^ j;
foreach (var item in list)
xorSum = xorSum ^ item;
return xorSum;
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Products/ProductsActor.cs
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Akka.Actor;
namespace Study.AkkaNet.Interview.Web.Products
{
public partial class ProductsActor : ReceiveActor
{
public IList<Product> Products { get; }
public ProductsActor(IList<Product> products)
{
Products = products;
Receive<GetAllProducts>(_ => Sender.Tell(new ReadOnlyCollection<Product>(Products)));
Receive<UpdateStock>(m => Sender.Tell(UpdateStockAction(m)));
}
public ProductEvent UpdateStockAction(UpdateStock message)
{
var product = Products.FirstOrDefault(p => p.Id == message.ProductId);
if (product == null)
return new ProductNotFound();
var newAmountChanged = product.InStock + message.AmountChanged;
if (newAmountChanged < 0)
return new InsufficientStock();
product.InStock = newAmountChanged;
return new StockUpdated(product);
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/KClosestPointsToOrigin.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Study.Algo.AlgoChallenge
{
public class KClosestPointsToOrigin
{
public static List<(int X, int Y, double Distance)> Find(List<(int X, int Y)> points, int k)
{
if (k <= 0)
return new List<(int X, int Y, double Distance)>();
List<(int X, int Y, double Distance)> pointsWithDistances = points
.Select(point => (point.X, point.Y, Math.Sqrt(point.X*point.X + point.Y*point.Y)))
.ToList();
var maxHeap = new List<(int X, int Y, double Distance)>();
for (var i = 0; i < k; i++)
maxHeap.Add(pointsWithDistances[i]);
var largestDistance = maxHeap.Max(x => x.Distance);
for (var i = k; i < pointsWithDistances.Count; i++)
{
var point = pointsWithDistances[i];
if (point.Distance < largestDistance)
{
var prevElement = maxHeap.First(x => Math.Abs(x.Distance - largestDistance) < 0.01d);
var prevElementIndex = maxHeap.IndexOf(prevElement);
maxHeap[prevElementIndex] = point;
largestDistance = maxHeap.Max(x => x.Distance);
}
}
return maxHeap;
}
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public double DistanceFromOrigin { get; set; }
}
}
}<file_sep>/Study.EventSourcing/Command/ChangePersonNameCommand.cs
namespace Study.EventSourcing.Command
{
public class ChangePersonNameCommand
{
public int Id { get; set; }
public string NewName { get; set; }
}
}<file_sep>/Study.AkkaNet.Interview.Web/Products/ProductsActor.Messages.cs
namespace Study.AkkaNet.Interview.Web.Products
{
public partial class ProductsActor
{
public class GetAllProducts { }
public class UpdateStock
{
public int ProductId { get; }
public int AmountChanged { get; }
public UpdateStock(int productId = 0, int amountChanged = 0)
{
ProductId = productId;
AmountChanged = amountChanged;
}
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/BinaryTreeTraversalTests.cs
using System.Linq;
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class BinaryTreeTraversalTests
{
private BinaryTreeTraversal.Tree _tree;
[SetUp]
public void SetUp()
{
_tree = new BinaryTreeTraversal.Tree();
_tree.Insert(30);
_tree.Insert(35);
_tree.Insert(57);
_tree.Insert(15);
_tree.Insert(63);
_tree.Insert(49);
_tree.Insert(89);
_tree.Insert(77);
_tree.Insert(67);
_tree.Insert(98);
_tree.Insert(91);
}
[Test]
public void InorderTraversalTest()
{
var result = _tree.Inorder(_tree.Root).ToList();
Assert.AreEqual("15 30 35 49 57 63 67 77 89 91 98", string.Join(" ", result));
}
[Test]
public void PreorderTraversalTest()
{
var result = _tree.Preorder(_tree.Root);
Assert.AreEqual("30 15 35 57 49 63 89 77 67 98 91", string.Join(" ", result));
}
[Test]
public void PostorderTraversalTest()
{
var result = _tree.Postorder(_tree.Root);
Assert.AreEqual("15 49 67 77 91 98 89 63 57 35 30", string.Join(" ", result));
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/FizzBuzzTests.cs
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class FizzBuzzTests
{
[Test]
public void GetFor20First()
{
var expected = new List<(int, string)> { (3, "Fizz"), (5, "Buzz"), (6, "Fizz"), (9, "Fizz"), (10, "Buzz"), (12, "Fizz"), (15, "FizzBuzz"), (18, "Fizz"), (20, "Buzz") };
var input = Enumerable.Range(1, 20).ToArray();
var result = FizzBuzz.Run(input);
Assert.AreEqual(expected, result);
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/Routes/Dto/AddItem.cs
namespace Study.AkkaNet.Interview.Web.Baskets.Routes.Dto
{
public class AddItem
{
public int ProductId { get; set; }
public int Amount { get; set; }
}
}<file_sep>/Study.Sorting.Tests/ProblemSolvingInDataStructuresBook/Chapter1Tests.cs
using System.Collections.Generic;
using NUnit.Framework;
using Study.Algo.ProblemSolvingInDataStructuresBook;
namespace Study.Algo.Tests.ProblemSolvingInDataStructuresBook
{
public class Chapter1Tests
{
[Test]
public void PermutationTest()
{
var outputs = new List<string>();
Chapter01.Permutation(new List<int> {1, 2, 3, 4, 5}, 0, outputs);
}
[Test]
public void RotateArray()
{
var array = new List<int> {10, 20, 30, 40, 50, 60};
Chapter01.RotateArray(array, 2);
Assert.AreEqual(new List<int> {30, 40, 50, 60, 10, 20}, array);
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/PromoCodesTests.cs
using System;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class PromoCodesTests
{
[Test]
public void Test00()
{
var sum = PromoCodes.GetPromoCodeFormulaSum(new [] {1, 2, 3, 4, 5, 6, 7, 8, 9});
Assert.AreEqual(165, sum);
}
[Test]
public void Test01()
{
var sw = Stopwatch.StartNew();
var codes = PromoCodes.Generate().Take(1000).ToList();
sw.Stop();
var time = sw.ElapsedMilliseconds;
Assert.AreEqual(1000, codes.Count);
foreach (var code in codes)
{
var numbersArray = code.Select(x => int.Parse(x.ToString())).ToList();
Assert.AreEqual(9, numbersArray.Count);
var hasAnyLetterMoreOccurrencesThan2 = numbersArray
.GroupBy(letter => letter, (letter, list) => new { Count = list.Count() })
.Any(result => result.Count > 2);
Assert.IsFalse(hasAnyLetterMoreOccurrencesThan2);
var index = 9;
var sum = numbersArray.Aggregate(0, (a, b) => a + b * index--);
Assert.AreEqual(sum % 11, 0);
}
}
}
}<file_sep>/Study.AkkaNet.Interview.Web.Tests/Products/ProductActorTests.cs
using System.Collections.Generic;
using Akka.Actor;
using Akka.TestKit.NUnit3;
using NUnit.Framework;
using Study.AkkaNet.Interview.Web.Products;
namespace Study.AkkaNet.Interview.Web.Tests.Products
{
public class ProductActorTests : TestKit
{
private IEnumerable<Product> Products { get; } = GetProductData();
[Test]
public void Return_All_Products()
{
var actorUnderTest = ActorOf(Props.Create<ProductsActor>(Products));
actorUnderTest.Tell(new ProductsActor.GetAllProducts());
var result = ExpectMsg<IEnumerable<Product>>();
Assert.AreEqual(this.Products, result);
}
private static IEnumerable<Product> GetProductData()
{
return new List<Product> {
new Product {
Id = 1000,
Title = "Product 1",
InStock = 1
},
new Product {
Id = 1001,
Title = "Product 2",
InStock = 2
}
};
}
}
}<file_sep>/Study.Sorting/SortingApps/MergeSortApp.cs
using System.Collections.Generic;
namespace Study.Algo.SortingApps
{
public class MergeSortApp
{
public static List<int> Sort(List<int> list)
{
if (list.Count <= 1)
return list;
var left = new List<int>();
var right = new List<int>();
for (int i = 0; i < list.Count; i++)
{
if (i < list.Count / 2)
left.Add(list[i]);
else
right.Add(list[i]);
}
left = Sort(left);
right = Sort(right);
var merged = Merge(left, right);
return merged;
}
private static List<int> Merge(List<int> left, List<int> right)
{
var result = new List<int>();
while (left.Count > 0 && right.Count > 0)
{
if (left[0] <= right[0])
{
result.Add(left[0]);
left.RemoveAt(0);
}
else
{
result.Add(right[0]);
right.RemoveAt(0);
}
}
while (left.Count > 0)
{
result.Add(left[0]);
left.RemoveAt(0);
}
while (left.Count > 0)
{
result.Add(right[0]);
right.RemoveAt(0);
}
return result;
}
}
}<file_sep>/Study.Sorting/Patterns/SingletonC.cs
namespace Study.Algo.Patterns
{
public sealed class SingletonC
{
private static SingletonC _instance = null;
private static readonly object Lock = new object();
private SingletonC() { }
public static SingletonC Instance
{
get
{
if (_instance == null)
lock (Lock)
if (_instance == null)
_instance = new SingletonC();
return _instance;
}
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/PromoCodes.cs
using System.Collections.Generic;
using System.Linq;
using Study.Algo.Combinatorics;
namespace Study.Algo.AlgoChallenge
{
/// <summary>
/// #### LP-1: As LeasePlan I would like to have 1000 pregenerated promotion codes for use on printed posters.
///
/// The promotion code should be of the following format:
///
/// * Nine numerical characters
/// * When multiplying the first number by 9, the second by 8, the third by 7, and so on...the resulting number should be divisible by 11 and a single digit may not appear more the twice.
///
/// Examples:
/// * 613884922 is valid, because 6 x 9 + 1 x 8 + 3 x 7 + 8 x 6 + 8 x 5 + 4 x 4 + 9 x 3 + 2 x 2 + 2 x 1 = 220 / 11 = 20 (whole number, no digit is repeated 3+ times)
/// * 538820102 is invalid, because 5 x 9 + 3 x 8 + 8 x 7 + 8 x 6 + 2 x 5 + 0 x 4 + 1 x 3 + 0 x 2 + 2 x 1 = 188 / 11 = 17.09 (not a whole number)
/// * 131888331 is invalid(digits 1, 3 and 8 appear too often)
///
/// Note: you can store the 1000 codes in any format.Please also keep the source code by which you generated them.
/// </summary>
public static class PromoCodes
{
private static readonly int MinimalPossibleSum = GetPromoCodeFormulaSum(0, 0, 1, 1, 2, 2, 3, 3, 4); // 50
private static readonly int MaximumPossibleSum = GetPromoCodeFormulaSum(9, 9, 8, 8, 7, 7, 6, 6, 5); // 355
private static readonly IEnumerable<int> ValidRange = Enumerable.Range(MinimalPossibleSum, MaximumPossibleSum - MinimalPossibleSum);
// 28 numbers: 55, 66, 77, 88, 99, 110, 121, 132, 143, 154, 165, 176, 187, 198, 209, 220, 231, 242, 253, 264, 275, 286, 297, 308, 319, 330, 341, 352
private static readonly HashSet<int> ValidSumsDivisiblesBy11 = ValidRange.Where(number => number % 11 == 0).ToHashSet();
public static IEnumerable<string> Generate()
{
List<int> numbersPossibleToUse = new List<int> {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9};
Dictionary<string, bool> usedCodes = new Dictionary<string, bool>();
Variations<int> variations = new Variations<int>(numbersPossibleToUse, 9, GenerateOption.WithoutRepetition);
foreach (var permutation in variations)
{
var calculatedSum = GetPromoCodeFormulaSum(permutation.ToArray());
if (ValidSumsDivisiblesBy11.Contains(calculatedSum))
{
var code = permutation.Aggregate("", (s, i) => s + i);
//if (!usedCodes.ContainsKey(code))
{
//usedCodes[code] = true;
yield return code;
}
}
}
yield return "";
}
public static int GetPromoCodeFormulaSum(params int[] numbers)
{
var index = numbers.Length;
return numbers.Aggregate(0, (a, b) => a + b * index--);
}
public static int GetPromoCodeFormulaSum(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9)
=> GetPromoCodeFormulaSum(new [] {a1, a2, a3, a4, a5, a6, a7, a8, a9});
}
}<file_sep>/Study.Websocket.Client/Program.cs
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Study.Websocket.Client
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Press any button to send message. Press escape to quit");
const string url = "ws://localhost:50221/hello";
//WebsocketSharpApp.Run(url);
await WebsocketNetApp.RunAsync(url, CancellationToken.None);
}
}
}
<file_sep>/Study.Auth0.Client/Program.cs
using System;
using Newtonsoft.Json;
using RestSharp;
namespace Study.Auth0.Client
{
class Program
{
static void Main(string[] args)
{
const string authority = "https://stylehopper.eu.auth0.com/oauth/token";
const string apiIdentifier = "https://quickstarts/api";
var clientId = Environment.GetEnvironmentVariable("STUDY_AUTH0_CLIENT_CLIENT_ID");
var clientSecret = Environment.GetEnvironmentVariable("STUDY_AUTH0_CLIENT_CLIENT_SECRET");
var client0 = new RestClient(authority);
var request0 = new RestRequest(Method.POST);
request0.AddHeader("content-type", "application/json");
request0.AddParameter("application/json", "{\"grant_type\":\"client_credentials\",\"client_id\": \"" + clientId + "\",\"client_secret\": \""
+ clientSecret + "\",\"audience\": \"" + apiIdentifier + "\"}", ParameterType.RequestBody);
IRestResponse response1 = client0.Execute(request0);
var resp1 = JsonConvert.DeserializeObject<Auth0Response>(response1.Content);
Console.WriteLine("Press any key to send a request. Press ESC to exit...");
while (Console.ReadKey().Key != ConsoleKey.Escape)
{
var client1 = new RestClient("http://localhost:3010/api/private");
var request1 = new RestRequest(Method.GET);
request1.AddHeader("authorization", $"Bearer {resp1.AccessToken}");
IRestResponse response = client1.Execute(request1);
Console.WriteLine($"Response from /private: ${response.Content}");
var client2 = new RestClient("http://localhost:3010/api/private-scoped");
var request2 = new RestRequest(Method.GET);
request2.AddHeader("authorization", $"Bearer {resp1.AccessToken}");
IRestResponse response2 = client2.Execute(request1);
Console.WriteLine($"Response from /private-scoped: {response2.Content}");
}
Console.ReadKey(true);
}
}
}
<file_sep>/Study.Auth0/Controllers/ApiController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Study.Auth0.Server.Filters;
namespace Study.Auth0.Server.Controllers
{
[Route("api")]
public class ApiController : Controller
{
[HttpGet]
[Route("public")]
public IActionResult Public()
{
return Json(new
{
Message = "Hello from a public endpoint! You don't need to be authenticated to see this."
});
}
[HttpGet]
[Route("private")]
[Authorize, WithRoles("admin,user")]
public IActionResult Private()
{
return Json(new
{
Message = "Hello from a private endpoint! You need to be authenticated to see this."
});
}
[HttpGet]
[Route("private-scoped")]
[Authorize("read:messages")]
public IActionResult Scoped()
{
return Json(new
{
Message = "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this."
});
}
[HttpGet]
[Route("private-admin")]
[Authorize(Roles = "admin")]
public IActionResult Admin()
{
return Json(new
{
Message = "Hello from a private endpoint! You need to be authenticated and have an admin role."
});
}
}
}<file_sep>/Study.EventSourcing/Event/BatchedPersonNameChangedEvent.cs
using System.Collections.Generic;
namespace Study.EventSourcing.Event
{
public class BatchedPersonNameChangedEvent
{
public List<PersonNameChangedEvent> Events { get; set; } = new List<PersonNameChangedEvent>();
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/Routes/GetBasket.cs
using System.Threading.Tasks;
using Akka.Actor;
using Microsoft.Extensions.Logging;
namespace Study.AkkaNet.Interview.Web.Baskets.Routes
{
public class GetBasket
{
private readonly ILogger<GetBasket> _logger;
private IActorRef _basketActor;
public GetBasket(BasketsActorProvider provider, ILogger<GetBasket> logger)
{
_logger = logger;
_basketActor = provider.Get();
}
public async Task<Basket> Execute(int customerId)
{
_logger.LogInformation($"Getting basket with customer id of {customerId}.");
return await _basketActor.Ask<Basket>(new BasketActor.GetBasket(customerId));
}
}
}<file_sep>/Study.EventSourcing/BusConfigurator.cs
using System;
using MassTransit;
using Study.EventSourcing.Consumer;
namespace Study.EventSourcing
{
public class BusConfigurator
{
public static IBusControl CreateBus()
{
var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
{
var host = sbc.Host(new Uri("rabbitmq://localhost"), h =>
{
h.Username("guest");
h.Password("<PASSWORD>");
});
sbc.ReceiveEndpoint(host, "person_queue", ep =>
{
ep.Consumer<UpdatePersonConsumer>();
ep.BindMessageExchanges = true;
});
});
return bus;
}
}
}<file_sep>/Study.Sorting/Patterns/SingletonB.cs
namespace Study.Algo.Patterns
{
public sealed class SingletonB
{
private static SingletonB _instance = null;
private static readonly object Lock = new object();
private SingletonB() { }
public static SingletonB Instance
{
get
{
lock (Lock)
return _instance ?? (_instance = new SingletonB());
}
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/BasketsActor.cs
using Akka.Actor;
using Study.AkkaNet.Interview.Web.Core.Messaging;
namespace Study.AkkaNet.Interview.Web.Baskets
{
public class BasketsActor : ReceiveActor
{
public IActorRef ProductActor { get; }
public BasketsActor(IActorRef productActor)
{
ProductActor = productActor;
ReceiveAny(message =>
{
switch (message)
{
case MessageWithCustomerId envelope:
var child = Context.Child(envelope.CustomerId.ToString());
if (child is Nobody)
child = Context.ActorOf(BasketActor.Props(ProductActor), envelope.CustomerId.ToString());
child.Forward(envelope);
break;
}
});
}
public static Props Props(IActorRef productsActor)
{
return Akka.Actor.Props.Create(() => new BasketsActor(productsActor));
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/MaximumProductSubarray.cs
using System;
namespace Study.Algo.AlgoChallenge
{
/// <summary>
/// Given an array that contains both positive and negative integers, find the product of the maximum product subarray.
/// </summary>
public class MaximumProductSubarray
{
public static int? RunImplementationA(int[] numberArray)
{
int? lastNegativeNumber = null;
int? currentMax = null, lastMax = null;
foreach (var number in numberArray)
{
if (number < 0 && lastNegativeNumber == null)
lastNegativeNumber = number;
else if (number > 0)
currentMax = currentMax == null ? number : currentMax * number;
else if (number < 0 && lastNegativeNumber < 0)
{
var temp = number * lastNegativeNumber.Value;
currentMax = currentMax == null ? temp : currentMax * temp;
lastNegativeNumber = null; // reset
}
else if (number == 0)
{
lastMax = GetMax(currentMax, lastMax, number);
currentMax = null;
lastNegativeNumber = null; // reset
}
}
return GetMax(currentMax, lastMax, lastNegativeNumber);
}
private static int? GetMax(int? currentMax, int? lastMax, int? defaultValue)
=> lastMax == null
? currentMax ?? defaultValue
: currentMax != null ? Math.Max(lastMax.Value, currentMax.Value) : lastMax;
/* Source: https://www.geeksforgeeks.org/maximum-product-subarray/ and https://www.quora.com/How-do-I-solve-maximum-product-subarray-problems */
public static int? RunImplementationB(int[] arr)
{
int maxEndingHere = 1, minEndingHere = 1, maxSoFar = 1;
foreach (var number in arr)
{
if (number > 0)
{
maxEndingHere = maxEndingHere * number;
minEndingHere = Min(minEndingHere * number, 1);
}
else if (number == 0)
{
maxEndingHere = 1;
minEndingHere = 1;
}
else
{
var temp = maxEndingHere;
maxEndingHere = Max(minEndingHere * number, 1);
minEndingHere = temp * number;
}
if (maxSoFar < maxEndingHere)
maxSoFar = maxEndingHere;
}
return maxSoFar;
}
private static int Min(int x, int y) => x < y ? x : y;
private static int Max(int x, int y) => x > y ? x : y;
}
}<file_sep>/Study.EventSourcing/DAL/Model/Person.cs
using SQLite;
namespace Study.EventSourcing.DAL.Model
{
public class Person
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
[Unique]
public string Keyword { get; set; }
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/BasketActor.cs
using System;
using System.Threading.Tasks;
using Akka.Actor;
using Study.AkkaNet.Interview.Web.Products;
namespace Study.AkkaNet.Interview.Web.Baskets
{
public partial class BasketActor : ReceiveActor
{
public Basket BasketState { get; set; } = new Basket();
public IActorRef ProductsActorRef { get; }
public BasketActor(IActorRef productsActor)
{
ProductsActorRef = productsActor;
Receive<GetBasket>(_ => Sender.Tell(BasketState));
ReceiveAsync<AddItemToBasket>(m => AddItemToBasketAction(m).PipeTo(Sender), m => m.Amount > 0);
Receive<RemoveItemFromBasket>(m => Sender.Tell(RemoveItemToBasketAction(m)));
}
public static Props Props(IActorRef productActor) => Akka.Actor.Props.Create(() => new BasketActor(productActor));
private async Task<BasketEvent> AddItemToBasketAction(AddItemToBasket message)
{
var productActorResult = await this.ProductsActorRef.Ask<ProductsActor.ProductEvent>(
new ProductsActor.UpdateStock(message.ProductId, -message.Amount)
);
switch (productActorResult)
{
case ProductsActor.StockUpdated _:
{
var product = ((ProductsActor.StockUpdated)productActorResult).Product;
return AddToBasket(product, message.Amount) as ItemAdded;
}
case ProductsActor.ProductNotFound _:
return new ProductNotFound();
case ProductsActor.InsufficientStock _:
return new NotInStock();
default:
throw new NotImplementedException($"Unknown response: {productActorResult.GetType().ToString()}");
}
}
private BasketEvent RemoveItemToBasketAction(RemoveItemFromBasket message)
{
var basketItem = BasketState.Items.Find(item => item.Id == message.BasketItemId);
switch (basketItem)
{
case BasketItem _:
BasketState.Items.Remove(basketItem);
return new ItemRemoved();
default:
return new ItemNotFound();
}
}
private ItemAdded AddToBasket(Product productToAdd, int amount)
{
var existingBasketItemWithProduct = BasketState.Items.Find(item => item.ProductId == productToAdd.Id);
switch (existingBasketItemWithProduct)
{
case BasketItem _:
// Add to existing basket item
existingBasketItemWithProduct.Amount += amount;
return new ItemAdded(basketItemId: existingBasketItemWithProduct.Id);
default:
// Create a new basket item
var basketItemId = Guid.NewGuid();
this.BasketState.Items.Add(new BasketItem
{
Id = basketItemId,
ProductId = productToAdd.Id,
Title = productToAdd.Title,
Brand = productToAdd.Brand,
PricePerUnit = productToAdd.PricePerUnit,
Amount = amount
});
return new ItemAdded(basketItemId);
}
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Products/Routes/GetAllProducts.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using Akka.Actor;
using Microsoft.Extensions.Logging;
namespace Study.AkkaNet.Interview.Web.Products.Routes
{
public class GetAllProducts
{
private readonly ILogger<GetAllProducts> _logger;
private readonly IActorRef _productsActor;
public GetAllProducts(ProductsActorProvider provider, ILogger<GetAllProducts> logger)
{
_logger = logger;
_productsActor = provider.Get();
}
public async Task<IEnumerable<Product>> Execute()
{
_logger.LogInformation("Requesting all products");
return await _productsActor.Ask<IEnumerable<Product>>(new ProductsActor.GetAllProducts());
}
}
}<file_sep>/Study.Websocket.Client/WebsocketSharpApp.cs
using System;
using System.Text;
using Newtonsoft.Json;
using Study.Websocket.Common;
using WebSocketSharp;
namespace Study.Websocket.Client
{
public class WebsocketSharpApp
{
public static void Run(string url)
{
using (var ws = new WebSocket(url))
{
ws.OnMessage += (sender, e) => Console.WriteLine("Received: " + e.Data);
ws.Connect();
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
var message = new Message<string> { Data = "Hello world" };
var json = JsonConvert.SerializeObject(message);
ws.Send(Encoding.UTF8.GetBytes(json));
Console.WriteLine("Sent");
}
ws.Close();
}
}
}
}<file_sep>/Study.EventSourcing/DAL/SqliteDbContext.cs
using SQLite;
using Study.EventSourcing.DAL.EventSourcingHistory;
using Study.EventSourcing.DAL.Model;
namespace Study.EventSourcing.DAL
{
public class SqliteDbContext
{
public SQLiteConnection Db { get; }
public SqliteDbContext()
{
Db = new SQLiteConnection("MyData.db");
}
public void CreateTables()
{
Db.CreateTable<Person>();
Db.CreateTable<PersonNameChangedHistoryItem>();
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Products/ProductsActorProvider.cs
using Akka.Actor;
namespace Study.AkkaNet.Interview.Web.Products
{
public class ProductsActorProvider
{
private readonly IActorRef _productsActor;
public ProductsActorProvider(ActorSystem actorSystem)
{
var sampleData = SampleData.Get();
_productsActor = actorSystem.ActorOf(Props.Create<ProductsActor>(sampleData), "products");
}
public IActorRef Get() => _productsActor;
}
}<file_sep>/Study.Websocket.Server/MIddleware/WebSocketMiddleware.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Study.Websocket.Server.MIddleware
{
public class WebSocketMiddleware
{
public static async Task ProcessRequest(HttpContext context, Func<Task> next)
{
if (!context.WebSockets.IsWebSocketRequest)
{
await next();
return;
}
var hub = context.RequestServices.GetService<Hub>();
var ws = await context.WebSockets.AcceptWebSocketAsync();
switch (context.Request.Path.Value.ToLowerInvariant())
{
case "/hello":
await hub.SayHello(ws);
break;
default:
context.Response.StatusCode = StatusCodes.Status400BadRequest;
break;
}
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Products/Routes/ProductApiController.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Study.AkkaNet.Interview.Web.Products.Routes
{
[Route("/products")]
public class ProductApiController
{
public GetAllProducts GetAllProducts { get; }
public ProductApiController(GetAllProducts getAllProducts)
{
GetAllProducts = getAllProducts;
}
[HttpGet]
public async Task<IEnumerable<Product>> Get() => await this.GetAllProducts.Execute();
}
}<file_sep>/Study.EventSourcing/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MassTransit;
using Study.EventSourcing.Command;
using Study.EventSourcing.DAL;
using Study.EventSourcing.DAL.Model;
using Study.EventSourcing.DAL.Repository;
using Study.EventSourcing.Event;
namespace Study.EventSourcing
{
class Program
{
private const string KeywordDummy = "dummy";
static async Task Main(string[] args)
{
var context = new SqliteDbContext();
context.CreateTables();
var bus = BusConfigurator.CreateBus();
await bus.StartAsync();
// Create or get dummy person
var personRepository = new PersonRepository(context);
var person = personRepository.Find(KeywordDummy);
if (person == null)
{
personRepository.Insert(new Person {Name = "John", Keyword = KeywordDummy });
person = personRepository.Find(KeywordDummy);
}
// Replay history
var historyItems = new EventSourcingRepository(context).GetHistoryItems();
var events = historyItems?.Select(x => x.GetEvent()).ToList() ?? new List<PersonNameChangedEvent>();
await bus.Publish(new BatchedPersonNameChangedEvent { Events = events });
//foreach (var personNameChangedEvent in events)
// await bus.Publish(personNameChangedEvent);
while (true)
{
Console.WriteLine("Enter new name");
var newName = Console.ReadLine();
if (string.IsNullOrWhiteSpace(newName))
break;
await bus.Publish(new ChangePersonNameCommand {Id = person.Id, NewName = newName});
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
await bus.StopAsync();
}
}
}
<file_sep>/Study.Sorting.Tests/AlgoChallenge/LinkedListDeleteGreaterValueNodesTests.cs
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class LinkedListDeleteGreaterValueNodesTests
{
[TestCase(new []{1, 10}, 2, new [] {1})]
[TestCase(new []{1, 2, 8, 4, -2, 15, 14, 7}, 6, new [] {1, 2, 4, -2})]
[TestCase(new int[0], 0, new int[0])]
public void Test1(int[] arr, int maxAllowedValue, int[] expectedArr)
{
var linkedList = new LinkedList<int>(arr);
LinkedListDeleteGreaterValueNodes.Run(linkedList, maxAllowedValue);
var result = linkedList.ToArray();
Assert.AreEqual(expectedArr, result);
}
}
}<file_sep>/Study.EventSourcing/Event/PersonNameChangedEvent.cs
namespace Study.EventSourcing.Event
{
public class PersonNameChangedEvent : Event
{
public int Id { get; set; }
public string Name { get; set; }
}
}<file_sep>/Study.Sorting/ProblemSolvingInDataStructuresBook/ChapterOnSortingExersize01.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Study.Algo.ProblemSolvingInDataStructuresBook
{
public class ChapterOnSortingExersize01
{
public static Dictionary<string, int> PrintWordsWithFrequency(string sentence)
=> sentence.Split(new [] {' ', ',', '\n', '\\'}, StringSplitOptions.RemoveEmptyEntries)
.GroupBy(x => x, (s, enumerable) => (s, enumerable.Count()))
.OrderByDescending(x => x.Item2)
.ToDictionary(pair => pair.Item1, pair => pair.Item2);
}
}<file_sep>/Study.EventSourcing/DAL/EventSourcingHistory/PersonNameChangedHistoryItem.cs
using System;
using Newtonsoft.Json;
using SQLite;
using Study.EventSourcing.Event;
namespace Study.EventSourcing.DAL.EventSourcingHistory
{
public class PersonNameChangedHistoryItem
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Payload { get; set; }
public DateTime UpdatedOn { get; set; }
public PersonNameChangedEvent GetEvent() => JsonConvert.DeserializeObject<PersonNameChangedEvent>(Payload);
}
}<file_sep>/Study.Sorting/Helpers.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Study.Algo
{
public static class Helpers
{
public static IEnumerable<T[]> Combinations<T>(this IList<T> argList, int argSetSize)
{
if (argList == null) throw new ArgumentNullException("argList");
if (argSetSize <= 0) throw new ArgumentException("argSetSize Must be greater than 0", "argSetSize");
return CombinationsImpl(argList, 0, argSetSize - 1);
}
private static IEnumerable<T[]> CombinationsImpl<T>(IList<T> argList, int argStart, int argIteration, List<int> argIndicies = null)
{
argIndicies = argIndicies ?? new List<int>();
for (int i = argStart; i < argList.Count; i++)
{
argIndicies.Add(i);
if (argIteration > 0)
{
foreach (var array in CombinationsImpl(argList, i + 1, argIteration - 1, argIndicies))
{
yield return array;
}
}
else
{
var array = new T[argIndicies.Count];
for (int j = 0; j < argIndicies.Count; j++)
{
array[j] = argList[argIndicies[j]];
}
yield return array;
}
argIndicies.RemoveAt(argIndicies.Count - 1);
}
}
// Variations
public static IEnumerable<string> VariationsOf(string source, int count)
{
if (source.Length == 1)
{
yield return source;
}
else if (count == 1)
{
for (var n = 0; n < source.Length; n++)
{
yield return source.Substring(n, 1);
}
}
else
{
for (var n = 0; n < source.Length; n++)
foreach (var suffix in VariationsOf(
source.Substring(0, n)
+ source.Substring(n + 1, source.Length - n - 1), count - 1))
{
yield return source.Substring(n, 1) + suffix;
}
}
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/KClosestPointsToOriginTests.cs
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class KClosestPointsToOriginTests
{
[Test]
public void Test01()
{
var points = new List<(int X, int Y)> { (-2, -4), (0, -2), (-1, 0), (3, -5), (-2, -3), (3, 2)};
var results = KClosestPointsToOrigin.Find(points, 3).ToList();
var xyResults = results.Select(result => (result.X, result.Y)).OrderBy(x => x.Item1).ThenBy(x => x.Item2).ToList();
Assert.AreEqual(new List<(int X, int Y)> { (-2, -3), (-1, 0), (0, -2)}, xyResults);
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/SortAlmostSortedArray.cs
using System.Collections.Generic;
namespace Study.Algo.AlgoChallenge
{
/// <summary>
/// Sort an almost sorted array where only two elements are swapped.
/// </summary>
public class SortAlmostSortedArray
{
public static bool Run(int[] arr)
{
int? i1 = null, i2 = null;
var n = arr.Length;
for (int i = 0; i < n; i++)
{
if (i1 == null && n - 1 > i && arr[i] > arr[i + 1])
i1 = i;
else if (i2 == null && i != 0 && arr[i] < arr[i - 1] && i1 != i-1)
i2 = i;
if (i1 != null && i2 != null)
{
(arr[i1.Value], arr[i2.Value]) = (arr[i2.Value], arr[i1.Value]);
return true;
}
}
return false;
}
}
}<file_sep>/Study.Websocket.Client/WebsocketNetApp.cs
using System;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Study.Websocket.Common;
namespace Study.Websocket.Client
{
public class WebsocketNetApp
{
public static async Task RunAsync(string url, CancellationToken token)
{
var ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri(url), token);
var tsc = new CancellationTokenSource();
var token1 = tsc.Token;
var t = Task.Run(() => Receive(ws, token1));
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
if (token.IsCancellationRequested)
break;
var message = new Message<string> { Data = "Hello world" };
var json = JsonConvert.SerializeObject(message);
var bytes = Encoding.UTF8.GetBytes(json);
var buffer = new ArraySegment<byte>(bytes);
await ws.SendAsync(buffer.Array, WebSocketMessageType.Text, true, token);
Console.WriteLine("Sent");
}
tsc.Cancel();
await t;
await ws.CloseAsync(WebSocketCloseStatus.Empty, "", token);
}
private static async Task Receive(ClientWebSocket webSocket, CancellationToken token)
{
while (webSocket.State == WebSocketState.Open)
{
using (var ms = new MemoryStream())
{
var buffer = new ArraySegment<byte>(new byte[8192]);
WebSocketReceiveResult result;
do
{
result = await webSocket.ReceiveAsync(buffer, token);
ms.Write(buffer.Array, buffer.Offset, buffer.Count);
} while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, token);
}
else
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var json = await reader.ReadToEndAsync();
var message = JsonConvert.DeserializeObject<Message<string>>(json);
Console.WriteLine(message.Data);
}
}
}
}
}
}
}<file_sep>/Study.EventSourcing/DAL/Repository/PersonRepository.cs
using Study.EventSourcing.DAL.EventSourcingHistory;
using Study.EventSourcing.DAL.Model;
namespace Study.EventSourcing.DAL.Repository
{
public class PersonRepository
{
private readonly SqliteDbContext _context;
public PersonRepository(SqliteDbContext context)
{
_context = context;
}
public int Insert(Person person) => _context.Db.Insert(person);
public void Update(Person person) => _context.Db.Update(person);
public Person Get(int id) => _context.Db.Table<Person>().FirstOrDefault(x => x.Id == id);
public Person Find(string keyword) => _context.Db.Table<Person>().FirstOrDefault(x => x.Keyword == keyword);
}
}<file_sep>/Study.AkkaNet.Interview.Web/Products/ProductsActor.Events.cs
namespace Study.AkkaNet.Interview.Web.Products
{
public partial class ProductsActor
{
public abstract class ProductEvent { }
public class ProductFound : ProductEvent
{
public Product Product { get; }
public ProductFound(Product product)
{
Product = product;
}
}
public class ProductNotFound : ProductEvent { }
public class StockUpdated : ProductEvent
{
public Product Product { get; }
public StockUpdated(Product product)
{
Product = product;
}
}
public class InsufficientStock : ProductEvent { }
}
}<file_sep>/Study.Sorting/Combinatorics/SimpleVariations.cs
using System.Collections;
using System.Collections.Generic;
namespace Study.Algo.Combinatorics
{
public class SimpleVariations : IEnumerable<IList<int>>
{
private int _myLowerIndex;
private List<int> _myValues;
public IEnumerator<IList<int>> GetEnumerator() => new SimpleEnumeratorWithoutRepetition(this);
IEnumerator IEnumerable.GetEnumerator() => new SimpleEnumeratorWithoutRepetition(this);
private void Initialize(List<int> values, int lowerIndex)
{
}
}
public class SimpleEnumeratorWithoutRepetition : IEnumerator<List<int>>
{
private readonly SimpleVariations _source;
public SimpleEnumeratorWithoutRepetition(SimpleVariations source)
{
_source = source;
}
public bool MoveNext()
{
throw new System.NotImplementedException();
}
public void Reset()
{
throw new System.NotImplementedException();
}
public List<int> Current { get; }
object IEnumerator.Current => Current;
public void Dispose()
{
throw new System.NotImplementedException();
}
}
}<file_sep>/Study.Sorting.Tests/Combinatorics/VariationsTests.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
namespace Study.Algo.Tests.Combinatorics
{
public class VariationsTests
{
[Test]
public void Test01()
{
int[] ints = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Variations<int> variations = new Variations<int>(ints.ToList(), 3);
foreach (IList<int> variation in variations)
TestContext.Out.WriteLine(string.Join("", variation));
}
}
}<file_sep>/Study.Websocket.Server/Hub.cs
using System.Net.WebSockets;
using System.Threading.Tasks;
using Study.Websocket.Common;
using Study.Websocket.Server.Extension;
namespace Study.Websocket.Server
{
public class Hub
{
public async Task SayHello(WebSocket ws)
{
while (true)
{
var message = await ws.Receive<string>();
if (message == null)
break;
await ws.Send($"Got {message.Data}. Right back at ya.");
}
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/Fibonacci.cs
using System.Collections.Generic;
namespace Study.Algo.AlgoChallenge
{
public static class Fibonacci
{
public static IEnumerable<int> GenerateSequence()
{
int a = 0, b = 1;
while (true)
{
yield return a;
(a, b) = (b, a + b);
}
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/Routes/BasketApiController.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Study.AkkaNet.Interview.Web.Baskets.Routes.Dto;
namespace Study.AkkaNet.Interview.Web.Baskets.Routes
{
[Route("/baskets")]
public class BasketApiController
{
private GetBasket GetBasket { get; }
private AddItemToBasket AddItemToBasket { get; }
private RemoveItemFromBasket RemoveItemFromBasket { get; }
public BasketApiController(GetBasket getBasket, AddItemToBasket addItemToBasket, RemoveItemFromBasket removeItemFromBasket)
{
GetBasket = getBasket;
AddItemToBasket = addItemToBasket;
RemoveItemFromBasket = removeItemFromBasket;
}
[HttpGet("{customerId}")]
public async Task<Basket> Get(int customerId)
=> await GetBasket.Execute(customerId);
[HttpPut("{customerId}/items")]
public async Task<IActionResult> PutItem(int customerId, [FromBody] AddItem item)
=> await AddItemToBasket.Execute(customerId, item.ProductId, item.Amount);
[HttpDelete("{customerId}/items/{basketItemId}")]
public async Task<IActionResult> DeleteItem(int customerId, Guid basketItemId)
=> await RemoveItemFromBasket.Execute(customerId, basketItemId);
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/BasketsActorProvider.cs
using Akka.Actor;
using Study.AkkaNet.Interview.Web.Products;
namespace Study.AkkaNet.Interview.Web.Baskets
{
public class BasketsActorProvider
{
private IActorRef BasketsActorInstance { get; }
public BasketsActorProvider(ActorSystem actorSystem, ProductsActorProvider provider)
{
var productsActor = provider.Get();
BasketsActorInstance = actorSystem.ActorOf(BasketsActor.Props(productsActor), "baskets");
}
public IActorRef Get() => BasketsActorInstance;
}
}<file_sep>/Study.Sorting/Patterns/SingletonD.cs
namespace Study.Algo.Patterns
{
public sealed class SingletonD
{
static SingletonD() { }
private SingletonD() { }
public static SingletonD Instance { get; } = new SingletonD();
}
}<file_sep>/Study.Websocket.Server/MIddleware/HttpMiddleware.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Study.Websocket.Server.MIddleware
{
public class HttpMiddleware
{
public static async Task ProcessRequest(HttpContext context, Func<Task> next)
{
await context.Response.WriteAsync("Hi");
}
}
}<file_sep>/Study.Sorting/SortingApps/BubbleSortApp.cs
using System.Collections.Generic;
using System.Linq;
namespace Study.Algo.SortingApps
{
public class BubbleSortApp
{
public static List<int> Sort(List<int> list)
{
var result = list.ToList();
for (int i = 0; i < list.Count; i++)
for (int j = 0; j < list.Count - 1; j++)
if (list[j] > list[j + 1])
(list[j], list[j + 1]) = (list[j + 1], list[j]);
return result;
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/FibonacciTests.cs
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class FibonacciTests
{
[Test]
public void Get10()
{
var expected = new List<int> {0, 1, 1, 2, 3, 5, 8, 13, 21, 34};
var result = Fibonacci.GenerateSequence().Take(10);
Assert.AreEqual(expected, result);
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/Routes/AddItemToBasket.cs
using System;
using System.Threading.Tasks;
using Akka.Actor;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Study.AkkaNet.Interview.Web.Baskets.Routes
{
public class AddItemToBasket
{
private readonly ILogger<AddItemToBasket> _logger;
private readonly IActorRef _basketActor;
public AddItemToBasket(BasketsActorProvider provider, ILogger<AddItemToBasket> logger)
{
_logger = logger;
_basketActor = provider.Get();
}
public async Task<IActionResult> Execute(int customerId, int productId, int amount)
{
_logger.LogInformation($"Adding {amount} of product '{productId}' to basket for customer '{customerId}'");
var result = await _basketActor.Ask<BasketActor.BasketEvent>(
new BasketActor.AddItemToBasket(customerId, productId, amount)
);
switch (result)
{
case BasketActor.ItemAdded itemAddedResult:
return new CreatedResult($"/api/baskets/{customerId}/", itemAddedResult.BasketItemId);
case BasketActor.ProductNotFound _:
case BasketActor.NotInStock _:
return new BadRequestResult();
default:
throw new NotSupportedException();
}
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/FizzBuzz.cs
using System.Collections.Generic;
namespace Study.Algo.AlgoChallenge
{
public class FizzBuzz
{
public static List<(int, string)> Run(params int[] input)
{
var prepared = new List<(int Number, string Sentence)>();
foreach (var number in input)
{
if (number % (3 * 5) == 0)
prepared.Add((number, "FizzBuzz"));
else if (number % 5 == 0)
prepared.Add((number, "Buzz"));
else if (number % 3 == 0)
prepared.Add((number, "Fizz"));
}
return prepared;
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/IntervalMergeTests.cs
using System.Collections.Generic;
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class IntervalMergeTests
{
[Test]
public void RunTest()
{
var input = new List<(int Start, int End)> { (1, 4), (8, 10), (3, 6) };
var output = IntervalMerge.Run(input);
var expectedOutput = new List<(int Start, int End)> { (1, 6), (8, 10) };
Assert.AreEqual(expectedOutput, output);
}
}
}<file_sep>/Study.Sorting.Tests/AlgoChallenge/MaximumProductSubarrayTests.cs
using NUnit.Framework;
using Study.Algo.AlgoChallenge;
namespace Study.Algo.Tests.AlgoChallenge
{
public class MaximumProductSubarrayTests
{
[Test]
public void Test1()
{
int[] arr = { 6, -3, -10, 0, 2 };
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(180));
}
[Test]
public void Test2()
{
int[] arr = {-1, -3, -10, 0, 60};
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(60));
}
[Test]
public void Test3()
{
int[] arr = { -2, -3, 0, -2, -40 };
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(80));
}
[Test]
public void Test4()
{
int[] arr = { -1, 0, 0, 1, -1, 1 };
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(1));
}
[Test]
public void Test5()
{
int[] arr = { 0 };
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(0));
}
[Test]
public void Test6()
{
int[] arr = { 1, -3, -5, -2, 0, 4, 9, 0, 3, -8, 7, -6 };
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(1008));
}
[Test]
public void Test7()
{
int[] arr = { -1 };
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(-1));
}
[Test]
public void Test8()
{
int[] arr = { };
var result = MaximumProductSubarray.RunImplementationA(arr);
Assert.That(result, Is.EqualTo(null));
}
}
}<file_sep>/Study.AkkaNet.Interview.Web/Baskets/Routes/RemoveItemFromBasket.cs
using System;
using System.Threading.Tasks;
using Akka.Actor;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Study.AkkaNet.Interview.Web.Baskets.Routes
{
public class RemoveItemFromBasket
{
private readonly ILogger<RemoveItemFromBasket> _logger;
private readonly IActorRef _basketActor;
public RemoveItemFromBasket(BasketsActorProvider provider, ILogger<RemoveItemFromBasket> logger)
{
_logger = logger;
_basketActor = provider.Get();
}
public async Task<IActionResult> Execute(int customerId, Guid basketItemId)
{
_logger.LogInformation($"Removing item {basketItemId} from basket of customer {customerId}");
var result = await _basketActor.Ask<BasketActor.BasketEvent>(
new BasketActor.RemoveItemFromBasket(customerId, basketItemId));
switch (result)
{
case BasketActor.ItemRemoved _:
return new OkResult();
case BasketActor.ItemNotFound _:
return new NotFoundResult();
default:
throw new NotSupportedException();
}
}
}
}<file_sep>/Study.Sorting/ProblemSolvingInDataStructuresBook/Chapter01Exersizes.cs
using System;
using System.Collections.Generic;
namespace Study.Algo.ProblemSolvingInDataStructuresBook
{
public class Chapter01Exersizes
{
/// <summary>
/// Find the average of all the elemens in an array
/// </summary>
public static int Exersize01(List<int> list)
{
var sum = 0;
for (int i = 0; i < list.Count; i++)
sum += list[i];
return sum / list.Count;
}
/// <summary>
/// Find the sum of all the elements of a two dimensional array
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
public static int Exersize02(int[][] arr)
{
var sum = 0;
for (int i = 0; i < arr.Length; i++)
for (int j = 0; j < arr[i].Length; j++)
sum += arr[i][j];
return sum;
}
/// <summary>
/// Find the largest item
/// </summary>
/// <returns></returns>
public static int Exersize03(List<int> list)
{
int largest = int.MinValue;
for (int i = 0; i < list.Count; i++)
{
if (list[i] > largest)
largest = list[i];
}
return largest;
}
/// <summary>
/// Find the second largest item
/// </summary>
/// <returns></returns>
public static int Exersize05(List<int> list)
{
int largest = int.MinValue;
int secondLargest = int.MinValue;
for (int i = 0; i < list.Count; i++)
{
if (list[i] > largest)
{
secondLargest = largest;
largest = list[i];
}
else if (list[i] > secondLargest)
secondLargest = list[i];
}
return secondLargest;
}
/// <summary>
/// Given a list of intervals, merge all overlapping intervals
/// </summary>
/// <param name="intervals"></param>
/// <returns></returns>
public static List<(int, int)> Exersize09(List<(int, int)> intervals)
{
var results = new List<(int, int)>();
for (int i = 0; i < intervals.Count; i++)
{
for (int j = 0; j < intervals.Count-1; j++)
{
if (i == j)
continue;
// TODO
//if (intervals[i].Item1 >= intervals[j].Item2 && intervals[i].Item2 >= intervals[j].Item1)
//{
// results.Add();
//}
}
}
throw new NotImplementedException();
}
}
}<file_sep>/Study.Sorting/AlgoChallenge/BinaryTreeTraversal.cs
using System.Collections.Generic;
namespace Study.Algo.AlgoChallenge
{
public class BinaryTreeTraversal
{
public class Node
{
public int Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
}
public class Tree
{
public Node Root { get; set; }
public void Insert(int value)
{
Node node = new Node {Value = value};
var current = Root;
if (current == null)
{
Root = node;
return;
}
while (true)
{
if (value < current.Value)
{
if (current.Left == null)
{
current.Left = node;
return;
}
current = current.Left;
}
else
{
if (current.Right == null)
{
current.Right = node;
return;
}
current = current.Right;
}
}
}
public IEnumerable<int> Inorder(Node root)
{
if (root != null)
{
foreach (var i in Inorder(root.Left)) yield return i;
yield return root.Value;
foreach (var i in Inorder(root.Right)) yield return i;
}
}
public IEnumerable<int> Preorder(Node root)
{
if (root != null)
{
yield return root.Value;
foreach (var i in Preorder(root.Left)) yield return i;
foreach (var i in Preorder(root.Right)) yield return i;
}
}
public IEnumerable<int> Postorder(Node root)
{
if (root != null)
{
foreach (var i in Postorder(root.Left)) yield return i;
foreach (var i in Postorder(root.Right)) yield return i;
yield return root.Value;
}
}
}
}
}<file_sep>/Study.EventSourcing/DAL/Repository/EventSourcingRepository.cs
using System.Collections.Generic;
using System.Linq;
using Study.EventSourcing.DAL.EventSourcingHistory;
namespace Study.EventSourcing.DAL.Repository
{
public class EventSourcingRepository
{
private readonly SqliteDbContext _context;
public EventSourcingRepository(SqliteDbContext context)
{
_context = context;
}
public List<PersonNameChangedHistoryItem> GetHistoryItems()
=> _context.Db.Table<PersonNameChangedHistoryItem>().OrderBy(x => x.UpdatedOn).ToList();
public void AddHistoryItem(PersonNameChangedHistoryItem @event) => _context.Db.Insert(@event);
}
}<file_sep>/Study.Sorting/Patterns/SingletonA.cs
namespace Study.Algo.Patterns
{
public sealed class SingletonA
{
private static SingletonA instance = null;
private SingletonA() { }
public static SingletonA Instance => instance ?? (instance = new SingletonA());
}
}<file_sep>/study-auth0-frontend/src/App.js
import React, {Component} from 'react';
import './App.css';
import { Navbar, Button } from 'react-bootstrap';
import './App.css';
class App extends Component {
goTo(route) {
this.props.history.replace(`/${route}`)
}
login() {
this.props.auth.login();
}
logout() {
this.props.auth.logout();
}
async checkIfLoggedIn() {
const token = this.props.auth.getToken();
console.info(`checkIfLoggedIn using token ${token}`);
await fetch('http://localhost:3010/api/private', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
})
.catch(reason => console.error(reason))
.then(value => console.info(value));
}
async getUserInfo() {
const response = await this.props.auth.userinfo();
console.log(response);
}
render() {
const {isAuthenticated} = this.props.auth;
return (
<div>
<Navbar fluid>
<Navbar.Header>
<Navbar.Brand>
<a href="#">Auth0 - React</a>
</Navbar.Brand>
<Button
bsStyle="primary"
className="btn-margin"
onClick={this.goTo.bind(this, 'home')}
>
Home
</Button>
{
!isAuthenticated() && (
<Button
bsStyle="primary"
className="btn-margin"
onClick={this.login.bind(this)}
>
Log In
</Button>
)
}
{
isAuthenticated() && (
<div>
<Button
bsStyle="primary"
className="btn-margin"
onClick={this.checkIfLoggedIn.bind(this)}
>
Check if logged in
</Button>
<Button
bsStyle="primary"
className="btn-margin"
onClick={this.getUserInfo.bind(this)}
>
Get user info
</Button>
<Button
bsStyle="primary"
className="btn-margin"
onClick={this.logout.bind(this)}
>
Log Out
</Button>
</div>
)
}
</Navbar.Header>
</Navbar>
</div>
);
}
}
export default App;
| 1950408128920c8f46490bd2e94ef4b06285fc20 | [
"JavaScript",
"C#"
] | 78 | C# | jackinf/Studying | d572d5ba1362d84cc5094f2ea1645baec447b442 | d6c7b8b8de44a15887cf764ce488ba2923b2246a |
refs/heads/master | <repo_name>udot-a/notes<file_sep>/client/src/services/dispatchMiddleware.js
import {httpRequest} from "./index";
/*
Ф-ция HOF к-я дает возможность dispatch возвращаемой useReducer работать с асинхронным кодом
*/
const dispatchMiddleware = dispatch => {
return (action) => {
const getData = async (action) => {
const payload = await httpRequest("http://localhost:3000/notes");
return dispatch({...action, payload});
}
const delItem = async() => {
await httpRequest(`http://localhost:3000/notes/${action.id}`, "DELETE");
await getData({type: "LOAD_DATA"});
}
const createItem = async() => {
await httpRequest(`http://localhost:3000/notes`, "POST", action.payload);
await getData({type: "LOAD_DATA"});
}
const updateItem = async() => {
await httpRequest(`http://localhost:3000/notes/${action.id}`, "PUT", action.payload);
await getData({type: "LOAD_DATA"});
}
switch (action.type) {
case "LOAD_DATA":
return getData(action);
case "DELETE":
return delItem();
case "CREATE":
return createItem();
case "UPDATE":
return updateItem();
default:
return dispatch(action);
}
};
}
export {dispatchMiddleware}
<file_sep>/client/src/services/Context.js
import {createContext} from "react";
function noop() {}
export const Context = createContext({
dispatch: noop,
state: null
})
<file_sep>/client/src/layouts/MainLayout.jsx
import React, {useContext} from "react";
import {Link} from "react-router-dom";
import {Context} from "../services";
import {vocabulary as v} from "./MainLayot.lang";
import css from "./MainLayout.module.scss"
const MainLayout = ({children}) => {
const {dispatch, state: { language: lg }} = useContext(Context);
const {pointer, wrap, center} = css;
const clickHandler = ({target: { textContent }}) => {
dispatch({type: textContent});
}
return (
<div className={wrap}>
<nav className={"navbar navbar-dark bg-dark"}>
<Link className={"navbar-brand"} to="/">
{v[lg].pageTitle}
</Link>
<div>
<span
className={`badge badge-${lg === "ru" ? "primary" : "secondary"} ${pointer}`}
data-testid={"ru"}
onClick={clickHandler}
>
{"RU"}
</span>
<span
className={`badge badge-${lg === "eng" ? "primary" : "secondary"} ${pointer}`}
data-testid={"eng"}
onClick={clickHandler}
>
{"ENG"}
</span>
</div>
</nav>
<div className={center}>
{children}
</div>
</div>
)
}
export {MainLayout};
<file_sep>/client/src/services/index.js
import {reducer} from "./reducer";
import {dispatchMiddleware} from "./dispatchMiddleware";
import {Context} from "./Context";
import {httpRequest} from "./httpRequest";
import {Note} from "./noteClass";
import {Language} from "./languageClass";
import {pause} from "./pause";
export {
reducer,
dispatchMiddleware,
httpRequest,
Context,
Note,
Language,
pause
}
<file_sep>/client/src/services/reducer.js
/*
Функция которая является аргументом useReducer
*/
const reducer = (state, action) => {
switch (action.type) {
case 'LOAD_DATA':
return {
...state,
data: action.payload
};
case 'RU':
return {
...state,
language: "ru"
};
case 'ENG':
return {
...state,
language: "eng"
};
default:
return state;
}
}
export {reducer};
| 00a92f35b0243cb8e7919b7ebd780f9a211b16c6 | [
"JavaScript"
] | 5 | JavaScript | udot-a/notes | cad7a0a25b03da46bbfa943fd4b0b26be8f2aa44 | f96c0b638e866e2aa2de12e261fc24820a447374 |
refs/heads/master | <file_sep>DROP DATABASE IF EXISTS employees_db;
CREATE DATABASE employees_db;
USE employees_db;
CREATE TABLE department(
id INT NOT NULL AUTO_INCREMENT,
department_name VARCHAR(30) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE role(
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(30) NOT NULL,
salary DECIMAL(6,0) NOT NULL,
department_id INT(30) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE employee(
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
role_id INT NOT NULL,
manager_id INT(30),
PRIMARY KEY (id)
);
INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ("Ulf", "Erstenschlager", 1, NULL),
("Zilchina", "Alleslieber", 1, NULL),
("Troy", "McCloyerson", 1, NULL),
("Little", "Managedman", 2, 1);
INSERT INTO role (title, salary, department_id )
VALUES ("Manager", 90000, 1),
("HR clerk", 10000, 2),
("Accountant", 50000, 3);
INSERT INTO department (department_name)
VALUES ("Managerial Department"),
("Human Resources"),
("Accounts Receivable");<file_sep>var mysql = require("mysql");
var inquirer = require("inquirer");
const cTable = require('console.table');
var connection = mysql.createConnection({
host: "localhost",
// Your port; if not 3306
port: 3306,
// Your username
user: "root",
// Your password
password: "",
database: "employees_db"
});
connection.connect(function (err) {
if (err) throw err;
// run the start function after the connection is made to prompt the user
start();
});
function start() {
inquirer
.prompt({
name: "startCommand",
type: "list",
message: "What would you like to do?",
choices: ["View all employees", "View all roles", "View all departments", "Add employee", "Add role", "Add department", "Update employee role", "Exit"]
})
.then(function (answer) {
if (answer.startCommand === "View all employees") {
ViewAllEmployees();
}
else if (answer.startCommand === "View all roles") {
ViewAllRoles();
}
else if (answer.startCommand === "View all departments") {
ViewAllDepartments();
}
else if (answer.startCommand === "Add employee") {
CreateNewEmployee();
}
else if (answer.startCommand === "Add role") {
CreateNewRole();
}
else if (answer.startCommand === "Add department") {
CreateNewDepartment();
}
else if (answer.startCommand === "Update employee role") {
updateEmployeeRole();
}
else {
connection.end();
}
});
}
// UPDATE tableName
// SET column1 = value1,
function ViewAllEmployees() {
// query the database for all items being auctioned
connection.query("SELECT employee.id,employee.first_name,employee.last_name,title,department_name,salary,employee.manager_id FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department ON department.id = role.department_id", function (err, results) {
if (err) throw err;
console.log(cTable.getTable(results));
start();
// function to handle posting new items up for auction
});
}
function ViewAllRoles() {
// query the database for all items being auctioned
connection.query("SELECT role.*, department_name FROM role LEFT JOIN department ON department.id = role.department_id", function (err, results) {
if (err) throw err;
console.log(cTable.getTable(results));
start();
// function to handle posting new items up for auction
});
}
function ViewAllDepartments() {
connection.query("SELECT * FROM department", function (err, results) {
if (err) throw err;
console.log(cTable.getTable(results));
start();
});
}
function CreateNewEmployee() {
// let manager = ["No manager", "Mrs. <NAME>", "Sir Meistro Contractor", "Mr. Account Lord"]
inquirer
.prompt([
{
name: "firstName",
type: "input",
message: "What is the employee's first name?"
},
{
name: "lastName",
type: "input",
message: "What is the employee's last name?"
},
{
name: "role",
type: "number",
message: "What is the employee's role?"
},
{
name: "manager",
type: "number",
message: "Who is the employee's manager?"
}
])
.then(function (answer) {
// when finished prompting, insert a new item into the db with that info
connection.query(
"INSERT INTO employee SET ?",
{
first_name: answer.firstName,
last_name: answer.lastName,
role_id: answer.role,
manager_id: answer.manager
},
function (err) {
if (err) throw err;
console.log("New employee was created successfully!");
// re-prompt the user for if they want to bid or post
start();
}
);
});
}
function CreateNewRole() {
let roles = ["Contract Worker", "Human Resources", "Accounts Receivable"]
let departments = connection.query("SELECT * FROM department")
// prompt for info about the item being put up for auction
inquirer
.prompt([
{
name: "roleTitle",
type: "input",
message: "What is the title of the new role?"
},
{
name: "salary",
type: "number",
message: "What will the salary for this role be? [must enter numerical value]"
},
{
name: "department",
type: "input",
message: "Which department does this new role belong to?"
}
])
.then(function (answer) {
results = answer.department;
// when finished prompting, insert a new item into the db with that info
connection.query(
"INSERT INTO role SET ?",
{
title: answer.roleTitle,
salary: answer.salary,
department_id: answer.department
},
function (err) {
if (err) throw err;
console.log("New role was created successfully!");
roles.push(results);
start();
}
);
});
}
function CreateNewDepartment() {
let roles = ["Contract Worker", "Human Resources", "Accounts Receivable"]
let departments = connection.query("SELECT * FROM department")
// prompt for info about the item being put up for auction
inquirer
.prompt([
{
name: "NewDepartmentName",
type: "input",
message: "What is the new department you would like to add?"
}
])
.then(function (answer) {
// results = answer.NewDepartmentName;
// when finished prompting, insert a new item into the db with that info
connection.query(
"INSERT INTO department SET ?",
{
department_name: answer.NewDepartmentName
},
function (err) {
if (err) throw err;
console.log("New department was created successfully!");
// NewDepartmentName.push(results);
start();
}
);
});
}
function updateEmployeeRole() {
connection.query("SELECT first_name, last_name, id FROM employee",
function (err, res) {
let employees = res.map(employee => ({ name: employee.first_name + " " + employee.last_name, value: employee.id }))
let roles = res.map(role => ({ name: role.title, value: role.id }))
inquirer
.prompt([
{
type: "list",
name: "employeeName",
message: "Which employee's role would you like to update?",
choices: employees
},
{
type: "list",
name: "role",
message: "What is your new role?",
choices: roles
}
])
.then(function (res) {
connection.query(`UPDATE employee SET role_id = ${res.role} WHERE id = ${res.employeeName}`,
function (err, res) {
//updateRole(res);
start();
}
);
})
}
)
}; | 0261a03442a029106c20963d925f2e4c1fac57b8 | [
"JavaScript",
"SQL"
] | 2 | SQL | zilchlorf/Employee_Creeper_Deluxe | d5e7029ad14307413d28e60aee5273256a687a6d | 4fc85f78173bdee3f5c09a7cad51a00f3164e1e6 |
refs/heads/master | <file_sep># db-angular
Experimenting with learning angular by creating a simple music blog
<file_sep>describe('Controller: MainCtrl', function(){
beforeEach(module('dbApp'));
var ctrl;
beforeEach(inject(function($controller){
ctrl = $controller('MainCtrl');
}));
it('should have items available on load', function() {
expect(ctrl.posts).toEqual([
{id: 1, artist: 'Blah', title: 'Blah Blah', link: 'https://www.youtube.com/embed/hzqFmXZ8tOE?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'},
{id: 2, artist: 'Bblah', title: 'Who knows', link: 'https://www.youtube.com/embed/9Bmh9A8Dl1c?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'},
{id: 3, artist: 'Bblah', title: 'Who knows', link: 'https://www.youtube.com/embed/9Bmh9A8Dl1c?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'},
{id: 4, artist: 'Bbblah', title: 'Summat', link: 'https://www.youtube.com/embed/9Bmh9A8Dl1c?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'}
])
});
}); <file_sep>var dbApp = angular.module('dbApp', [])
dbApp.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
// Allow same origin resource loads.
'self',
// Allow loading from our assets domain. Notice the difference between * and **.
'https://www.youtube.com/embed/**'
]);
});
dbApp.controller('MainCtrl', ['$http', function($http) {
var self = this;
$http.get('http://localhost:3000/tunes.json').
success(function(data, status, headers, config) {
self.posts = data;
});
// self.posts = [
// {id: 1, artist: 'Blah', title: 'Blah Blah', link: 'https://www.youtube.com/embed/hzqFmXZ8tOE?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'},
// {id: 2, artist: 'Bblah', title: 'Who knows', link: 'https://www.youtube.com/embed/9Bmh9A8Dl1c?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'},
// {id: 3, artist: 'Bblah', title: 'Who knows', link: 'https://www.youtube.com/embed/9Bmh9A8Dl1c?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'},
// {id: 4, artist: 'Bbblah', title: 'Summat', link: 'https://www.youtube.com/embed/9Bmh9A8Dl1c?list=FL7wg_Gt_lNNcI8-Wxes6KGw}'}
// ];
}]);
| 136e8c357773b40893630f9330e13ad2892c959f | [
"Markdown",
"JavaScript"
] | 3 | Markdown | lukeclewlow/db-angular | f5eecb2ca3a080e2fde2f7994c78ce61e1c8f0c8 | 21a238c894de4ed5c4cd8690ec8e795688dfa82b |
refs/heads/master | <file_sep>#变量的使用
'''
1、变量名只能以下划线,字母开头。
2、变量名中可以有下划线,字母,数字。
2、尽量用小写,且有意义的命名,不同的单词用下划线隔开
'''
#关于报错
'''
当程序无法成功运行时,解释器会给我们一个traceback,让我们能及时发现错误所在。
'''
#字符串
'''
1、将字符串的每个单词的首字母改成大写。 str_name.title()
2、将字符串的小写全部改成大写,str_name.upper(),将字符串的大写全部改成大写,str_name.lower()
3、合并(拼接字符串):使用”+“
添加空白
1、制表符:\t
2、换行符:\n
删除空白
1.python能够找到字符串开头和末尾的多余的空格! str_name.rstrip() (删除只是暂时的) 永久删除必须把删除后的结果存回变量中去
2.删除开头的空格:lstrip()
3.删除开头和结尾的空格:strip()
'''
#数字
'''
1、整数,浮点数
2、将数字转换成字符串:str(num)
3、/ 得到的时一个浮点数, // 得到是时丢弃到小数部分的整数。
乘方:**
'''
message="hello world !"
print(message)
print(message.title())
print(message.upper())
print(message.lower())
name="python "
print(name)
name.rstrip()
print(name)<file_sep>#函数
'''
1、定义 函数名只使用下划线和小写字母
2、形参、实参 默认值
3、返回值
4、让形参变成可选的,利用默认值,给形参一个空的默认值
5、在函数中修改列表
6、在函数中禁止修改列表:创建列表的副本:list[:]
7、传递任意数量的实参 *让函数创建一个空元组,并将所有的参数都封装到这个元组中去
'''
'''
1、将函数存储在模块中
2、导入模块中的特定函数 form module_name import fiction_name
3、使用as给程序、模块指定别名 form module_name import fiction_name as other_name import module_name as other_name
4、导入模块中的所有函数 from module_name import *
5、传可变对象
6、传不可变对象
7、默认参数
8、lambda来创建匿名函数
'''
def greet(username='rainbow'):
print('hello,'+username)
def pizza(*toppings):
print(toppings)
greet()
pizza('onino','tomato','potato')
sum=lambda arg1, arg2: arg1 + arg2<file_sep># 类 对象 实例化等
'''
1、创建和使用类
2、self.name=name 中 右边的name是形参,将形参传入到name中,并将之关联到类的实例中,这样,类中的任何一个方法都可以使用这个参数。
age和name称为属性
3、创建类的实例,访问属性,修改属性的值,通过方法修改属性的值,调用方法
'''
class Dog():
'''一次模拟小狗的简单尝试'''
def __init__(self,name,age):
self.name=name
self.age=age
def update_age(self,age1):
self.age=age1
def sit(self):
'''模拟小狗被命令时的蹲下'''
print(self.name.title()+' is now sitting!')
def roll_over(self):
'''模拟小狗被命令时打滚'''
print(self.name.title()+'rolled over')
my_dog=Dog('wangwang',12)
print("my dog's name is "+my_dog.name.title()+'.')
my_dog.sit()
my_dog.roll_over()
my_dog.update_age(10)
print(my_dog.age)
#继承
'''
1、子类继承父类所有的方法和属性,同时还可以添加自己的属性和方法
2、super是一个特殊的函数,帮助python吧父类和子类关联起来
3、重写父类的方法,将实例作为属性
4、导入类 from module_name import class_name
5、在一个模块中导入另一个模块 from module_name import module_name/class_name
6、__init__.py
'''
class BigDog(Dog):
def __init__(self,name,age):
super().__init__(name,age)
self.height=50
def dog_height(self):
print("my dog's height is "+str(self.height))
my_big_dog=BigDog('bigwangwang',23)
print(my_big_dog.name.title())
print(my_big_dog.height)
#pthon标准库
'''
collection
'''
#模块
'''
1、__name__属性:一个模块被另一个程序第一次引入时,其主程序将运行。如果我们想在模块被引入时,模块中的某一程序块不执行,我们可以用__name__属性来使该程序块仅在该模块自身运行时执行。
2、标准模块
3、包:目录文件只有包含一个叫做__init__.py的文件时才会被认作是一个包
'''
if __name__ == '__main__':
print('程序自身在运行')
else:
print('我来自另一模块')
<file_sep># 访问列表元素,增删查改等功能
'''
1.指出列表名和列表的索引即可。
2.可以调用任何对string适用的方法,例如:title()
3.列表第一个元素的索引是0,列表最后一个元素的索引是-1(经常需要在不知道列表长度时访问最后一个元素)
4、list.append() 在列表末尾添加一个元素
5、list.insert(索引,值)
6、删除 若知道索引,可以用 del list[索引] list.pop() 删除列表末尾的数,并且可以接着用他 也可以list.pop(索引) 若不知道值的位置,list.removal(value),会删除第一个满足要求的数
'''
#组织列表
'''
1、使用sort()进行永久性的排序。若要反向排序,只需要sort(reverse=True)
2、使用sorted()可以对列表进行临时排序
3、使用reverse()将列表反向
4、确定列表的长度 len(list)
'''
#操作数组
'''
1、遍历整个数组, for x in list :
'''
bicycles=['trek','cannoadale','specialized']
print(bicycles)
list1=['car','bus','plane','boat']
#临时排序
print(sorted(list1))
list2=bicycles+list1
print(list2)
#数字数组
'''
1、使用range(),包括前面不包括后面
2、使用range创建数字列表。
3、处理数组,包括sum(),min(),max()
4、列表解析 amazing!
5、切片,遍历切片
6、复制列表
'''
for value in range(1,5):
print(value)
numbers=list(range(1,6))
print(numbers)
#列表解析
squares=[values**2 for values in range(1,11)]
print(squares)
big_num=[int(n) for n in range(1,1000001)]
print(big_num[0:10])
print(min(big_num))
print(max(big_num))
print(sum(big_num))<file_sep>#coding:utf-8
#文件
'''
1、读取文件 open() rstrip()删除结尾的空行 在windows中,反斜杠表示文件路径
2、逐行读取
3、创建一个包含文件各行内容的列表
4、处理包含大量数据的文件,检查圆周率包含我的生日吗?
'''
'''
1、写入空文件 读取模式('r') 写入模式('w') 附加模式('a') 读取写入模式('r+')
2、写入多行
3、附加模式 打开附加模式就可以
'''
with open('README.md',encoding='utf-8') as file_object:
contents=file_object.read()
print(contents.rstrip())
with open('README.md',encoding='utf-8') as f:
for line in f:
print(line)
with open('README.md',encoding='utf-8') as ff:
lins=ff.readlines()
for lin in lins:
print(lin.rstrip())
filename='learnprogramming.txt'
with open(filename,'w') as write:
write.write('I love programming!\n')
write.write('so sad!\n')
#异常
'''
1、try except 使用异常避免崩溃 else
2、FileNoFoundError异常
3、split() 将字符串转换成单词列表
4、使用多个文件
5、pass语句告诉程序什么都不做
'''
#抛出异常
'''
1、raise Exception
'''<file_sep>#for
'''
1、条件测试
2、and , or , in , not in
'''
'''
it's so easy that I don't need to do any notes or any practices.
'''<file_sep>#关于报错
'''
1、IndexError:list out of range 数组超出索引
2、IndentationError:expected a indented block 循环后面没有缩进的执行语句
3、IndentationError:unexpected indent 出现了不必要的缩进
4、
'''<file_sep>import os #操作系统接口
os.getcwd()
import glob #文件通配符
glob.glob('*.py')
import sys #命令行参数
print(sys.argv)
import re #字符串正则匹配
re.findall(r'\\bf[a-z]\*','which foot or hand fell fastest')
import math #数学
math.log(1024,2)
import random
random.choice(['apple','pear','banana'])
random.sample(range(100),10)
random.random()
random.randrange(6)
from urllib.request import urlopen #访问互联网
from datetime import date #访问时间
now=date.today()
print(now)<file_sep>#输入输出
'''
1、表达式语句和print()函数
2、str(),repr()
3、input()
'''''
str=input('请输入:')
print(str)
#os<file_sep>#存储数据
import json
'''
1、用模块json存储数据
2、json.dump()将内容保存到文件中去
3、json.load()将文件中的内容读取到内存中去
4、保存和读取用户生成的数据
'''
#重构
'''
'''
num=[1,2,3,4,5,6,7,8]
filename='number.json'
with open(filename,'w') as file_object:
json.dump(num,file_object)
with open(filename,'r') as file_object:
numbers=json.load(file_object)
print(numbers)<file_sep>#元组
"""
1、定义元组
2、修改元组,通过重新定义
"""
tuple1=(1,"liuying")
print(tuple1)<file_sep>#用户输入
'''
this is also simple,so that's just skip it.
'''
#while
'''
1、标志
2、break
3、continue
'''
'''
fine,it's also easy.
'''<file_sep>#字典
'''
1、动态结构,python不关心键值对的顺序,而只关心他们之间的关联
2、定义,添加,修改,删除
3、遍历字典 items(), keys(), values() set():屏蔽重复的
4、字典和列表的嵌套:字典列表,列表字典,字典中储存字典
'''
alien_0={'color':'yellow','speed':25}
alien_0['color']='red'
alien_0['x_position']=0
alien_0['y_positon']=25
alien_1={'color':'blue','x_position':10,'y_position':10}
alien_2={'color':'white','x_position':23,'y_position':45}
list=[alien_0,alien_1,alien_2]
print(alien_0)
del alien_0['color']
for key,value in alien_0.items():
print(key,end=':')
print(value)
print(list) | affc412c07962169bbfd442244d8a7520b757ddf | [
"Python"
] | 13 | Python | myrainbowliuying/Python | 6897ea454a2ba3c48a4c9f2701c2885c9f29d1a3 | 3c7b7a024b22cd304961825bdaa9b2bdb5555bbd |
refs/heads/master | <file_sep>/**
* Robotics
*
* MapDisplay.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef MAPDISPLAY_H_
#define MAPDISPLAY_H_
#include "Grid.h"
#include "Particle.h"
#include <string>
#include <vector>
#include <queue>
#include <HamsterAPIClientCPP/Hamster.h>
#include "Coordinate.h"
using namespace std;
using namespace HamsterAPI;
class MapDisplay
{
private:
Grid grid;
int startRow;
int startCol;
int goalRow;
int goalCol;
vector<vector<bool> > occupationMap;
int height;
int width;
vector<vector<int> > mapFromPlannedRoute;
cv::Mat_<cv::Vec3b> routeCvMat;
string plannedRoute;
vector<Coordinate> waypoints;
int numOfWaypoints;
void InitMapWithRoute();
void InitMapWithParticles(vector<Particle *> particles);
void ColorPixelByRoute(int currentCellValue, int i, int j);
void ColorPixelByParticles(int currentCellValue, int i, int j);
public:
MapDisplay(Grid * grid, string plannedRoute, vector<Coordinate> * waypoints, int numOfWaypoints);
Coordinate ConvertToHamsterCoordinate(Coordinate waypoint);
void PrintWaypoints();
void PrintRouteCvMat();
void PrintRouteCvMat(vector<Particle *> particles);
virtual ~MapDisplay();
};
#endif /* MAPDISPLAY_H_ */
<file_sep>/**
* Robotics
*
* MapDisplay.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "MapDisplay.h"
#include "Globals.h"
#define FREE_SPACE 0
#define OBSTACLE 1
#define START 2
#define PARTICLE 3
#define GOAL 4
#define TOP_PARTICLE 4
#define WAYPOINT 5
#define TOP_PARTICLES_NUM 5
#define BELIEF_LEVEL 0.5
MapDisplay::MapDisplay(Grid * grid, string plannedRoute, vector<Coordinate> * waypoints, int numOfWaypoints)
{
this->startRow = grid->GetGridStartCoordinate().y;
this->startCol = grid->GetGridStartCoordinate().x;
this->goalRow = grid->GetGridGoalCoordinate().y;
this->goalCol = grid->GetGridGoalCoordinate().x;
this->occupationMap = grid->GetInflatedMap();
this->height = grid->GetGridHeight();
this->width = grid->GetGridWidth();
this->plannedRoute = plannedRoute;
this->waypoints = *waypoints;
this->numOfWaypoints = numOfWaypoints;
}
// Convert coordinate from cv to hamster
Coordinate MapDisplay::ConvertToHamsterCoordinate(Coordinate waypoint)
{
Coordinate hamsterCoordinate =
{
.x = (waypoint.x - startCol),
.y = -(waypoint.y - startRow)
};
return hamsterCoordinate;
}
void MapDisplay::PrintRouteCvMat()
{
InitMapWithRoute();
//sleep(1);
cv::namedWindow("OccupancyGrid-view-route");
cv::imshow("OccupancyGrid-view-route", routeCvMat);
cv::waitKey(1);
}
void MapDisplay::PrintRouteCvMat(vector<Particle *> particles)
{
InitMapWithParticles(particles);
sleep(1);
cv::namedWindow("OccupancyGrid-view-particles");
cv::imshow("OccupancyGrid-view-particles", routeCvMat);
cv::waitKey(1);
}
void MapDisplay::InitMapWithRoute()
{
Coordinate start = { .x = startCol, .y = startRow };
mapFromPlannedRoute.resize(height);
for (int i = 0; i < height; i++)
{
mapFromPlannedRoute.at(i).resize(width);
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
(mapFromPlannedRoute.at(i)).at(j) = (occupationMap.at(i)).at(j);
}
}
// Follow the route on the map
if (plannedRoute.length() <= 0)
{
cout << "No route found";
cout << endl;
}
else
{
int currDirectionIndex;
int currWaypointIndex = 0;
char directionCharacter;
int chosenXDirection;
int chosenYDirection;
bool isWaypoint = false;
unsigned int x = start.x;
unsigned int y = start.y;
(mapFromPlannedRoute.at(y)).at(x) = START;
for (int i = 0; i < plannedRoute.length(); i++)
{
directionCharacter = plannedRoute.at(i);
currDirectionIndex = numericCharToInt(directionCharacter);
chosenXDirection = dirX[currDirectionIndex];
chosenYDirection = dirY[currDirectionIndex];
x += chosenXDirection;
y += chosenYDirection;
}
(mapFromPlannedRoute.at(y)).at(x) = GOAL;
// Iterate through all waypoints and mark them on the map
for (int i = 0; i < numOfWaypoints; i++)
{
Coordinate currWaypoint = waypoints.at(i);
int currCoordinate = (mapFromPlannedRoute.at(currWaypoint.y)).at(currWaypoint.x);
if (currCoordinate != START && currCoordinate != GOAL)
{
(mapFromPlannedRoute.at(currWaypoint.y)).at(currWaypoint.x) = WAYPOINT;
}
}
routeCvMat = cv::Mat(height, width, CV_8UC3, cv::Scalar::all(0));
// Initialize the map with the route
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int currentCellValue = (mapFromPlannedRoute.at(i)).at(j);
ColorPixelByRoute(currentCellValue, i, j);
}
}
}
}
void MapDisplay::InitMapWithParticles(vector<Particle *> particles)
{
Coordinate start = { .x = startCol, .y = startRow };
mapFromPlannedRoute.resize(height);
for (int i = 0; i < height; i++)
{
mapFromPlannedRoute.at(i).resize(width);
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
(mapFromPlannedRoute.at(i)).at(j) = (occupationMap.at(i)).at(j);
}
}
routeCvMat = cv::Mat(height, width, CV_8UC3, cv::Scalar::all(0));
for (int i = 0; i < particles.size(); i++)
{
Particle * currParticle = particles.at(i);
bool isTopParticle = i >= particles.size() - TOP_PARTICLES_NUM;
bool isTopBeliefParticle = isTopParticle /*&& currParticle->belief > BELIEF_LEVEL*/;
if (isTopBeliefParticle)
{
(mapFromPlannedRoute.at(currParticle->i)).at(currParticle->j) = TOP_PARTICLE;
}
else
{
(mapFromPlannedRoute.at(currParticle->i)).at(currParticle->j) = PARTICLE;
}
}
// Initialize the map with the particles
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int currentCellValue = (mapFromPlannedRoute.at(i)).at(j);
ColorPixelByParticles(currentCellValue, i, j);
}
}
}
void MapDisplay::ColorPixelByRoute(int currentCellValue, int i, int j)
{
switch(currentCellValue)
{
case(0):
{
// Color in white
routeCvMat.at<cv::Vec3b>(i, j)[0] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[0] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 255;
break;
}
case(OBSTACLE):
{
// Color in black
routeCvMat.at<cv::Vec3b>(i, j)[0] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 0;
break;
}
case(START):
{
// Color in blue
routeCvMat.at<cv::Vec3b>(i, j)[0] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 0;
break;
}
case(GOAL):
{
// Color in green
routeCvMat.at<cv::Vec3b>(i, j)[0] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 0;
break;
}
case(WAYPOINT):
{
// Color in yellow
routeCvMat.at<cv::Vec3b>(i, j)[0] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 255;
break;
}
default: // unknown
{
// Color in gray
routeCvMat.at<cv::Vec3b>(i, j)[0] = 128;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 128;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 128;
break;
}
}
}
void MapDisplay::ColorPixelByParticles(int currentCellValue, int i, int j)
{
switch(currentCellValue)
{
case(FREE_SPACE):
{
// Color in white
routeCvMat.at<cv::Vec3b>(i, j)[0] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[0] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 255;
break;
}
case(OBSTACLE):
{
// Color in black
routeCvMat.at<cv::Vec3b>(i, j)[0] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 0;
break;
}
case(PARTICLE):
{
// Color in red
routeCvMat.at<cv::Vec3b>(i, j)[0] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 255;
break;
}
case(TOP_PARTICLE):
{
// Color in green
routeCvMat.at<cv::Vec3b>(i, j)[0] = 0;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 255;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 0;
break;
}
default: // unknown
{
// Color in gray
routeCvMat.at<cv::Vec3b>(i, j)[0] = 128;
routeCvMat.at<cv::Vec3b>(i, j)[1] = 128;
routeCvMat.at<cv::Vec3b>(i, j)[2] = 128;
break;
}
}
}
MapDisplay::~MapDisplay()
{
/*cv::destroyWindow("OccupancyGrid-view-route");
cv::destroyWindow("OccupancyGrid-view-particles");*/
}
<file_sep>/**
* Robotics
*
* WaypointsManager.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "WaypointsManager.h"
#include "Globals.h"
#include <math.h>
#define NUMBER_OF_PARTICLES 1000
#define MAX_NUM_OF_WAYPOINTS 100
#define MAX_PIXEL_DIFF_BETWEEN_WAYPOINTS 10
int WayPointsManager::CalculateWaypoints(string plannedRoute, Coordinate startCoordinate, Coordinate goalCoordinate)
{
int numOfWaypoints = 0;
waypoints.resize(MAX_NUM_OF_WAYPOINTS);
// Check if any route was found
if (plannedRoute.length() <= 0)
{
return 0;
}
else
{
int movesInDirectionCounter = 0;
char directionCharacter = plannedRoute.at(0);
int currDirectionIndex = numericCharToInt(directionCharacter);
int prevDirectionIndex = numericCharToInt(directionCharacter);
int x = startCoordinate.x;
int y = startCoordinate.y;
// Run over all routes and create waypoints
for (int i = 0; i < plannedRoute.length(); i++)
{
directionCharacter = plannedRoute.at(i);
currDirectionIndex = numericCharToInt(directionCharacter);
bool isSameDirection =
currDirectionIndex == prevDirectionIndex &&
movesInDirectionCounter <= MAX_PIXEL_DIFF_BETWEEN_WAYPOINTS;
bool isNotWaypoint = movesInDirectionCounter == 0 || isSameDirection;
if (isNotWaypoint)
{
movesInDirectionCounter++;
}
else
{
// Create a new waypoint
waypoints.at(numOfWaypoints).x = x;
waypoints.at(numOfWaypoints).y = y;
prevDirectionIndex = currDirectionIndex;
movesInDirectionCounter = 0;
numOfWaypoints++;
}
x += dirX[currDirectionIndex];
y += dirY[currDirectionIndex];
}
}
waypoints.at(numOfWaypoints) = goalCoordinate;
return numOfWaypoints;
}
<file_sep>/**
* Robotics
*
* Grid.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "Grid.h"
// Ctor
Grid::Grid()
{
}
// Ctor
Grid::Grid(vector< vector<bool> > grid, double mapResolution,
double height, double width,
Coordinate start, Coordinate goal)
{
this->gridInflated = grid;
this->mapResolution = mapResolution;
this->gridHeight = height;
this->gridWidth = width;
this->startCoordinate = start;
this->goalCoordinate = goal;
}
int Grid::GetGridHeight() const
{
return gridHeight;
}
int Grid::GetGridWidth() const
{
return gridWidth;
}
vector< vector<bool> > Grid::GetInflatedMap() const
{
return gridInflated;
}
double Grid::GetMapResolution() const
{
return mapResolution;
}
Coordinate Grid::GetGridStartCoordinate() const
{
return startCoordinate;
}
Coordinate Grid::GetGridGoalCoordinate() const
{
return goalCoordinate;
}
Grid::~Grid()
{}
<file_sep>/**
* Robotics
*
* Map.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef MAP_H_
#define MAP_H_
#include "Grid.h"
#include <unistd.h>
#include <HamsterAPIClientCPP/Hamster.h>
using namespace std;
using namespace HamsterAPI;
class Map
{
private:
OccupancyGrid map;
double mapResolutionInCm; /* Each OccupancyGrid cell takes an area of mapResolutionInCm^2 centimeters */
cv::Mat originalCvMat;
cv::Mat inflatedCvMat;
int mapWidth;
int mapHeight;
int robotSizeInCm;
Coordinate startCoordinate;
Coordinate goalCoordinate;
void InitCvMatFromMap();
vector< vector<bool> > InflateOccupationMap();
void InitInflatedCvMat();
bool DoesCellHaveOccupiedNeighbor(int rowIndex, int colIndex);
public:
vector< vector<bool> > occupationMap;
Grid grid;
int inflationRadius;
Map();
Map(HamsterAPI::OccupancyGrid * map, int robotSizeInCm,
Coordinate startCoordinate, Coordinate goalCoordinate,
double mapHeight, double mapWidth);
virtual ~Map();
};
#endif /* MAP_H_ */
<file_sep>/**
* Robotics
*
* Robot.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "Robot.h"
Robot::Robot(
Hamster * hamster, LocalizationManager * localizationManager, int inflationRadius,
double mapHeight, double mapWidth)
{
this->hamster = hamster;
this->localizationManager = localizationManager;
this->inflationRadius = inflationRadius;
this->mapHeight = mapHeight;
this->mapWidth = mapWidth;
this->prevX = 0;
this->prevY = 0;
this->prevYaw = 0;
this->currX = 0;
this->currY = 0;
this->currYaw = 0;
}
void Robot::Init(Coordinate startCoordinate)
{
hamsterStartX = startCoordinate.x - (mapWidth / 2);
hamsterStartY = startCoordinate.y - (mapHeight / 2);
currX = hamsterStartX;
currY = hamsterStartY;
currYaw = startCoordinate.yaw;
Pose initialPose;
initialPose.setX(hamsterStartX);
initialPose.setY(hamsterStartY);
initialPose.setHeading(startCoordinate.yaw);
sleep(3);
hamster->setInitialPose(initialPose);
//localizationManager->InitParticles();
UpdateCoordinate();
}
double Robot::GetDeltaX() const
{
return currX - prevX;
}
double Robot::GetDeltaY() const
{
return currY - prevY;
}
double Robot::GetDeltaYaw() const
{
return currYaw - prevYaw;
}
Coordinate Robot::GetCurrHamsterCoordinate()
{
/*Particle * topParticle = localizationManager->GetTopParticle();
Coordinate currCoordinate;
currCoordinate = {
.x = topParticle->x + 2*inflationRadius,
.y = topParticle->y + 2*inflationRadius,
.yaw = topParticle->yaw
};*/
Pose currPose = hamster->getPose();
// Convert the coordinates
double currX = (currPose.getX() - hamsterStartX) * 10;
double currY = (currPose.getY() - hamsterStartY) * 10;
double currYaw = currPose.getHeading();
if (currYaw < 0)
{
currYaw += 360;
}
else if (currYaw > 360)
{
currYaw -= 360;
}
Coordinate currCoordinate = { .x = currX, .y = currY, .yaw = currYaw };
return currCoordinate;
}
void Robot::UpdateCoordinate()
{
prevX = currX;
prevY = currY;
prevYaw = currYaw;
Coordinate currentCoordinate = GetCurrHamsterCoordinate();
// Update the current and previous coordinates by the position of the robot
currX = currentCoordinate.x;
currY = currentCoordinate.y;
currYaw = currentCoordinate.yaw;
}
Robot::~Robot() {}
<file_sep>/**
* Robotics
*
* PathPlanner.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef PATHPLANNER_H_
#define PATHPLANNER_H_
#include "Grid.h"
#include "Node.h"
#include <string>
#include <vector>
#include <queue>
using namespace std;
struct NodePriorityComparer
{
bool operator()(const Node& nodeA, const Node& nodeB)
{
return nodeA.GetPriority() > nodeB.GetPriority();
}
};
// List of open nodes
static priority_queue<Node, vector<Node>, NodePriorityComparer> openNodesQueues[2];
class PathPlanner
{
private:
Grid grid;
int startRow;
int startCol;
int goalRow;
int goalCol;
vector< vector<bool> > occupationMap;
int height;
int width;
public:
string plannedRoute;
PathPlanner(const Grid * grid);
void PrintRouteCvMat();
string CalculateAStarRoute();
virtual ~PathPlanner();
};
#endif /* PATHPLANNER_H_ */
<file_sep>/**
* Robotics
*
* Node.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef NODE_H_
#define NODE_H_
#include "Coordinate.h"
class Node
{
private:
Coordinate currCoordinate;
int level;
int priority;
public:
Node();
Node(Coordinate currCoordinate, int level, int priority);
Coordinate GetCoordinate() const;
int GetLevel() const;
int GetPriority() const;
void CalculatePriority(const int & xDest, const int & yDest);
void CalculateLevel(const int & direction);
const int & GetHeuristicEstimate(const int & xDest, const int & yDest) const;
virtual ~Node();
};
#endif /* NODE_H_ */
<file_sep>/**
* Robotics
*
* Globals.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef GLOBALS_H_
#define GLOBALS_H_
#define ROBOT_SIZE_IN_CM 20
#define X_START 470
#define Y_START 470
#define YAW_START 0
#define X_GOAL 370
#define Y_GOAL 630
#define numericCharToInt(numChar) (numChar - '0')
// map of directions
const int dirNum = 8; // number of possible directions to go at any position
static int dirX[dirNum] = {1, 1, 0, -1, -1, -1, 0, 1};
static int dirY[dirNum] = {0, 1, 1, 1, 0, -1, -1, -1};
#endif /* GLOBALS_H_ */
<file_sep>/**
* Robotics
*
* ConfigurationManager.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef CONFIGURATIONMANAGER_H_
#define CONFIGURATIONMANAGER_H_
#include "Coordinate.h"
class ConfigurationManager
{
private:
double mapHeight, mapWidth;
public:
ConfigurationManager();
ConfigurationManager(double mapHeight, double mapWidth);
Coordinate GetStartCoordinate();
Coordinate GetGoalCoordinate();
int GetRobotRadiusInCm();
};
#endif /* CONFIGURATIONMANAGER_H_ */
<file_sep>/**
* Robotics
*
* LocalizationManager.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "LocalizationManager.h"
#include "math.h"
#include <iostream>
#include <algorithm>
#define NUM_OF_PARTICLES 350
#define BAD_BELIEF_PARTICLES 80
#define GOOD_BELIEF_PARTICLES 80
#define ADJACENT_PARTICLE_DESTINATION 1
#define PARTICLE_CORRECTION_MAX_RETRIES 20
LocalizationManager::LocalizationManager(
Hamster * hamster, OccupancyGrid & ogrid,
double mapHeight, double mapWidth, double mapResolution) :
hamster(hamster), ogrid(ogrid),
ogridHeight(mapHeight), ogridWidth(mapWidth), ogridResolution(mapResolution)
{}
void LocalizationManager::InitParticles()
{
particles.resize(NUM_OF_PARTICLES);
for (size_t i = 0; i < particles.size(); i++)
{
particles.at(i) = new Particle();
RandomizeParticle(particles.at(i));
}
}
vector<Particle *> LocalizationManager::GetParticles() const
{
return particles;
}
// Return rather the belief of x is greater than y's
bool ParticleCompare(Particle * x, Particle * y)
{
return (x->belief < y->belief);
}
Particle * LocalizationManager::GetTopParticle() const
{
return *(std::max_element(particles.begin(), particles.end(), ParticleCompare));
}
void LocalizationManager::ConvertFromMapCoordinateToMatIndex(Particle * particle)
{
particle->i = (double) ogridHeight / 2 - particle->y / ogridResolution;
particle->j = particle->x / ogridResolution + (double) ogridWidth / 2;
}
void LocalizationManager::ConvertFromMatIndexToMapCoordinate(Particle * particle)
{
particle->x = (particle->j - (double) ogridWidth / 2) * ogridResolution;
particle->y = ((double) ogridHeight / 2 - particle->i) * ogridResolution;
}
bool LocalizationManager::InsertParticleIntoMap(Particle * particle)
{
Particle * copyParticle = new Particle(*particle);
int distance, count = 0;
do
{
// Finds closest free cell to the out-of-range particle
distance = 10 - rand() % 20;
particle->j = copyParticle->j + distance;
distance = 10 - rand() % 20;
particle->i = copyParticle->i + distance;
count++;
} while (ogrid.getCell(particle->i, particle->j) != CELL_FREE && count < PARTICLE_CORRECTION_MAX_RETRIES);
// Convert indices to coordinate on map
ConvertFromMatIndexToMapCoordinate(particle);
delete copyParticle;
return count < PARTICLE_CORRECTION_MAX_RETRIES;
}
float LocalizationManager::CalculateBelief(Particle * particle)
{
LidarScan lidarScan = hamster->getLidarScan();
int corrects = 0;
int incorrects = 0;
for (int i = 0; i < lidarScan.getScanSize(); i++)
{
double angle = lidarScan.getScanAngleIncrement() * i * DEG2RAD;
if (lidarScan.getDistance(i) < lidarScan.getMaxRange() - 0.001)
{
// Calculate the obstacle's map coordinate
double obsX = particle->x + lidarScan.getDistance(i) * cos(angle + particle->yaw * DEG2RAD- 180 * DEG2RAD);
double obsY = particle->y + lidarScan.getDistance(i) * sin(angle + particle->yaw * DEG2RAD- 180 * DEG2RAD);
// Convert from map coordinate to matrix cell
int i = (double) ogridHeight / 2 - obsY / ogridResolution;
int j = obsX / ogridResolution + ogridWidth / 2;
// Determine if there was a hit according to the grid
if (ogrid.getCell(i, j) == CELL_OCCUPIED)
{
corrects++;
}
else
{
incorrects++;
}
}
}
return (float) corrects / (corrects + incorrects);
}
void LocalizationManager::UpdateParticles(double deltaX, double deltaY, double deltaYaw)
{
int size = particles.size();
for (size_t i = 0; i < particles.size(); i++)
{
Particle * currParticle = particles.at(i);
double r = sqrt(deltaX * deltaX + deltaY * deltaY);
currParticle->x += r * cos(currParticle->yaw * DEG2RAD);
currParticle->y += r * sin(currParticle->yaw * DEG2RAD);
// Modulo 360 calculation
currParticle->yaw += deltaYaw;
// Perform the modulu
if (currParticle->yaw >= 360)
{
currParticle->yaw = currParticle->yaw - 360;
}
if (currParticle->yaw < 0)
{
currParticle->yaw = currParticle->yaw + 360;
}
ConvertFromMapCoordinateToMatIndex(currParticle);
bool isSuccessfullyInserted = false;
// In case the particle goes outside the free area - try to get it back in
if (ogrid.getCell(currParticle->i, currParticle->j) != CELL_FREE)
{
int indexFromTop = size - rand() % GOOD_BELIEF_PARTICLES - 1;
if (currParticle->belief > 0.3)
{
// Try to get the particle back in
isSuccessfullyInserted = InsertParticleIntoMap(currParticle);
}
if (!isSuccessfullyInserted)
{
Particle * betterParticle = particles.at(indexFromTop);
if (betterParticle->belief > 0.4)
{
// Get the current particle closer to another particle which has greater belief
ImproveParticle(currParticle, betterParticle);
}
else
{
// If we don't have a better particle, randomize a new one.
RandomizeParticle(currParticle);
}
}
}
currParticle->belief = CalculateBelief(currParticle);
}
// Dump low-belief particles and change their coordinate to be close to high belief particles
std::sort(particles.begin(), particles.end(), ParticleCompare);
for (int i = 1; i <= BAD_BELIEF_PARTICLES; i++)
{
Particle * currParticle = particles.at(i - 1);
Particle * betterParticle = particles.at(size - i);
if (betterParticle->belief > 0.3)
{
ImproveParticle(currParticle, betterParticle);
CalculateBelief(currParticle);
}
else
{
RandomizeParticle(currParticle);
CalculateBelief(currParticle);
}
}
}
void LocalizationManager::PrintParticles() const
{
for (size_t i = 0; i < particles.size(); i++)
{
Particle * currParticle = particles.at(i);
cout << "Particle " << i << ": " <<
currParticle->x << "," <<
currParticle->y << "," <<
" yaw: " << currParticle->yaw << "," <<
" belief: " << currParticle->belief << endl;
}
}
void LocalizationManager::RandomizeParticle(Particle * particleToUpdate)
{
do
{
particleToUpdate->j = rand() % ogridWidth;
particleToUpdate->i = rand() % ogridHeight;
} while (ogrid.getCell(particleToUpdate->i, particleToUpdate->j) != CELL_FREE);
ConvertFromMatIndexToMapCoordinate(particleToUpdate);
// Randomize an angle
particleToUpdate->yaw = rand() % 360;
}
void LocalizationManager::ImproveParticle(Particle * particleToUpdate, Particle * betterParticle)
{
do
{
if (betterParticle->belief < 0.3)
{
particleToUpdate->x = betterParticle->x + 0.4 - 0.8*(double)rand()/(double)RAND_MAX;
particleToUpdate->y = betterParticle->y + 0.4 - 0.8*(double)rand()/(double)RAND_MAX;
}
else if (betterParticle->belief < 0.6)
{
particleToUpdate->x = betterParticle->x + 0.2 - 0.4*(double)rand()/(double)RAND_MAX;
particleToUpdate->y = betterParticle->y + 0.2 - 0.4*(double)rand()/(double)RAND_MAX;
}
else
{
particleToUpdate->x = betterParticle->x + 0.1 - 0.2*(double)rand()/(double)RAND_MAX;
particleToUpdate->y = betterParticle->y + 0.1 - 0.2*(double)rand()/(double)RAND_MAX;
}
ConvertFromMapCoordinateToMatIndex(particleToUpdate);
} while (ogrid.getCell(particleToUpdate->i, particleToUpdate->j) != CELL_FREE);
// Randomizing the angle according to the belief of the goodParticle
if (betterParticle->belief < 0.2)
{
particleToUpdate->yaw = (betterParticle->yaw + (180 - rand() % 360));
}
else if (betterParticle->belief < 0.4)
{
particleToUpdate->yaw = (betterParticle->yaw + (90 - rand() % 180));
}
else if (betterParticle->belief < 0.6)
{
particleToUpdate->yaw = (betterParticle->yaw + (30 - rand() % 60));
}
else if (betterParticle->belief < 0.8)
{
particleToUpdate->yaw = (betterParticle->yaw + (10 - rand() % 20));
}
else
{
particleToUpdate->yaw = (betterParticle->yaw + (5 - rand() % 10));
}
//Reducing degrees - modulo 360
particleToUpdate->yaw = (particleToUpdate->yaw >= 360) ?
particleToUpdate->yaw - 360 : particleToUpdate->yaw;
particleToUpdate->yaw = (particleToUpdate->yaw < 0) ?
particleToUpdate->yaw + 360 : particleToUpdate->yaw;
}
LocalizationManager::~LocalizationManager() {}
<file_sep>/**
* Robotics
*
* LocalizationManager.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef LOCALIZATIONMANAGER_H_
#define LOCALIZATIONMANAGER_H_
#include "Particle.h"
#include <vector>
#include <HamsterAPIClientCPP/Hamster.h>
using namespace std;
using namespace HamsterAPI;
class LocalizationManager
{
private:
vector<Particle *> particles;
const OccupancyGrid & ogrid;
int ogridHeight, ogridWidth;
double ogridResolution;
Hamster * hamster;
void ConvertFromMapCoordinateToMatIndex(Particle * particle);
void ConvertFromMatIndexToMapCoordinate(Particle * particle);
float CalculateBelief(Particle * particle);
bool InsertParticleIntoMap(Particle * particle);
void RandomizeParticle(Particle * particleToUpdate);
void ImproveParticle(Particle * particleToUpdate, Particle * betterParticle);
public:
LocalizationManager(
Hamster * hamster, OccupancyGrid & ogrid,
double mapHeight, double mapWidth, double mapResolution);
void InitParticles();
vector<Particle *> GetParticles() const;
Particle * GetTopParticle() const;
void UpdateParticles(double deltaX, double deltaY, double deltaYaw);
void PrintParticles() const;
virtual ~LocalizationManager();
};
#endif /* LOCALIZATIONMANAGER_H_ */
<file_sep>/**
* Robotics
*
* main.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "math.h"
#include "ConfigurationManager.h"
#include "PathPlanner.h"
#include "Map.h"
#include "MapDisplay.h"
#include "Navigator.h"
#include "WaypointsManager.h"
#include "Robot.h"
int main()
{
try
{
Hamster * hamster = new HamsterAPI::Hamster(1);
sleep(3);
OccupancyGrid occupancyGrid = hamster->getSLAMMap();
sleep(1);
double mapHeight = occupancyGrid.getHeight();
double mapWidth = occupancyGrid.getWidth();
double mapResolution = occupancyGrid.getResolution();
ConfigurationManager configurationManager(mapHeight, mapWidth);
Coordinate startCoordinate = configurationManager.GetStartCoordinate();
Coordinate goalCoordinate = configurationManager.GetGoalCoordinate();
int robotSize = configurationManager.GetRobotRadiusInCm();
Map map = Map(&occupancyGrid, robotSize, startCoordinate, goalCoordinate, mapHeight, mapWidth);
Grid grid = map.grid;
LocalizationManager localizationManager(hamster, occupancyGrid, mapHeight, mapWidth, mapResolution);
Robot robot(hamster, &localizationManager, map.inflationRadius, mapHeight, mapWidth);
PathPlanner pathPlanner = PathPlanner(&grid);
string plannedRoute = pathPlanner.plannedRoute;
WayPointsManager waypointsManager;
int numOfWaypoints = waypointsManager.CalculateWaypoints(plannedRoute, startCoordinate, goalCoordinate);
vector<Coordinate> waypoints = waypointsManager.waypoints;
// Create and display the map
MapDisplay mapDisplay = MapDisplay(&grid, plannedRoute, &waypoints, numOfWaypoints);
Navigator navigator(hamster, &robot, &mapDisplay);
robot.Init(startCoordinate);
Coordinate currCoordinate;
int waypointIndex = 0;
Coordinate currWaypoint, hamsterWaypoint;
double deltaX = 0, deltaY = 0, deltaYaw = 0;
while (hamster->isConnected())
{
try
{
while (waypointIndex < numOfWaypoints)
{
currCoordinate = robot.GetCurrHamsterCoordinate();
currWaypoint = waypoints.at(waypointIndex);
hamsterWaypoint = mapDisplay.ConvertToHamsterCoordinate(currWaypoint);
double distanceFromWaypoint =
sqrt(pow(currCoordinate.x - hamsterWaypoint.x, 2) +
pow(currCoordinate.y - hamsterWaypoint.y, 2));
bool isWaypointReached = distanceFromWaypoint <= DISTANCE_FROM_WAYPOINT_TOLERANCE;
if (!isWaypointReached)
{
navigator.NavigateToWaypoint(&hamsterWaypoint);
}
else
{
cout << endl <<
"Reached waypoint (" << hamsterWaypoint.x << ", " << hamsterWaypoint.y << ")" << endl;
}
waypointIndex++;
/*robot.UpdateCoordinate();
deltaX = robot.GetDeltaX();
deltaY = robot.GetDeltaY();
deltaYaw = robot.GetDeltaYaw();
cout << "Real values:" << " deltaX : " << deltaX << " deltaY: " << deltaY << " deltaYaw : " << deltaYaw << endl;
localizationManager.UpdateParticles(deltaX, deltaY, deltaYaw);
MapDisplay.PrintRouteCvMat(localizationManager.GetParticles());
localizationManager.PrintParticles();*/
}
navigator.Stop();
cout << "Hamster has reached its destination!" << endl;
return 0;
}
catch (const HamsterAPI::HamsterError & message_error)
{
HamsterAPI::Log::i("Client", message_error.what());
}
}
}
catch (const HamsterAPI::HamsterError & connection_error)
{
HamsterAPI::Log::i("Client", connection_error.what());
}
return 0;
}
<file_sep>/**
* Robotics
*
* PathPlanner.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "PathPlanner.h"
#include "Globals.h"
// Ctor
PathPlanner::PathPlanner(const Grid * grid)
{
this->startRow=grid->GetGridStartCoordinate().y;
this->startCol=grid->GetGridStartCoordinate().x;
this->goalRow=grid->GetGridGoalCoordinate().y;
this->goalCol=grid->GetGridGoalCoordinate().x;
this->occupationMap=grid->GetInflatedMap();
this->height=grid->GetGridHeight();
this->width=grid->GetGridWidth();
this->plannedRoute = CalculateAStarRoute();
}
string PathPlanner::CalculateAStarRoute()
{
vector<vector<int> > closed_nodes;
vector<vector<int> > open_nodes;
vector<vector<int> > path_directions;
static Node* nNodeA;
static Node* nNodeB;
static int smallerPQIndex;
static int dirIndex, cellIndex, rowIndex, colIndex;
static char c;
smallerPQIndex = 0;
closed_nodes.resize(height);
open_nodes.resize(height);
path_directions.resize(height);
// Resizing the vectors
for (int i = 0; i < height; i++)
{
(closed_nodes.at(i)).resize(width);
(open_nodes.at(i)).resize(width);
(path_directions.at(i)).resize(width);
}
// Initialize the cells in the maps
for (rowIndex = 0; rowIndex < height; rowIndex++)
{
for (colIndex = 0; colIndex < width; colIndex++)
{
(closed_nodes.at(rowIndex)).at(colIndex) = 0;
(open_nodes.at(rowIndex)).at(colIndex) = 0;
}
}
// Create the start node and push into list of open nodes
Coordinate startCoordinate = { .x = startCol, .y = startRow };
nNodeA = new Node(startCoordinate, 0, 0);
nNodeA->CalculatePriority(goalCol, goalRow);
(openNodesQueues[smallerPQIndex]).push(*nNodeA);
// Mark it on the open nodes map
rowIndex = nNodeA->GetCoordinate().y;
colIndex = nNodeA->GetCoordinate().x;
(open_nodes.at(rowIndex)).at(colIndex) = nNodeA->GetPriority();
// A* search
while (!(openNodesQueues[smallerPQIndex]).empty())
{
// Get the current node with the highest priority from the list of open nodes
Node highestPriorityNode = (openNodesQueues[smallerPQIndex]).top();
nNodeA = new Node(highestPriorityNode.GetCoordinate(),
highestPriorityNode.GetLevel(),
highestPriorityNode.GetPriority());
rowIndex = nNodeA->GetCoordinate().y;
colIndex = nNodeA->GetCoordinate().x;
// Remove the node from the open list
(openNodesQueues[smallerPQIndex]).pop();
(open_nodes.at(rowIndex)).at(colIndex) = 0;
// Mark it on the closed nodes map
(closed_nodes.at(rowIndex)).at(colIndex) = 1;
// Check if we reached to goal coordinate
bool isGoalCoordinateReached = rowIndex == goalRow && colIndex == goalCol;
if (isGoalCoordinateReached)
{
// Generate the path from finish to start by following the directions
string plannedRoute = "";
while (rowIndex != startRow || colIndex != startCol)
{
cellIndex = (path_directions.at(rowIndex)).at(colIndex);
c = '0' + (cellIndex + dirNum / 2) % dirNum;
plannedRoute = c + plannedRoute;
rowIndex += dirY[cellIndex];
colIndex += dirX[cellIndex];
}
// Delete node and all left nodes
delete nNodeA;
while (!(openNodesQueues[smallerPQIndex]).empty())
{
(openNodesQueues[smallerPQIndex]).pop();
}
return plannedRoute;
}
// Generate all possible moves
for (dirIndex = 0; dirIndex < dirNum; dirIndex++)
{
Coordinate coordinate = { .x = colIndex + dirX[dirIndex], .y = rowIndex + dirY[dirIndex] };
bool isCoordinateInBounds =
coordinate.x >= 0 && coordinate.x <= height - 1
&& coordinate.y >= 0 && coordinate.y <= width - 1;
bool isCellNotOccupied = (occupationMap.at(coordinate.y)).at(coordinate.x) != 1;
bool isNodeNotClosed = (closed_nodes.at(coordinate.y)).at(coordinate.x) != 1;
if (isCoordinateInBounds && isCellNotOccupied && isNodeNotClosed)
{
// Generate a child node
nNodeB = new Node(coordinate, nNodeA->GetLevel(), nNodeA->GetPriority());
nNodeB->CalculateLevel(dirIndex);
nNodeB->CalculatePriority(goalCol, goalRow);
// If the node isn't in the open list - add it
bool isNodeNotOpened = (open_nodes.at(coordinate.y)).at(coordinate.x) == 0;
if (isNodeNotOpened)
{
(open_nodes.at(coordinate.y)).at(coordinate.x) = nNodeB->GetPriority();
(openNodesQueues[smallerPQIndex]).push(*nNodeB);
// Mark its parent node direction
(path_directions.at(coordinate.y)).at(coordinate.x) =
(dirIndex + dirNum / 2) % dirNum;
}
else if ((open_nodes.at(coordinate.y)).at(coordinate.x) > nNodeB->GetPriority())
{
// Update the priority info
(open_nodes.at(coordinate.y)).at(coordinate.x) = nNodeB->GetPriority();
// Update the parent direction info
(path_directions.at(coordinate.y)).at(coordinate.x) =
(dirIndex + dirNum / 2) % dirNum;
/* Replace the node by emptying one priority queue to the other one,
except the node to be replaced and the new node */
while ((((Node) (openNodesQueues[smallerPQIndex].top())).GetCoordinate().x != coordinate.x) ||
(((Node) (openNodesQueues[smallerPQIndex].top())).GetCoordinate().y != coordinate.y))
{
Node topNode = (openNodesQueues[smallerPQIndex]).top();
(openNodesQueues[1 - smallerPQIndex]).push(topNode);
(openNodesQueues[smallerPQIndex]).pop();
}
// Remove the wanted node
(openNodesQueues[smallerPQIndex]).pop();
// Compare queues sizes
int firstQueueSize =
(openNodesQueues[smallerPQIndex]).size();
int secondQueueSize =
(openNodesQueues[1 - smallerPQIndex]).size();
if (firstQueueSize > secondQueueSize)
{
smallerPQIndex = 1 - smallerPQIndex;
}
// Empty the larger size priority queue to the smaller one
while (!openNodesQueues[smallerPQIndex].empty())
{
Node nodeToPush = openNodesQueues[smallerPQIndex].top();
(openNodesQueues[1 - smallerPQIndex]).push(nodeToPush);
(openNodesQueues[smallerPQIndex]).pop();
}
smallerPQIndex = 1 - smallerPQIndex;
// Insert the better node instead
(openNodesQueues[smallerPQIndex]).push(*nNodeB);
}
else
{
delete nNodeB;
}
}
}
delete nNodeA;
}
// No route found
return "";
}
PathPlanner::~PathPlanner()
{}
<file_sep>/**
* Robotics
*
* Node.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "Node.h"
#include <math.h>
using namespace std;
Node::Node()
{
Coordinate coordinate = { .x = 0, .y = 0 };
this->currCoordinate = coordinate;
this->level = 0;
this->priority = 0;
}
Node::Node(Coordinate currCoordinate, int level, int priority)
{
this->currCoordinate = currCoordinate;
this->level = level;
this->priority = priority;
}
Coordinate Node::GetCoordinate() const
{
return currCoordinate;
}
int Node::GetLevel() const
{
return level;
}
int Node::GetPriority() const
{
return priority;
}
void Node::CalculatePriority(const int & xDest, const int & yDest)
{
priority = level + GetHeuristicEstimate(xDest, yDest) * 10;
}
// Set the level according to the next move
void Node::CalculateLevel(const int & direction)
{
if (direction % 2 == 0)
{
level += 10;
}
else
{
level += 14;
}
}
// Heuristic estimation function for the remaining distance to the goal
const int & Node::GetHeuristicEstimate(const int & xDest, const int & yDest) const
{
static int xd, yd, distance;
xd = xDest - currCoordinate.x;
yd = yDest - currCoordinate.y;
distance = static_cast<int>(sqrt(xd * xd + yd * yd));
return (distance);
}
Node::~Node() {}
<file_sep>/**
* Robotics
*
* Navigator.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef NAVIGATOR_H_
#define NAVIGATOR_H_
#include "Robot.h"
#include "HamsterAPIClientCPP/Hamster.h"
#include <vector>
#include "Coordinate.h"
#include "MapDisplay.h"
using namespace std;
using namespace HamsterAPI;
#define DISTANCE_FROM_WAYPOINT_TOLERANCE 5
class Navigator
{
private:
HamsterAPI::Hamster * hamster;
Robot * robot;
Coordinate currCoordinate;
Coordinate prevCoordinate;
Coordinate * waypoint;
double distanceFromWaypoint, prevDistanceFromWaypoint;
double currYaw, destYaw, currDeltaYaw;
double turnSpeed, moveSpeed;
string chosenDirectionName;
clock_t navigationStartTime;
float wheelsAngle;
bool coordinateChanged;
MapDisplay * mapDisplay;
void TurnToWaypoint();
void MoveToWaypoint();
double GetAdjustedYaw(double yawToAdjust) const;
void RecalculateTurningDirection();
void RecalculateDistanceFromWaypoint();
void CalculateTurnSpeedByDeltaYaw();
void CalculateSpeedByDistanceFromWaypoint();
void PrintBeforeTurning();
void PrintAfterTurning();
void PrintAfterMoving();
void PrintAfterWaypointIsReached();
public:
Navigator(HamsterAPI::Hamster * hamster, Robot * robot, MapDisplay * MapDisplay);
void NavigateToWaypoint(Coordinate * waypoint);
void Stop() ;
virtual ~Navigator();
};
#endif /* NAVIGATOR_H_ */
<file_sep>/**
* Robotics
*
* Robot.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef ROBOT_H_
#define ROBOT_H_
#include "LocalizationManager.h"
#include <HamsterAPIClientCPP/Hamster.h>
#include "Coordinate.h"
using namespace HamsterAPI;
class Robot
{
private:
Hamster * hamster;
double hamsterStartX, hamsterStartY;
LocalizationManager * localizationManager;
double prevX, prevY, prevYaw, currX, currY, currYaw;
int inflationRadius;
double mapHeight, mapWidth;
public:
Robot(Hamster * hamster, LocalizationManager * localizationManager, int inflationRadius, double mapHeight, double mapWidth);
void Init(Coordinate startCoordinate);
Coordinate GetCurrHamsterCoordinate();
double GetDeltaX() const;
double GetDeltaY() const;
double GetDeltaYaw() const;
void UpdateCoordinate();
virtual ~Robot();
};
#endif /* ROBOT_H_ */
<file_sep>/**
* Robotics
*
* Particle.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef PARTICLE_H_
#define PARTICLE_H_
#include <vector>
#include "Coordinate.h"
using namespace std;
class Particle
{
public:
int i, j;
double x, y, yaw, belief;
Particle();
Particle(double posX, double posY, double yaw);
Coordinate GetCoordinate();
~Particle();
};
#endif /* PARTICLE_H_ */
<file_sep>/**
* Robotics
*
* ConfigurationManager.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "ConfigurationManager.h"
#include "Globals.h"
// Ctor
ConfigurationManager::ConfigurationManager(double mapHeight, double mapWidth)
{
this->mapHeight = mapHeight;
this->mapWidth = mapWidth;
}
Coordinate ConfigurationManager::GetStartCoordinate()
{
Coordinate startCoordinate =
{
.x = X_START,
.y = Y_START,
.yaw = YAW_START
};
return startCoordinate;
}
Coordinate ConfigurationManager::GetGoalCoordinate()
{
Coordinate goalCoordinate =
{
.x = X_GOAL,
.y = Y_GOAL
};
return goalCoordinate;
}
int ConfigurationManager::GetRobotRadiusInCm()
{
return ROBOT_SIZE_IN_CM;
}
<file_sep>/**
* Robotics
*
* Grid.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef GRID_H_
#define GRID_H_
#include <vector>
#include "Coordinate.h"
using namespace std;
class Grid
{
private:
double mapResolution;
vector<vector<bool> > gridInflated;
int gridWidth;
int gridHeight;
Coordinate startCoordinate;
Coordinate goalCoordinate;
public:
Grid();
Grid(vector< vector<bool> > grid, double mapResolution, double height, double width, Coordinate start, Coordinate goal);
int GetGridHeight() const;
int GetGridWidth() const;
vector< vector<bool> > GetInflatedMap() const;
double GetMapResolution() const;
Coordinate GetGridStartCoordinate() const;
Coordinate GetGridGoalCoordinate() const;
virtual ~Grid();
};
#endif /* GRID_H_ */
<file_sep>/**
* Robotics
*
* Coordinate.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef COORDINATE_H_
#define COORDINATE_H_
struct Coordinate
{
double x;
double y;
double yaw;
};
#endif /* COORDINATE_H_ */
<file_sep>/**
* Robotics
*
* WaypointsManager.h
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#ifndef WAYPOINTSMANAGER_H_
#define WAYPOINTSMANAGER_H_
#include <string>
#include <vector>
#include "Coordinate.h"
using namespace std;
class WayPointsManager
{
public:
vector<Coordinate> waypoints;
int CalculateWaypoints(string plannedRoute, Coordinate startCoordinate, Coordinate goalCoordinate);
};
#endif /* WAYPOINTSMANAGER_H_ */
<file_sep>/**
* Robotics
*
* Navigator.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "Navigator.h"
#include "Globals.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sstream>
#define MAP_ANGLE -30
#define MAX_MOVE_SPEED 0.4
#define MIN_TURN_SPEED 0.1
#define MAX_TURN_SPEED 0.2
#define YAW_TOLERANCE 1.05
#define NAVIGATION_TIMEOUT_IN_SECONDS 15
#define TURN_ANGLE 45.0
#define leftTurnAngle() TURN_ANGLE
#define rightTurnAngle() -TURN_ANGLE
#define radiansToDegrees(angleRadians) (angleRadians * 180.0 / M_PI)
Navigator::Navigator(HamsterAPI::Hamster * hamster, Robot * robot, MapDisplay * mapDisplay)
{
this->hamster = hamster;
this->robot = robot;
this->mapDisplay = mapDisplay;
}
void Navigator::Stop()
{
hamster->sendSpeed(0.0, 0.0);
}
void Navigator::NavigateToWaypoint(Coordinate * waypoint)
{
this->waypoint = waypoint;
double destYawInRad = atan2((waypoint->y - currCoordinate.y),(waypoint->x - currCoordinate.x));
double destYawInDegrees = radiansToDegrees(destYawInRad) + MAP_ANGLE;
destYaw = GetAdjustedYaw(destYawInDegrees);
RecalculateDistanceFromWaypoint();
RecalculateTurningDirection();
coordinateChanged = true;
bool isWaypointReached = false;
navigationStartTime = clock();
while (!isWaypointReached)
{
currCoordinate = robot->GetCurrHamsterCoordinate();
currYaw = currCoordinate.yaw;
currDeltaYaw = fabs(destYaw - currYaw);
if (currDeltaYaw > YAW_TOLERANCE)
{
bool isStuck = ((clock() - navigationStartTime) / CLOCKS_PER_SEC) >= NAVIGATION_TIMEOUT_IN_SECONDS;
if (!isStuck)
{
// Keep turning in the chosen direction
RecalculateTurningDirection();
TurnToWaypoint();
}
else
{
cout << "Moving Backwards" << endl;
// Move backwards trying to avoid the obstacle that the robot got stuck in
for (int i = 0; i < 1000000; i++)
{
hamster->sendSpeed(-0.1, 0.0);
}
navigationStartTime = clock();
}
}
else
{
// Keep moving in the chosen direction
cout << "Reached destination yaw, moving forward towards waypoint" << endl;
MoveToWaypoint();
}
RecalculateDistanceFromWaypoint();
mapDisplay->PrintRouteCvMat();
isWaypointReached = distanceFromWaypoint <= DISTANCE_FROM_WAYPOINT_TOLERANCE;
}
PrintAfterWaypointIsReached();
Stop();
return;
}
void Navigator::TurnToWaypoint()
{
CalculateTurnSpeedByDeltaYaw();
hamster->sendSpeed(turnSpeed, wheelsAngle);
prevCoordinate = currCoordinate;
currCoordinate = robot->GetCurrHamsterCoordinate();
currYaw = currCoordinate.yaw;
coordinateChanged =
prevCoordinate.x != currCoordinate.x &&
prevCoordinate.y != currCoordinate.y &&
prevCoordinate.yaw != currCoordinate.yaw;
if (coordinateChanged)
{
chosenDirectionName = wheelsAngle > 0 ? "Left" : "Right";
PrintAfterTurning();
}
}
void Navigator::MoveToWaypoint()
{
CalculateSpeedByDistanceFromWaypoint();
hamster->sendSpeed(moveSpeed, 0.0);
currCoordinate = robot->GetCurrHamsterCoordinate();
prevDistanceFromWaypoint = distanceFromWaypoint;
RecalculateDistanceFromWaypoint();
coordinateChanged = prevDistanceFromWaypoint != distanceFromWaypoint;
if (coordinateChanged)
{
chosenDirectionName = "Forward";
PrintAfterMoving();
}
}
void Navigator::RecalculateTurningDirection()
{
currCoordinate = robot->GetCurrHamsterCoordinate();
currYaw = currCoordinate.yaw;
currDeltaYaw = fabs(destYaw - currYaw);
if (currYaw > destYaw)
{
if (360 - currYaw + destYaw < currYaw - destYaw)
{
wheelsAngle = leftTurnAngle();
}
else
{
wheelsAngle = rightTurnAngle();
}
}
else
{
if (360 - destYaw + currYaw < destYaw - currYaw)
{
wheelsAngle = rightTurnAngle();
}
else
{
wheelsAngle = leftTurnAngle();
}
}
}
double Navigator::GetAdjustedYaw(double yawToAdjust) const
{
if (yawToAdjust < 0)
{
return yawToAdjust + 360;
}
if (yawToAdjust > 360)
{
return yawToAdjust - 360;
}
}
void Navigator::RecalculateDistanceFromWaypoint()
{
currCoordinate = robot->GetCurrHamsterCoordinate();
distanceFromWaypoint =
sqrt(pow(currCoordinate.x - waypoint->x, 2) +
pow(currCoordinate.y - waypoint->y, 2));
}
// Calculate the turn speed in order not to miss the destination yaw
void Navigator::CalculateTurnSpeedByDeltaYaw()
{
int numOfSpeedClasses = 5;
double diffConst = 2 * ((double)(MAX_TURN_SPEED - MIN_TURN_SPEED) / (numOfSpeedClasses - 1));
double classSize = (double)360.0 / numOfSpeedClasses;
double divisionResult = (double)currDeltaYaw / classSize;
// Varies from (0) to (numOfSpeedClasses - 1)
int speedClassIndex = floor(divisionResult);
if (speedClassIndex > ((int)(numOfSpeedClasses / 2)))
{
turnSpeed = MIN_TURN_SPEED + (numOfSpeedClasses - speedClassIndex) * diffConst;
}
else
{
turnSpeed = MIN_TURN_SPEED + speedClassIndex * diffConst;
}
}
// Calculate the move speed as it approached the waypoint in order not to miss it
void Navigator::CalculateSpeedByDistanceFromWaypoint()
{
if (distanceFromWaypoint > 5 * DISTANCE_FROM_WAYPOINT_TOLERANCE)
{
moveSpeed = MAX_MOVE_SPEED;
}
moveSpeed = (double)distanceFromWaypoint / 30;
}
void Navigator::PrintBeforeTurning()
{
cout << "Preparing to turn..." << endl <<
"current coordinate: " <<
"x = " << currCoordinate.x <<
", y = " << currCoordinate.y <<
", yaw = " << currYaw << endl <<
"current waypoint: " <<
"x = " << waypoint->x <<
", y = " << waypoint->y << endl <<
"destYaw: " << destYaw << endl;
}
void Navigator::PrintAfterTurning()
{
cout << "Turned " << chosenDirectionName << " to: " <<
"x = " << currCoordinate.x <<
", y = " << currCoordinate.y <<
", yaw = " << currYaw <<
", deltaYaw = " << currDeltaYaw <<
" (turnSpeed: " << turnSpeed << ")" << endl;
}
void Navigator::PrintAfterMoving()
{
cout << "Moved " << chosenDirectionName << " to: " <<
"x = " << currCoordinate.x <<
", y = " << currCoordinate.y <<
", yaw = " << currYaw <<
", distanceFromWaypoint = " << distanceFromWaypoint <<
" (moveSpeed: " << moveSpeed << ")" << endl;
}
void Navigator::PrintAfterWaypointIsReached()
{
cout << endl <<
"Reached waypoint (" << waypoint->x << ", " << waypoint->y << ")" << endl <<
"current coordinate: " <<
"x = " << currCoordinate.x <<
", y = " << currCoordinate.y <<
", yaw = " << currCoordinate.yaw << endl << endl;
}
Navigator::~Navigator() {}
<file_sep>/**
* Robotics
*
* Particle.cpp
*
* Students:
* <NAME> - 308417823
* <NAME> - 313522039
* <NAME> - 311123327
*
* 22.8.17
*/
#include "Particle.h"
#include <math.h>
// Ctor
Particle::Particle()
{}
// Ctor
Particle::Particle(double posX, double posY, double yaw)
{
this->x = posX;
this->y = posY;
this->yaw = yaw;
}
Coordinate Particle::GetCoordinate()
{
Coordinate coordinate = { .x = x, .y = y, .yaw = yaw };
return coordinate;
}
Particle::~Particle() {}
| 0e040a4f89f6c789d0413f09f4c40a8334ade9f3 | [
"C",
"C++"
] | 24 | C++ | jonBerg24/roboProj | 2249923fe1c19b8e19403d241367eb429ed1299f | c8f0282d032576190a33f3c726d93dc4777e6965 |
refs/heads/master | <file_sep>set :postgresql_version do
moonshine_yml[:postgresql][:version] || '9.0'
end
namespace :postgresql do
task :version do
puts postgresql_version
end
namespace :replication do
task :public_keys, :roles => :db do
sudo "cat /var/lib/postgresql/.ssh/id_rsa.pub", :as => 'postgres'
end
namespace :status do
task :default, :roles => :db do
tail
current_xlog_location
last_xlog_receive_location
end
task :tail, :roles => :db do
sudo %Q{tail /var/log/postgresql/postgresql-#{postgresql_version}-main.log}
end
task :current_xlog_location, :roles => :db, :only => {:primary => true} do
sudo %Q{psql -c 'SELECT pg_current_xlog_location()'}, :as => 'postgres'
end
task :last_xlog_receive_location, :roles => :db, :only => {:standby => true} do
sudo %Q{psql -c 'SELECT pg_last_xlog_receive_location()'}, :as => 'postgres'
end
end
namespace :setup do
task :wal_archiving_status, :roles => :db, :only => {:primary => true} do
sudo %Q{psql -c 'show archive_mode'}, :as => 'postgres'
sudo %Q{ps aux | grep "wal writer" | grep -v grep}
end
task :default do
take_snapshot_from_primary
copy_snapshot_from_primary_to_standby
apply_snapshot_to_standby
end
task :take_snapshot_from_primary, :roles => :db, :only => {:primary => true} do
sudo %Q{psql -c "SELECT pg_start_backup('base_backup')"}, :as => 'postgres'
sudo %Q{tar -C /var/lib/postgresql/#{postgresql_version}/main --exclude postmaster.pid -czvf /tmp/main.tar.gz ./}, :as => 'postgres'
# FIXME this command usually hangs forever with output like:
# ** [out :: server] NOTICE: pg_stop_backup cleanup done, waiting for required WAL segments to be archived
# ** [out :: server] WARNING: pg_stop_backup still waiting for all required WAL segments to be archived (60 seconds elapsed)
# ** [out :: server] HINT: Check that your archive_command is executing properly. pg_stop_backup can be cancelled safely, but the database backup will not be usable without all the WAL segments.
sudo %Q{psql -c "SELECT pg_stop_backup()"}, :as => 'postgres'
end
task :copy_snapshot_from_primary_to_standby do
run_locally "mkdir -p tmp"
get "/tmp/main.tar.gz", "tmp/main.tar.gz", :roles => :db, :only => {:primary => true}
upload "tmp/main.tar.gz", "/tmp/main.tar.gz", :roles => :db, :only => {:standby => true}
end
task :apply_snapshot_to_standby, :roles => :db, :only => {:standby => true} do
sudo "service postgresql stop"
sudo "rm -rf /var/lib/postgresql/#{postgresql_version}/main.old", :as => 'postgres'
sudo "mv /var/lib/postgresql/#{postgresql_version}/main /var/lib/postgresql/#{postgresql_version}/main.old", :as => 'postgres'
sudo "mkdir -p /var/lib/postgresql/#{postgresql_version}/main", :as => 'postgres'
sudo "chmod 700 /var/lib/postgresql/#{postgresql_version}/main", :as => 'postgres'
sudo "tar -C /var/lib/postgresql/#{postgresql_version}/main -xzf /tmp/main.tar.gz", :as => 'postgres'
sudo "ln -s /var/lib/postgresql/recovery.conf /var/lib/postgresql/#{postgresql_version}/main/recovery.conf", :as => 'postgres'
sudo "id", :as => 'postgres'
sudo "service postgresql start"
end
task :cleanup, :roles => :db do
run_locally "rm -f tmp/main.tar.gz"
sudo "rm -f /tmp/main.tar.gz"
end
end
end
end
<file_sep>#!/usr/bin/env bash
# Script for semi-automated promotion of a standby server to
# being a master server, including making sure the other master
# is down.
#
# ***********************************
# * WARNING: this script may not be appropriate for your particular use case;
# * different organizations may desire different logic for their respective
# * failover scenarios. Please consider your requirements when using or
# * adapting this script.
# ***********************************
# Version 1.6. Last updated 2011-02-17.
# Copyright (c) 2010-2011, PostgreSQL, Experts, Inc.
# Licensed under The PostgreSQL License; see
# http://www.postgresql.org/about/licence
# or the end of this file for details.
# grab the current config variables
CONF_FILE=/var/lib/postgresql/scripts/pitr-replication.conf
. ${CONF_FILE}
function restart_postgresql_on_master
{
echo "Attempting to restart postgresql on ${MASTER}."
if [ $OS = 'Joyent' ] && [ $USE_SVCADM ]; then
${SSH} ${SSH_OPT} ${MASTER} "/usr/sbin/svcadm disable postgresql:pg90" \
&& ${SSH} ${SSH_OPT} ${MASTER} "/usr/sbin/svcadm enable postgresql:pg90"
else
${SSH} ${SSH_OPT} ${MASTER} "${PGCTL} -l ${PGDATA}/../pgstartup.log -w -D $(dirname ${PGCONFFILE}) start"
fi
if [ $? -ne 0 ]; then
echo "Restart postgresql on ${MASTER} failed!"
echo "${MASTER} should be the master again, but"
echo "starting the postgresql service failed."
echo "Please inspect."
exit 2
else
echo "Postgresql successfully restarted on ${MASTER}."
echo "${MASTER} should still be the master."
echo "Please verify functionality."
fi
}
function reset_conf_on_replica
{
echo "Attempting to reset ${CONF_FILE} changes on ${REPLICA}"
sed -e "s/MASTER=${REPLICA}/MASTER=${MASTER}/" -e " s/REPLICA=${MASTER}/REPLICA=${REPLICA}/" ${CONF_FILE} > ${CONF_FILE}.swap && mv ${CONF_FILE}.swap ${CONF_FILE}
export ROLLBACK_EXIT_CODE = $?
if [ $ROLLBACK_EXIT_CODE -ne 0 ]; then
echo "Unable to rollback ${CONF_FILE} changes on ${REPLICA}"
else
mv ${CONF_FILE}.swap ${CONF_FILE}
echo "Config file changes successfully rolled back on ${REPLICA}"
sed "s/host=[0123456789.]*/host=${MASTER}/" $(dirname ${CONF_FILE})/recovery.conf > ${RECOVERYCONFDIR}/recovery.conf
fi
}
function reset_conf
{
echo "Attempting to reset config file changes on ${MASTER}"
${SSH} ${SSH_OPT} ${MASTER} /bin/sh -c "'sed -e \"s/MASTER=${REPLICA}/MASTER=${MASTER}/\" -e \"s/REPLICA=${MASTER}/REPLICA=${REPLICA}/\" ${CONF_FILE} > ${CONF_FILE}.swap && mv ${CONF_FILE}.swap ${CONF_FILE}'"
if [ $? -ne 0 ]; then
echo "Unable to rollback config file changes on ${MASTER}"
else
echo "Config file changes successfully rolled back on ${MASTER}"
${SSH} ${SSH_OPT} ${MASTER} "[ -f ${RECOVERYCONFDIR}/recovery.conf ] && rm -f ${RECOVERYCONFDIR}/recovery.conf"
reset_conf_on_replica
restart_postgresql_on_master
exit 1
fi
}
# Don't resync by default
DONT_RESYNC=1
# Get the command line options
TEMP=$(getopt -o "hr" --long help,resync -n "$0" -- "$@")
eval set -- "$TEMP"
while true ; do
case "$1" in
-h|--help) help=1 ; shift ;;
# Note: even if we set --resync here, it's
# possible to be overriden by errors later.
-r|--resync) unset DONT_RESYNC ; shift ;;
# \`$2' necessary evil
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
# Let's make sure we're running as the postgres OS user,
# this is the replica and we haven't been brought up already
if [ "$(id -un)" != "postgres" ]; then
echo "This script must be run as the postgres user."
exit 1
fi
# check if this is the master already because this script should only be run on
# the slave
if [ $OS = 'Joyent' ]; then
if ifconfig -a | grep inet ${MASTER} > /dev/null 2>&1; then
THIS_IS_MASTER=yes
fi
elif /sbin/ip addr | grep "inet ${MASTER}" > /dev/null 2>&1; then
THIS_IS_MASTER=yes
fi
if [ $THIS_IS_MASTER ]; then
echo "This is already the master, no need to promote. If you wanted to promote the current slave, please execute the script on that server."
exit 1
fi
# Is there already a promotion in progress?
if [ -f ${BRINGUP} ]; then
echo "${BRINGUP} file already exists!"
echo "Possible promotion in progress. Aborting."
echo "${MASTER} is still the master."
exit 1
fi
# Let's make sure we're standing by before we try to bring up the server
# First we check for the recovery.conf
if [ ! -f "${RECOVERYCONFDIR}/recovery.conf" ]; then
echo "${RECOVERYCONFDIR}/recovery.conf does not exist. ${REPLICA} not standing by. Aborting."
exit 1
fi
# Verify we can connect to the standby and it is in recovery
ISINRECOVERY=$(${PSQL} -Atc "SELECT pg_is_in_recovery()" -U ${PGUSER} postgres)
if [ $? -eq 0 ]; then
if [ ${ISINRECOVERY} != "t" ]; then
echo "${REPLICA} is not standing by. Aborting."
echo "${MASTER} is still the master."
exit 1
fi
else
echo "Could not connect to psql server on ${REPLICA}. Aborting."
echo "${MASTER} is still the master."
exit 1
fi
# Looks like the standby is good. Time to get to work.
# request the current master to switch xlog files so we're
# as up to date as possible
echo 'Requesting the master switch xlog files'
${PSQL} -c "SELECT pg_switch_xlog();" -h ${MASTER} -U ${PGUSER} postgres > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo "Unable to establish psql connection with current master."
PSQLMASTERFAIL=1
fi
# verify ssh connectivity to the current master
${SSH} ${SSH_OPT} ${MASTER} "/bin/true"
if [ $? -ne 0 ]; then
if [ -z "${PSQLMASTERFAIL}" ]; then
echo "Unable to establish SSH connection to ${MASTER}"
echo "but, psql connection succeeded."
echo "Please remedy or proceed with manual switchover."
echo "${MASTER} is still the master."
exit 1
fi
# We couldn't SSH to it, can we ping it?
if ping -q -c 1 ${MASTER} > /dev/null; then
echo "Unable to SSH or psql to ${MASTER}; however"
echo "ping reveals that the server is up."
echo "Aborting promotion. Please fix or proceed"
echo "with manual failover process."
exit 1
else
MASTERDOWN=1
fi
fi
# Are the services running on the master?
if [ -z "${MASTERDOWN}" ]; then
${SSH} ${SSH_OPT} ${MASTER} "head -1 ${PGDATA}/postmaster.pid 2> /dev/null | xargs ps -fp > /dev/null 2>&1"
if [ $? -ne 0 ]; then
echo "PostgreSQL service down on ${MASTER}"
MASTERDOWN=1
fi
fi
if [ -z "${MASTERDOWN}" ]; then
echo "Attempting to stop PostgreSQL service on ${MASTER}"
# shut down postgresql on the current master
if [ $OS = 'Joyent' ] && [ $USE_SVCADM ]; then
${SSH} ${SSH_OPT} ${MASTER} "/usr/sbin/svcadm disable postgresql:pg90"
else
${SSH} ${SSH_OPT} ${MASTER} "${PGCTL} -w -m fast -D ${PGDATA} ${PGCTLOPTIONS} stop"
fi
if [ $? -ne 0 ]; then
echo "Failed to stop postgresql on master: ${MASTER}."
echo "Please inspect the logs and proceed with manual switchover."
echo "${MASTER} is still the master but may be in the process of shutting down."
exit 1
fi
# Change the MASTER and REPLICA values in the conf file on the old MASTER
${SSH} ${SSH_OPT} ${MASTER} /bin/sh -c "'sed -e \"s/MASTER=${MASTER}/MASTER=${REPLICA}/\" -e \"s/REPLICA=${REPLICA}/REPLICA=${MASTER}/\" ${CONF_FILE} > ${CONF_FILE}.swap && mv ${CONF_FILE}.swap ${CONF_FILE}'"
if [ $? -ne 0 ]; then
echo "Failed to update ${CONF_FILE} on ${MASTER}."
# Attempt to restart the master's postgresql
restart_postgresql_on_master
exit 1
fi
fi
# Change the MASTER and REPLICA values in the conf file on the old REPLICA
sed -e "s/MASTER=${MASTER}/MASTER=${REPLICA}/" -e "s/REPLICA=${REPLICA}/REPLICA=${MASTER}/" ${CONF_FILE} > ${CONF_FILE}.swap && mv ${CONF_FILE}.swap ${CONF_FILE}
if [ $? -ne 0 ]; then
echo "Failed to update ${CONF_FILE} on ${REPLICA}."
# Try to put the conf file back as it was and restart
# postgresql service
reset_conf
exit 1
fi
echo "Bringing up PostgreSQL on ${REPLICA} as the master."
# Bring up the new master
touch ${BRINGUP}
if [ $? -ne 0 ]; then
# We had a problem creating the BRINGUP file, let's see if it exists or not
if [ -f ${BRINGUP} ]; then
echo "${BRINGUP} exists, but touch reported an error. Attempting to continue."
else
echo "Unable to create ${BRINGUP}; please check permissions on $(dirname ${BRINGUP})."
# Try to put the conf file back as it was and restart
# postgresql service
reset_conf
exit 1
fi
fi
# remove the no-archiving file on the old replica
if [ -f ${NOARCHIVEFILE} ]; then
rm -f ${NOARCHIVEFILE}
if [ $? -ne 0 ]; then
echo "Unable to rm ${NOARCHIVEFILE}, please check permissions and complete promotion manually."
DONT_RESYNC=1
fi
fi
if [ -z "${MASTERDOWN}" ]; then
# create the no-archiving file on the old master
${SSH} ${SSH_OPT} ${MASTER} "touch ${NOARCHIVEFILE}"
if [ $? -ne 0 ]; then
echo "Unable to touch ${NOARCHIVEFILE}, please check permissions, create ${NOARCHIVEFILE}, then resync the new replica manually."
DONT_RESYNC=1
fi
# create the recovery.conf file on the old master
${SSH} ${SSH_OPT} ${MASTER} "sed 's/host=[0123456789.]*/host=${REPLICA}/' $(dirname ${CONF_FILE})/recovery.conf > ${RECOVERYCONFDIR}/recovery.conf"
if [ $? -ne 0 ]; then
echo "Unable to create the ${RECOVERYCONFDIR}/recovery.conf file. Please verify permissions, create the recovery.conf, then resync the new replica manually."
DONT_RESYNC=1
fi
fi
# Loop for a bit and see if we can connect to the new master
echo -n "Waiting for postgresql service to be available."
i=0
while [ ${i} -lt 10 ]; do
ISINRECOVERY=$(${PSQL} -Atc "SELECT pg_is_in_recovery()" -U ${PGUSER} postgres)
if [ "${ISINRECOVERY}" = "f" ]; then
PSQL_SUCCESS=1
break
fi
echo -n "."
sleep 5
i=$[$i+1]
done
echo
# remove the recovery.done file if it exists
if [ -z "${PSQL_SUCCESS}" ]; then
echo "Unable to connect to new master ${REPLICA} via psql."
echo "Please verify functionality, then resync the new replica ${MASTER} manually."
reset_conf
else
if [ -f ${PGDATA}/recovery.done ]; then
rm -f ${PGDATA}/recovery.done
fi
fi
# resync the old master from the new master
if [ -n "${DONT_RESYNC}" -o -n "${MASTERDOWN}" ]; then
echo "Skipping resync of new replica ${MASTER}."
exit 1
else
echo "Initiating replica resync. This may take a while..."
${SSH} ${SSH_OPT} ${MASTER} "$(dirname ${CONF_FILE})/pg_resync_replica < /dev/null >& /dev/null"
if [ $? -ne 0 ]; then
echo "resync of ${MASTER} failed. Please fix errors and resync manually."
exit 1
fi
fi
echo "This is now the Master. Please verify replication is continuing properly."
exit 0
# -----------------------------------------------------------------------------
# The replication-tools package is licensed under the PostgreSQL License:
#
# Copyright (c) 2010-2011, PostgreSQL, Experts, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without a written agreement is
# hereby granted, provided that the above copyright notice and this paragraph
# and the following two paragraphs appear in all copies.
#
# IN NO EVENT SHALL POSTGRESQL EXPERTS, INC. BE LIABLE TO ANY PARTY FOR DIRECT,
# INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
# PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
# IF POSTGRESQL EXPERTS, INC. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# POSTGRESQL EXPERTS, INC. SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
# AND POSTGRESQL EXPERTS, INC. HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.<file_sep>#!/bin/sh
# script to ensure a copied file is exactly 16MB before copying it
SOURCE=$1
DEST=$2
if [ "$(stat --format=%s ${SOURCE})" -ne "16777216" ]; then
echo "${SOURCE} not 16MB in size!"
exit 2
fi
cp ${SOURCE} ${DEST}
<file_sep>#!/usr/bin/env bash
# Simple script to copy WAL archives from one server to another
# to be called as archive_command (call this as wal_archive "%p" "%f")
# Version 1.6. Last updated 2011-02-17.
# Copyright (c) 2010-2011, PostgreSQL, Experts, Inc.
# Licensed under The PostgreSQL License; see
# http://www.postgresql.org/about/licence
# or the end of this file for details.
# source config file
. /var/lib/postgresql/scripts/pitr-replication.conf
SOURCE="$1" # %p
FILE="$2" # %f
DEST="${WALDIR}/${FILE}"
TEMPDEST="${WALDIR}/.${FILE}"
export RSYNC_RSH="${SSH} ${SSH_OPT}"
# See whether we want all archiving off
test -f ${NOARCHIVEFILE} && exit 0
# Copy the file to the spool area on the replica, error out if
# the transfer fails
${RSYNC} --quiet --archive --rsync-path=${RSYNC} ${SOURCE} ${REPLICA}:${DEST}
if [ $? -ne 0 ]; then
exit 1
fi
# Copy elsewhere if you like.
if [ -f ${LOCAL_DESTINATIONS_LIST} ]; then
while read LDEST ; do
DEST="${LDEST}/${FILE}"
${CP} "${SOURCE}" ${DEST} || exit $?
done < ${LOCAL_DESTINATIONS_LIST}
fi
# -----------------------------------------------------------------------------
# The replication-tools package is licensed under the PostgreSQL License:
#
# Copyright (c) 2010-2011, PostgreSQL, Experts, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without a written agreement is
# hereby granted, provided that the above copyright notice and this paragraph
# and the following two paragraphs appear in all copies.
#
# IN NO EVENT SHALL POSTGRESQL EXPERTS, INC. BE LIABLE TO ANY PARTY FOR DIRECT,
# INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
# PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
# IF POSTGRESQL EXPERTS, INC. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# POSTGRESQL EXPERTS, INC. SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
# AND POSTGRESQL EXPERTS, INC. HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.<file_sep>module Moonshine
module Postgres9
def self.included(manifest)
manifest.class_eval do
extend ClassMethods
end
end
module ClassMethods
def postgresql_primary?
raise "FIXME please implement to determine if this server is the master"
end
def postgresql_standby?
raise "FIXME please implement to determine if this server is the slaver"
end
# master of this master-replica pair
def postgresql_primary_server
raise "FIXME please implement to return a hash with :hostname, :ip, and :internal_ip of primary server"
end
# master of this master-replica pair
def postgresql_standby_server
raise "FIXME please implement to return a hash with :hostname, :ip, and :internal_ip of standby server"
end
end
def postgresql_version
(configuration[:postgresql] && configuration[:postgresql][:version]) || '9.0'
end
def postgresql_supports_custom_variable_classes?
postgresql_version <= '9.1'
end
def postgresql_restart_on_change
restart_on_change = configuration[:postgresql][:restart_on_change]
restart_on_change = true if restart_on_change.nil? # treat nil as true, to be able to default
restart_on_change
end
def postgresql_ppa
exec "add postgresql key",
:command => "wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -",
:require => package('python-software-properties'),
:unless => "sudo apt-key list | grep 'PostgreSQL Debian Repository'"
file "/etc/apt/sources.list.d/pitti-postgresql-lucid.list",
:ensure => :absent
configure(:postgresql => HashWithIndifferentAccess.new)
if ubuntu_precise?
repo = "precise"
elsif ubuntu_lucid?
repo = "lucid"
elsif ubuntu_trusty?
repo = "trusty"
end
repo_path = "deb http://apt.postgresql.org/pub/repos/apt/ #{repo}-pgdg main"
file '/etc/apt/preferences.d',
:ensure => :directory
file '/etc/apt/preferences.d/postgresql',
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', "preferences")),
:ensure => :present,
:require => [file("/etc/apt/preferences.d")]
exec 'add postgresql source list',
:command => "add-apt-repository '#{repo_path}'",
:unless => "cat /etc/apt/sources.list | grep #{repo_path}",
:require => package('python-software-properties')
exec 'update sources',
:command => 'apt-get update',
:subscribe => exec('add postgresql source list'),
:refreshonly => true
end
def postgresql_client
recipe :postgresql_ppa
recipe :only_correct_postgres_version
package 'libpq-dev',
:ensure => :installed,
:require => exec('update sources'),
:before => exec('rails_gems')
package "postgresql-client-#{postgresql_version}",
:ensure => :installed,
:require => exec('update sources'),
:before => exec('rails_gems')
end
# Installs <tt>postgresql-9.x</tt> from apt and enables the <tt>postgresql</tt>
# service. Using a backports repo to get version 9.x:
# https://launchpad.net/~pitti/+archive/postgresql
def postgresql_server(options = {})
version = postgresql_version
recipe :postgresql_client
recipe :postgresql_scripts
package "postgresql-#{version}",
:ensure => :installed,
:require => exec('update sources')
package "postgresql-contrib-#{version}",
:ensure => :installed,
:require => exec('update sources')
service 'postgresql',
:ensure => :running,
:hasstatus => true,
:require => package("postgresql-#{version}")
notifies = if postgresql_restart_on_change
[service('postgresql')]
else
[]
end
# ensure the postgresql key is present on the configuration hash
file "/etc/postgresql/#{version}/main/pg_hba.conf",
:ensure => :present,
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', 'pg_hba.conf.erb'), binding),
:require => package("postgresql-#{version}"),
:mode => '600',
:owner => 'postgres',
:group => 'postgres',
:notify => notifies
file "/etc/postgresql/#{version}/main/postgresql.conf",
:ensure => :present,
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', 'postgresql.conf.erb'), binding),
:require => package("postgresql-#{version}"),
:mode => '600',
:owner => 'postgres',
:group => 'postgres',
:notify => notifies
end
# Install the <tt>pg</tt> rubygem and dependencies
def postgresql_gem
gem 'pg'
end
# Grant the database user specified in the current <tt>database_environment</tt>
# permisson to access the database with the supplied password
def postgresql_user
psql "CREATE USER #{database_environment[:username]} WITH PASSWORD '#{database_environment[:password]}'",
:alias => "postgresql_user",
:unless => psql_query('\\\\du') + "| grep \"\\b#{database_environment[:username]}\\b\"",
:require => service('postgresql')
end
# Create the database from the current <tt>database_environment</tt>
def postgresql_database
# FIXME work in progress
#encoding = "-E #{configuration[:postgresql][:encoding]}" if configuration[:postgresql][:encoding]
encoding = ''
template = "-T #{configuration[:postgresql][:template_database]}" if configuration[:postgresql][:template_database]
exec "postgresql_database",
:command => "/usr/bin/createdb -O #{database_environment[:username]} #{encoding} #{template} #{database_environment[:database]}",
:unless => "/usr/bin/psql -l | grep #{database_environment[:database]}",
:user => 'postgres',
:require => exec('postgresql_user'),
:before => exec('rake tasks')#,
# :notify => exec('rails_bootstrap') # TODO make this configurable to work with multi_server
end
def postgresql_streaming_replication
recipe :prune_pg_log
recipe :wal_archive
recipe :postgresql_ssh_access
recipe :postgresql_replication_user
if postgresql_primary?
recipe :postgresql_replication_master
elsif postgresql_standby?
recipe :postgresql_replication_standby
end
end
# Create a database user with replication priviledges
def postgresql_replication_user
replication_username = configuration[:postgresql][:replication_username] || "#{database_environment[:username]}_replication"
raise "Missing configuration[:postgresql][:replication_password], please add and try again" unless configuration[:postgresql][:replication_password]
psql "CREATE USER #{replication_username} WITH SUPERUSER ENCRYPTED PASSWORD '#{configuration[:postgresql][:replication_password]}'",
:alias => "postgresql_replication_user",
:unless => psql_query('\\\\du') + "| grep #{replication_username}",
:require => service('postgresql')
end
def postgresql_replication_master
file "/var/lib/postgresql/#{postgresql_version}/main/pg_xlogarch",
:ensure => :directory,
:owner => 'postgres',
:group => 'postgres'
end
def pgbouncer
package 'pgbouncer', :ensure => :installed
file '/etc/pgbouncer/userlist.txt',
:ensure => :present,
:require => package('pgbouncer'),
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', 'userlist.txt.erb'))
file '/etc/pgbouncer/pgbouncer.ini',
:ensure => :present,
:require => package('pgbouncer'),
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', 'pgbouncer.ini.erb'))
file '/etc/default/pgbouncer',
:ensure => :present,
:require => package('pgbouncer'),
:content => 'START=1'
service 'pgbouncer',
:ensure => :running,
:require => [
file('/etc/pgbouncer/pgbouncer.ini'),
file('/etc/pgbouncer/userlist.txt'),
file('/etc/default/pgbouncer')
],
:subscribe => [
file('/etc/pgbouncer/pgbouncer.ini'),
file('/etc/pgbouncer/userlist.txt'),
file('/etc/default/pgbouncer')
]
end
def postgresql_ssh_access
file '/var/lib/postgresql/.ssh',
:ensure => :directory,
:owner => 'postgres',
:require => package("postgresql-#{postgresql_version}")
exec %Q{ssh-keygen -f /var/lib/postgresql/.ssh/id_rsa -N ''},
:user => 'postgres',
:creates => '/var/lib/postgresql/.ssh/id_rsa',
:require => [file('/var/lib/postgresql/.ssh'), package("postgresql-#{postgresql_version}")]
(configuration[:postgresql][:public_ssh_keys] || {}).each do |hostname, key|
ssh_authorized_key "postgres@#{hostname}",
:type => 'ssh-rsa',
:key => key,
:user => 'postgres',
:require => file('/var/lib/postgresql/.ssh')
end
end
def wal_archive
version = postgresql_version
file '/var/lib/postgresql/wal_archive.sh',
:require => package("postgresql-#{version}"),
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', 'wal_archive.sh')),
:ensure => :present,
:mode => '755',
:owner => 'postgres',
:group => 'postgres'
wal_dir = configuration[:postgresql][:wal_dir] || "/var/lib/postgresql/#{version}/main/pg_xlogarch"
file wal_dir,
:require => package("postgresql-#{version}"),
:ensure => :directory,
:owner => 'postgres',
:group => 'postgres'
file '/var/lib/postgresql/scripts/pitr-replication.conf',
:require => package("postgresql-#{version}"),
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', 'pitr-replication.conf.erb'), binding),
:ensure => :present,
:mode => '755',
:owner => 'postgres',
:group => 'postgres'
end
def postgresql_scripts
file "/var/lib/postgresql/scripts",
:ensure => :directory,
:owner => 'postgres',
:require => package("postgresql-#{postgresql_version}")
["cp16mbonly", "pg_resync_replica", "promote_to_master", "wal_archive"].each do |f|
file "/var/lib/postgresql/scripts/#{f}",
:ensure => :present,
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', "#{f}.erb"), binding),
:owner => 'postgres',
:mode => '0755',
:require => file('/var/lib/postgresql/scripts')
end
end
def prune_pg_log
version = postgresql_version
cron 'prune pg log',
:command => "find /var/lib/postgresql/#{version}/main/pg_log -mtime +7 -delete",
:user => 'root',
:hour => '0',
:minute => '10'
end
def postgresql_replication_standby
version = postgresql_version
notifies = if postgresql_restart_on_change
[service('postgresql')]
else
[]
end
file '/var/lib/postgresql/recovery.conf',
:content => template(File.join(File.dirname(__FILE__), '..', '..', 'templates', 'recovery.conf.erb'), binding),
:require => package("postgresql-#{version}"),
:mode => '600',
:owner => 'postgres',
:group => 'postgres',
:notify => notifies
file "/var/lib/postgresql/#{version}/main/recovery.conf",
:ensure => '/var/lib/postgresql/recovery.conf',
:require => file('/var/lib/postgresql/recovery.conf')
end
# it's easy for other postgresql versions get installed. make sure they are uninstalled, and therefore not running
def only_correct_postgres_version
%w(8.4 9.0 9.1 9.2 9.3 9.4 9.5 9.6).each do |version|
if version != postgresql_version.to_s # need to_s, because YAML may think it's a float
package "postgresql-#{version}", :ensure => :absent
package "postgresql-contrib-#{version}", :ensure => :absent
end
end
end
private
def psql(query, options = {})
name = options.delete(:alias) || "psql #{query}"
hash = {
:command => psql_query(query, options),
:user => 'postgres'
}.merge(options)
exec(name,hash)
end
def psql_query(sql, options = {})
if options && options[:dbname]
dbname = "--dbname #{options.delete(:dbname)}"
end
"/usr/bin/psql -c \"#{sql}\" #{dbname}"
end
end
end
<file_sep>#!/usr/bin/env bash
# Simple script to re-sync a PITR replica
# Version 1.6. Last updated 2011-02-17.
# Copyright (c) 2010-2011, PostgreSQL, Experts, Inc.
# Licensed under The PostgreSQL License; see
# http://www.postgresql.org/about/licence
# or the end of this file for details.
# grab the config variables
. /var/lib/postgresql/scripts/pitr-replication.conf
# SSH and SSH_OPT are defined in the config file above
export PGDATA PGUSER PGOPTIONS
if [ ${USE_SSH_SYNC} == yes ]; then
export RSYNC_RSH="${SSH} ${SSH_OPT}"
DB_LOCATION="${MASTER}:${PGDATA}/"
else
DB_LOCATION="${MASTER}::${RSYNC_SERVER}"
export RSYNC_PASSWORD="${R<PASSWORD>}"
fi
echo "Rsync opts"
echo $RSYNC_RSH
function catch_trap
{
echo "Killed! Stopping backup mode on master"
${PSQL} -c "SELECT pg_stop_backup();" -h ${MASTER} -U ${PGUSER} postgres
trap - INT TERM EXIT
exit 1
}
trap catch_trap INT TERM EXIT
if [ -f ${RECOVERYCONFDIR}/recovery.conf -o -f ${RECOVERYCONFDIR}/recovery.done ]; then
echo 'Looks like this is the replica, continuing.'
else
echo 'No recovery.conf or recovery.done file.'
echo 'This might not be the replica.'
echo 'You should only run this script on the replica!'
exit 1
fi
# Remove the trigger file if it exists
if [ -f ${BRINGUP} ]; then
rm -f ${BRINGUP}
fi
# Stop postgres if running
if [ $OS = 'Joyent' ] && [ $USE_SVCADM ]; then
/usr/sbin/svcadm disable postgresql:pg90
else
${PGCTL} -m immediate ${PGCTLOPTIONS} stop 2> /dev/null
fi
# Did we stop postgres successfully?
if ps -ef | grep [p]ostgres: > /dev/null 2>&1; then
echo "Shutdown failed. Aborting."
exit 1
fi
echo 'Starting backup'
${PSQL} -c "SELECT pg_start_backup('`/bin/date +%Y%m%d`');" -h ${MASTER} -U ${PGUSER} postgres
echo 'Fetching filesystem image'
echo "${RSYNC} -avP ${RSYNC_OPT} --exclude postmaster.pid --exclude recovery.conf --exclude recovery.done --exclude postgresql.conf --exclude pg_log --exclude pg_x\
log ${DB_LOCATION} ${PGDATA}/ --rsync-path=${RSYNC} --delete"
${RSYNC} -avP ${RSYNC_OPT} --exclude postmaster.pid --exclude recovery.conf --exclude recovery.done --exclude postgresql.conf --exclude pg_log --exclude pg_x\
log ${DB_LOCATION} ${PGDATA}/ --rsync-path=${RSYNC} --delete
# Run through the rest of the tablespaces and rsync them, too.
# disabled because it doesn't work with current rsync code
# and we don't have tablespaces anyway
#echo 'Fetching tablespaces'
#GET_TB="SELECT spclocation FROM pg_catalog.pg_tablespace WHERE length(spclocation) > 0"
#for tablespace in $(${PSQL} -h ${MASTER} -U ${PGUSER} -Atc "${GET_TB}" postgres)
#do
# [ -d $(dirname ${tablespace}) ] || mkdir -p $(dirname ${tablespace})
# ${RSYNC} -avPz ${MASTER}:${tablespace} $(dirname ${tablespace}) --rsync-path=${RSYNC} --delete
#done
${PSQL} -c "SELECT pg_stop_backup();" -h ${MASTER} -U ${PGUSER} postgres
# clean out xlog files
find ${PGDATA}/pg_xlog/ -type f | xargs rm -f
# rename recovery.done to recovery.conf if it exists
if [ -f ${RECOVERYCONFDIR}/recovery.done ]; then
mv ${RECOVERYCONFDIR}/recovery.done ${RECOVERYCONFDIR}/recovery.conf
fi
# remove BRINGUP file if it exists
if [ -f ${BRINGUP} ]; then
rm -f ${BRINGUP}
fi
# Start postgres
if [ $OS = 'Joyent' ] && [ $USE_SVCADM ]; then
/usr/sbin/svcadm enable postgresql:pg90
else
${PGCTL} -D $(dirname ${PGCONFFILE}) start
fi
# reset the traps so we can exit cleanly
trap - INT TERM EXIT
# -----------------------------------------------------------------------------
# The replication-tools package is licensed under the PostgreSQL License:
#
# Copyright (c) 2010-2011, PostgreSQL, Experts, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without a written agreement is
# hereby granted, provided that the above copyright notice and this paragraph
# and the following two paragraphs appear in all copies.
#
# IN NO EVENT SHALL POSTGRESQL EXPERTS, INC. BE LIABLE TO ANY PARTY FOR DIRECT,
# INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
# PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
# IF POSTGRESQL EXPERTS, INC. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# POSTGRESQL EXPERTS, INC. SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
# AND POSTGRESQL EXPERTS, INC. HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
<file_sep>= Moonshine Postgres9
=== A plugin for Moonshine[http://github.com/railsmachine/moonshine]
A plugin for installing and managing postgres_9.
=== Instructions
* <tt>script/plugin install git://github.com/railsmachine/moonshine_postgres_9.git</tt>
* Configure settings if needed
configure(:postgresql => {:version => '9.2'})
* Add the following line near the top of your manifest:
include Moonshine::Postgres9
As long as you're using one of the standard moonshine stacks, like <code>:default_stack</code>, then the postgres 9 recipes will override the default Postgres recipes and install version 9.x instead.
Moonshine Postgres9 enables SSL connections between the client and server. The
server requires an SSL certificate and key to be placed at
<code>$PGDATA/server.crt</cody> and <code>$PGDATA/server.key</code> respectively.
The {PostgreSQL docs}(http://www.postgresql.org/docs/9.1/static/ssl-tcp.html)
describe the steps to create a self-signed certificate.
| 3b1378cb8a47acaf85b47d65e4bc90176b855be5 | [
"RDoc",
"Ruby",
"Shell"
] | 7 | Ruby | railsmachine/moonshine_postgres_9 | dc9a11832cccf0cb5c1ed8dcfc3fa37644ffc7e3 | da68ccd3df399636d7f89f42c1d005383cc5d34d |
refs/heads/master | <repo_name>adrianosilvareis/AgendaGap<file_sep>/README.md
"# AgendaGap"
<file_sep>/js/controllers/agenda.ctrl.js
angular.module('agenda').controller('agendaCtrl', function($scope){
$scope.title = "Agenda Polânia";
}); | 1e902caf03541703f2073c7adf6b40ca95b4755d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | adrianosilvareis/AgendaGap | d220b7bc0068c103acbeb6e17748ab17d098f66b | a9c739a237c72d05d537d48d3dda72e1350cff6c |
refs/heads/master | <file_sep># -*- coding:utf8 -*-
import tornado.ioloop
import tornado.web
from tornado.web import StaticFileHandler
import os
import json
import pymysql
from pymysql.cursors import DictCursor
import time
import qiniuyun
# mysql connect
# fix me
conn = pymysql.connect(host="", user="", password="", database="", charset="utf8")
# session obj
container = {}
class MainHandler(tornado.web.RequestHandler):
def get(self):
''' 获取前端cookie,若session obj存在则直接跳转上传页面 '''
hq_cookie = self.get_cookie('student_cookie', None)
session = container.get(hq_cookie, None)
if session is None:
self.render("template/login.html")
else:
self.render("template/student.html")
class GetUploadStatus(tornado.web.RequestHandler):
def get(self):
hid = self.get_query_argument("hid", "")
hq_cookie = self.get_cookie('student_cookie', None)
session = container.get(hq_cookie, None)
# start fix
cursor = conn.cursor(DictCursor)
sql = '''
SELECT is_upload,upload_time,stu_name FROM upload_list WHERE stu_num=%s AND homework_id=%s
''' % (session['stu_num'], hid)
cursor.execute(sql)
res = cursor.fetchall()
cursor.close()
# end fix
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.write({'data': res, 'code': 200})
class LoginHandle(tornado.web.RequestHandler):
def post(self):
''' 登录逻辑:验证信息通过后,生成MD5密钥作为session_key存到前端cookie '''
stu_num = self.get_body_argument("stu_num", "")
stu_name = self.get_body_argument("stu_name", "")
self.set_header("Content-Type", "application/json; charset=UTF-8")
if stu_name and stu_num:
# start fix
cursor = conn.cursor()
sql = '''
SELECT * FROM students WHERE stu_name='%s' AND stu_num_gdit='%s'
''' % (stu_name, stu_num)
res = cursor.execute(sql)
cursor.close()
# end fix
if res == 1:
import hashlib
md5 = hashlib.md5()
md5.update(bytes(str(stu_name), encoding="utf-8"))
cookie = md5.hexdigest()
self.set_cookie('student_cookie', cookie, expires_days=15)
stu_sex = cursor.fetchone()
container[cookie] = { 'stu_num': stu_num, 'stu_name': stu_name, 'sex': stu_sex[8]}
self.write({'code': 200})
else:
self.write({'code': 400})
else:
self.write({'code': 400})
class AdminLoginHandle(tornado.web.RequestHandler):
def post(self):
code = self.get_body_argument('code', 0)
# fix me
if code == "your admin code":
import hashlib
md5 = hashlib.md5()
md5.update(bytes(str(code), encoding="utf-8"))
cookie = md5.hexdigest()
self.set_cookie('admin_cookie', cookie, expires_days=7)
self.write({'code': 200})
else:
self.write({'code': 400})
class AdminHandle(tornado.web.RequestHandler):
def get(self):
hq_cookie = self.get_cookie('admin_cookie', None)
if hq_cookie is None:
self.render("template/admin-login.html")
else:
import hashlib
md5 = hashlib.md5()
# fix me
md5.update(bytes(str("your admin code"), encoding="utf-8"))
cookie = md5.hexdigest()
if cookie == hq_cookie:
self.render("template/admin.html")
else:
self.clear_cookie('admin_cookie')
self.render("template/admin-login.html")
def post(self):
hid = int(self.get_body_argument('hid', 0))
# start fix
cursor = conn.cursor()
sql = '''
DELETE FROM homework WHERE id=%s
''' % (hid)
cursor.execute(sql)
conn.commit()
sql = """
DELETE FROM upload_list WHERE homework_id=%s
""" % (hid)
cursor.execute(sql)
conn.commit()
cursor.close()
# end fix
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.write({'code': 200})
class HomeworkHandle(tornado.web.RequestHandler):
def get(self):
now = str(time.time()).split(".")[0]
page = self.get_query_argument("page", 1)
limit = self.get_query_argument("limit", 10)
page = (int(page) - 1) * int(limit)
# start fix
cursor = conn.cursor(DictCursor)
# 检查到期
sql_1 = '''
SELECT * FROM homework WHERE deadline != 0 AND status = 1 ORDER BY id DESC LIMIT %s,%s
''' % (page, limit)
cursor.execute(sql_1)
res1 = cursor.fetchall()
for i in res1:
create_time = int(i['create_time'])
day = int((int(now) - create_time) / (24 * 3600))
if i['deadline'] < day:
sql_2 = """
UPDATE homework SET status=0 WHERE id=%s
""" % (i['id'])
cursor.execute(sql_2)
conn.commit()
sql = '''
SELECT * FROM homework ORDER BY id DESC LIMIT %s,%s
''' % (page, limit)
hq_cookie = self.get_cookie('student_cookie', None)
session = container.get(hq_cookie, None)
if session is not None:
sql = '''
SELECT * FROM homework AS h LEFT JOIN upload_list AS ul ON ul.homework_id=h.id WHERE ul.stu_num='%s' ORDER BY h.id DESC LIMIT %s,%s
''' % (session['stu_num'], page, limit)
cursor.execute(sql)
res = cursor.fetchall()
cursor.close()
# end fix
self.set_header("Content-Type", "application/json; charset=UTF-8")
if session is not None:
self.write({'data': res, 'code': 200, 'info': session, 'now': now})
else:
self.write({'data': res, 'code': 200})
class UploadListHandle(tornado.web.RequestHandler):
def get(self):
hid = self.get_query_argument("hid", "")
self.set_header("Content-Type", "application/json; charset=UTF-8")
if hid:
hid = int(hid)
# start fix
cursor = conn.cursor(DictCursor)
sql = '''
SELECT * FROM upload_list WHERE homework_id=%s ORDER BY stu_num ASC
''' % (hid)
cursor.execute(sql)
res = cursor.fetchall()
cursor.close()
# end fix
self.write({'data': res, 'code': 200})
else:
self.write({'code': 400})
class AddHomeworkHandle(tornado.web.RequestHandler):
def get(self):
self.render("template/add-homework.html")
def post(self):
''' 提交作业,同时创建一个班级名单,默认设置待提交 '''
title = self.get_body_argument('title', '')
deadline = self.get_body_argument('deadline', '')
addtional_name = self.get_body_argument("addtional_name", '')
describe = self.get_body_argument("describe", '')
if title:
# start fix
cursor = conn.cursor()
sql = '''
INSERT INTO homework (title,deadline,addtional_name,`describe`,create_time) VALUE ('%s', '%s', '%s', '%s', '%s')
''' % (title, deadline, addtional_name, describe, str(time.time()).split(".")[0])
cursor.execute(sql)
conn.commit()
homework_id = int(cursor.lastrowid)
sql_1 = """
SELECT * FROM students ORDER BY stu_num_gdit ASC
"""
cursor.execute(sql_1)
res = list(cursor.fetchall())
sql_2 = "INSERT INTO upload_list (stu_name,stu_num,homework_id) VALUES ('%s', '%s', %s)" % (res[0][2], res[0][11], homework_id)
for i in res[1:20]:
sql_2 += ",('%s', '%s', %s)" % (i[2], i[11], homework_id)
cursor.execute(sql_2)
conn.commit()
sql_2 = "INSERT INTO upload_list (stu_name,stu_num,homework_id) VALUES ('%s', '%s', %s)" % (res[20][2], res[20][11], homework_id)
for i in res[21:]:
sql_2 += ",('%s', '%s', %s)" % (i[2], i[11], homework_id)
cursor.execute(sql_2)
conn.commit()
cursor.close()
# end fix
self.redirect("/admin")
class UploadFileHandle(tornado.web.RequestHandler):
def get(self):
''' 获取七牛云上传的凭证 '''
# fix me
auth = qiniuyun.Auth('AccessKey', "SecretKey")
bucket = auth.upload_token(bucket="gdit")
self.write(bucket)
def post(self):
''' 保存上传记录 '''
url = self.get_body_argument("url", "")
hid = int(self.get_body_argument("hid", 0))
hq_cookie = self.get_cookie('student_cookie', None)
session = container.get(hq_cookie, None)
stu_num = session['stu_num']
import time
# start fix
cursor = conn.cursor()
sql = '''
UPDATE upload_list SET is_upload=1,upload_time='%s',url='%s' WHERE stu_num='%s' AND homework_id=%s
''' % (str(time.time()).split(".")[0], url, stu_num, hid)
cursor.execute(sql)
conn.commit()
cursor.close()
# end fix
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.write({'code': 200})
class LogoutHandle(tornado.web.RequestHandler):
def post(self):
self.clear_cookie("student_cookie")
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.write({'code': 200})
class EditHomeworkHandle(tornado.web.RequestHandler):
def get(self):
self.render("template/edit-homework.html")
def post(self):
hid = self.get_body_argument("id", "")
title = self.get_body_argument("title", "")
describe = self.get_body_argument("describe", "")
# start fix
cursor = conn.cursor(DictCursor)
sql = '''
UPDATE homework SET title="%s", `describe`="%s" WHERE id=%s
''' % (title, describe, hid)
cursor.execute(sql)
conn.commit()
cursor.close()
# end fix
self.redirect("/admin")
class HomeworkStatusHandle(tornado.web.RequestHandler):
def post(self):
hid = self.get_body_argument("id", "")
status = self.get_body_argument("changeS", "")
# start fix
cursor = conn.cursor(DictCursor)
sql = '''
UPDATE homework SET status=%s WHERE id=%s
''' % (int(status), hid)
cursor.execute(sql)
conn.commit()
cursor.close()
# end fix
# 路由配置
def make_app():
return tornado.web.Application(
[
(r"/", MainHandler),
(r'/admin', AdminHandle),
(r'/admin/add-homework', AddHomeworkHandle),
(r'/admin/edit-homework', EditHomeworkHandle),
(r'/api/v1/login', LoginHandle),
(r'/api/v1/addHomework', AddHomeworkHandle),
(r'/api/v1/getHomework', HomeworkHandle),
(r'/api/v1/getUploadList', UploadListHandle),
(r'/api/v1/uploadStatus', GetUploadStatus),
(r"/api/v1/upload", UploadFileHandle),
(r'/api/v1/getBucket', UploadFileHandle),
(r'/api/v1/delHomework', AdminHandle),
(r'/api/v1/adminLogin', AdminLoginHandle),
(r'/api/v1/logout', LogoutHandle),
(r'/api/v1/editHomework', EditHomeworkHandle),
(r'/api/v1/changeStatus', HomeworkStatusHandle),
],
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True
)
# 启动项目
if __name__ == "__main__":
print("app run listen on 5003")
app = make_app()
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(5003)
tornado.ioloop.IOLoop.current().start()
<file_sep># homework-system
一.环境介绍
1.运行环境 Python3.6
2.后台框架:Tornado
3.前端ui框架:妹子UI
二.目录介绍
static为静态资源目录,存放css.js等资源;
template为前端html文件;
app.py为后台项目的主要文件,包含路由配置,项目运行配置,后台API接口逻辑处理;
compat.py,utils.py,qiniuyun.py是七牛云提供的python上传文件的Demo。
三.项目环境配置
基于Python3.6,安装项目运行环境:pip install -r requirements.txt
四.项目运行配置
要使该项目运行起来主要需要配置你的数据库:在app.py文件中,第16行处配置你的数据库信息;
另外由于上传的文件被存储在第三方资源服务器(七牛云),所以你需要创建属于自己的七牛云账号(创建教程:https://blog.yellow948.cn/article/49/) 在app.py第254行处填写你的七牛云的授权码;
其他配置:在项目全局搜索"fix me"是项目运行必须的配置,"start fix"主要是数据库语句的修改,若你的数据库表设计与项目不符合,你可以修改相应的数据库语句已让后台业务逻辑能够正常运行。
五.项目运行
进入项目根目录,执行 python app.py,访问 http://127.0.0.1:5003 进入学生端,http://127.0.0.1:5003/admin 进入管理员端
六.其他
数据库表的字段展示:
students: id,stu_name,stu_num_gdit
homework: id,title,status,describe,create_time,deadline,addtional_name
upload_list: id,stu_name,stu_num,is_upload,upload_time,homework_id,url
<file_sep>PyMySQL==0.9.3
requests==2.22.0
tornado==6.0.4
urllib3==1.25.6 | 994ec4c3bea427161510f416399a87cc0b88b7fd | [
"Markdown",
"Python",
"Text"
] | 3 | Python | yellow948/homework-system | 0d4c3cd9253aee679bda5a364a7acc024a7e0b4f | 29b2893c39aca973de29bdadad0c8d478c72b740 |
refs/heads/main | <repo_name>ps9610/tjoeun_10_26-10_30_education<file_sep>/10_30/10_30_프로젝트_스타벅스_알드라이브용/js/section5.js
//스크롤 이벤트 해야하기 때문에 3개 매개변수 다 필요함
;(function(window,document,$,undefined){
var t = 0;
function init(){
$("#section5 .left") .stop().animate({ left: -1000 },1000,function(){
$("#section5 .left") .stop().animate({ left: 0 },2000);
});
$("#section5 .right").stop().animate({ right:-1000 },1000,function(){
$("#section5 .right").stop().animate({ right:0 },2000);
});
}
setTimeout(init,100);
function s5AnimationtFormatFn(){
//#section5 .wrap .left
$("#section5 .left") .stop().animate({ left: -1000 },1000);
// 초기 함수
$("#section5 .right").stop().animate({ right:-1000 },1000);
}
function s5AnimationFn(){
$("#section5 .left") .stop().animate({ left: 0 },2000);
//실행하는 함수
$("#section5 .right").stop().animate({ right:0 },2000);
}
$(window).scroll(function(){
if( $(this).scrollTop() < 400 ){
if(t == 0)
s5AnimationtFormatFn();
t=1;
}
if( $(this).scrollTop() >= 400 ){
if(t == 1)
s5AnimationFn();
t=0;
}
});
})(window,document,$);<file_sep>/10_28/10_28_프로젝트_스타벅스_섹션_8_혼자하기/js/section8.js
(function(document,window,$,undefined){
var t = 0;
setTimeout(init,100);
function init(){
$(".right-row1 .image").stop().animate({ right:-1000 },0).animate({ right:0 },2500);
$(".right-row2 .image").stop().animate({ right:-1000 },0).animate({ right:0 },2900);
}
function formatFn(){
$(".right-row1 .image").stop().animate({ right:-1000 },1000);
$(".right-row2 .image").stop().animate({ right:-1000 },1000);
};
function animateFn(){
$(".right-row1 .image").stop().animate({ right:0 },2500);
$(".right-row2 .image").stop().animate({ right:0 },2800);
};
$(window).scroll(function(){
if( $(this).scrollTop() >= $("#section7").offset().top+200 ){
if( t==0 ){
t=1;
animateFn();
}
}
if( $(this).scrollTop() < $("#section7").offset().top+200 ){
if( t==1 ){
t=0;
formatFn();
}
}
});
})(document,window,jQuery);<file_sep>/10_26/10_26_링컨자동차코리아_메인슬라이드_제작_구현/js/index.js
// 클릭이벤트 터치이벤트 6초 이상 없으면 자동실행
(function(window, document, $){
var cnt = 0;
var setId = 0;
var setId2 = 0;
function nextSlideFn(){
cnt++;
mainSlideFn();
};
$(".next-button").on({
click : function(){
if( !$("slide-wrap".is(":animated")) ){
nextSlideFn();
}
timerControlFn();
}
});
function mainSlideFn(){
$(".slide-wrap").stop().animate({left : -1445 * cnt}, 200, function(){
if(cnt>4){cnt=0;}
if(cnt<0){cnt=4;}
$(".slide-wrap").stop().animate({left : -1445 * cnt}, 0);
});
pageBtnFn(cnt);
};
function prevSlideFn(){
cnt--;
mainSlideFn();
};
$(".prev-button").on({
click : function(){
if( !$("slide-wrap".is(":animated")) ){
prevSlideFn();
}
timerControlFn();
}
});
// 터치 스와이프 안됨
$(".slide-wrap").swipe({
swipeLeft : function(e){
e.preventDefault();
if( !$("slide-wrap".is(":animated")) ){
nextSlideFn();
}
timerControlFn();
},
swipeRight : function(e){
e.preventDefault();
if( !$("slide-wrap".is(":animated")) ){
prevSlideFn();
}
timerControlFn();
}
});
$(".indacator-btn").each(function(index){
$(this).on({
click : function(){
cnt = index;
mainSlideFn();
timerControlFn();
}
})
});
function pageBtnFn(z){
z>4? z=0 : z;
$(".indacator-btn").removeClass("addBtn");
$(".indacator-btn").eq(z).addClass("addBtn");
};
function initTimerFn(){
setId = setInterval(nextSlideFn,5000);
};
initTimerFn();
function timerControlFn(){
clearInterval(setId);
clearInterval(setId2);
var cnt2 = 0;
setId2 = setInterval(function(){
cnt2++;
if(cnt2>5){
nextSlideFn();
initTimerFn();
clearInterval(setId2);
}
console.log(cnt2);
},1000); // 정지하고 나서 1초씩 cnt 증가
};
})(window, document, jQuery);<file_sep>/10_30/10_30_프로젝트_스타벅스_알드라이브용/js/section2-3.js
(function(window, document, $){
var cnt = -1;
function noticeSlideFn(){
cnt++;
if(cnt > 3){
cnt = -1;
}
$(".notice-list li").stop().animate({top:24},0).css({zIndex:2});
$(".notice-list li").eq(cnt<0? 4:cnt).stop().animate({top:0},0).css({zIndex:1});
$(".notice-list li").eq(cnt+1).stop().animate({top:24},0).animate({top:0},1000).css({zIndex:3});
}
setInterval(noticeSlideFn, 2500);
}(window, document, jQuery));<file_sep>/10_29/10_29_프로젝트_스타벅스_섹션_8_9_스크롤이벤트_애니메이션/js/section5.js
//스크롤 이벤트 해야하기 때문에 3개 매개변수 다 필요함
;(function(window,document,$,undefined){
//여태까지 했던 것들은 다 DOM, 오늘은 BOM
// (Browser Object Modelling) 윈도우(창)에서 실행되는 이벤트: 홈페이지를 이동하는 location, 위-아래 올라갔다 내려갔다 하는 scroll, 화면 줄였다 늘렸다하는 resize
//1. 섹션1 높이의 반정도(400px) scroll-top(가장 위에서 스크롤함) : 애니메이션 실행되게해라
// : 400px 넘어가면 한 번만 실행하게 toggle변수 사용할예정
// = 패럴럭스(parallelax) = 페이지 스크롤 이벤트
// + 강화할 수 있는 이벤트 : mousewheel
//2. 애니메이션 : 섹션 5의 애니메이션 함수 호출 실행
/*//문서 전체 길이 값 알아보기
$(window).scroll(function(){
console.log("웹페이지가 갖고 있는 문서는 "+ $(document).length + "개 입니다.");
console.log("웹페이지가 갖고 있는 슬라이드는 "+ $(".slide").length + "개 입니다.");
console.log("실제 실행되는 슬라이드는 ", $(".slide").length-2);
console.log( "현재 위치는 " + $(this).scrollTop() + "입니다.");
console.log("문서 전체 높이는 "+ $(document).height() + "입니다.");
console.log("문서 전체 넓이는 "+ $(document).width() + "입니다.");
console.log($(document).height()-$(this).scrollTop());
console.log("창 높이는 "+ $(window).height() + "입니다.");
console.log("창 넓이는 "+ $(window).width() + "입니다.");
});//scroll이벤트 시작*/
var t = 0;
//var t = 'scrollOff';
/* var f = 0; */
setTimeout(animationLoadFn,100);
function animationLoadFn(){
//#section5 .wrap .left
$("#section5 .left") .stop().animate({ left:-1000 },0).animate({ left:0 },1000);
$("#section5 .right").stop().animate({right:-1000 },0).animate({right:0 },1000);
};
function s5AnimationtFormatFn(){
//#section5 .wrap .left
$("#section5 .left") .stop().animate({ left: -1000 },1000);
// 초기 함수
$("#section5 .right").stop().animate({ right:-1000 },1000); //자릿수맞춰서입력 = 체인방식
}
function s5AnimationFn(){
//#section5 .wrap .left
$("#section5 .left") .stop().animate({ left: 0 },2000);
//실행하는 함수
$("#section5 .right").stop().animate({ right:0 },2000);
}
$(window).scroll(function(){
/* if( $(this).scrollTop() == 0 ){
t=0; //스크롤 탑 값이 맨 위 상단위치 0에 도달하면 다시 변수 초기화됨
s5AnimationFormatFn();//애니메이션 포지션을 아예 초기화 시킴
}
*/
// 변수 2개쓰는 방법
/* if( $(this).scrollTop() < 400 ){// 스크롤 탑 값이 맨 위 상단위치 400 미만으로 도달하면 다시 변수 초기화됨
if(f == 0)
t=0 //위에 Top이 0인 경우의 조건문 지웠으니까
f=1;
s5AnimationFormatFn();
}
if( $(this).scrollTop() >= 400 ){
if(t==0){ //토글변수 t의 값이 0이면 함수 호출
t=1; //호출 하고나서 바로 변수값 1로 변경 스크롤 실행 상태임
f=0;
s5AnimationFn();
}
} */
//변수 1개 쓰는 방법(스크롤 이벤트는 무조건 if문만 써야됨 (else if 안먹음))
if( $(this).scrollTop() < 400 ){// 스크롤 탑 값이 맨 위 상단위치 400 미만으로 도달하면 다시 변수 초기화됨
if(t == 0) // t와 함수의 animate left와는 관계없음
s5AnimationtFormatFn();
t=1;
}
if( $(this).scrollTop() >= 400 ){
if(t == 1)
s5AnimationFn();
t=0;
}
/*// t 변수 이해하기
//스크롤 이벤트는 무조건 if문만 써야됨 (elseif 안먹음)
if( $(this).scrollTop() < 400 ){// 스크롤 탑 값이 맨 위 상단위치 400 미만으로 도달하면 다시 변수 초기화됨
if(t == 'scrollOff') // t와 함수의 animate left와는 관계없음
t ='scrollOn' //위에 Top이 0인 경우의 조건문 지웠으니까
s5AnimationFormatFn();
}
if( $(this).scrollTop() >= 400 ){
if(t == 'scrollOn'){ //토글변수 t의 값이 ON이면 함수 호출
t ='scrollOff'; //호출 하고나서 바로 변수값 OFF로 변경
s5AnimationFn();
}
};*/
/* function s5AnimationtFormatFn(){
//#section5 .wrap .left
$("#section5 .left").stop().animate({ left: 0 },1000);
// 초기 함수
$("#section5 .right").stop().animate({ right:0 },1000); //자릿수맞춰서입력 = 체인방식
} */
/* function s5AnimationFn(){
//#section5 .wrap .left
$("#section5 .left").stop().animate({ left: -1000 },2500);
//실행하는 함수
$("#section5 .right").stop().animate({ right:-1000 },2500);
} */
});
})(window,document,$);<file_sep>/10_27/10_27_프로젝트_링컨자동차_슬라이드마무리_혼자하기/js/main-slide.js
;(function($){
var cnt = 0;
var z = 0;
//1.이전, 다음, 메인 슬라이드 만들기
function nextSlideFn(){
cnt++;
mainSlideFn();
};
function prevSlideFn(){
cnt--;
mainSlideFn();
};
function mainSlideFn(){
$(".slide-wrap").stop().animate({left : -1438 * cnt},200,function(){
cnt>4? cnt=0:cnt;
cnt<0? cnt=4:cnt;
console.log(cnt)
$(".slide-wrap").stop().animate({left : -1438 * cnt},0);
});
cnt>4? z=0:z=cnt;
pageBtnFn();
};
//2.이전,다음 클릭 이벤트 리스너(이벤트 받을 준비)/핸들러(이벤트 실행)
$(".next-btn").on({
click:function(e){
e.preventDefault();
if( !$(".slide-wrap").is(":animated") ){
nextSlideFn();
}
}
});
$(".prev-btn").on({
click:function(e){
e.preventDefault();
if( !$(".slide-wrap").is(":animated") ){
prevSlideFn();
}
}
});
//3.페이지 버튼 이벤트
function pageBtnFn(){
$(".page-btn-wrap li").removeClass("addPage");
$(".page-btn-wrap li").eq(z).addClass("addPage");
};
//4.페이지 버튼 클릭 이벤트
$(".page-btn").each(function(index){
$(this).on({
click:function(e){
e.preventDefault();
cnt=index;
nextSlideFn();
mainSlideFn();
}
});
})
$(".slide-wrap").swipe({
swipeLeft:function(){
if( !$(this).is(":animated") ){
nextSlideFn();
}
},
swipeRight:function(){
if( !$(this).is(":animated") ){
prevSlideFn();
}
}
})
//5.페이지 버튼 애니메이션 작동 시에만 실행시키기
// 2번에 추가
})(jQuery);<file_sep>/10_27/10_27_프로젝트_링컨자동차_슬라이드마무리/js/main_slide.js
//; = 이전 실행하던것을 종료함 () ; = 새로운 스크립트를 시작함
;(function($){
var cnt = 0;
var z = 0;
// nextSlideCountFn();
//1-1.next SLide Count(cnt가 증가하냐 감소하냐) 함수
function nextSlideCountFn(){
cnt++; //1) 먼저 되고
mainSlideFn(); //2) 그 담에 1번 정보를 전달받으면서 호출하면서 함수실행
}
//1-2.prev SLide Count(cnt가 증가하냐 감소하냐) 함수
function prevSlideCountFn(){
cnt--;
mainSlideFn();
}
//2. mainSlideFn 함수 -> 5번줄처럼 테스트 한 번 해보기
function mainSlideFn(){
$(".slide-wrap").stop().animate({left:(-1438*cnt)},200,function(){ //이동이 된 다음에 리턴이 가장 깔끔하게 되는 방법이 콜백함수
cnt>4? cnt=0 : cnt;
cnt<0? cnt=4 : cnt;
$(".slide-wrap").stop().animate({left:(-1438*cnt)},0) //5번 사진이 보였는데 이동속도가 0이니까 처음으로 돌아가는 모습이 보이지 않고 초기의 사진으로 돌아옴 = 초기의 값으로 리턴됨
});
cnt>4? z=0 : z=cnt; // cnt= 위에서 쓰고 있는 거 그대로 써야됨 -> z를 사용하는 방법
pageBtnFn();
};
//3-1. 다음 화살 버튼 클릭 이벤트 리스너(이벤트 받을 준비) / 이벤트 핸들러(이벤트 실행하는 주체)
$(".next-btn").on({
click : function(e){
e.preventDefault();
if( !$(".slide-wrap").is(":animated") ){
nextSlideCountFn();
//= cnt++;
// mainSlideFn();
};
}
});
//3-2. 이전 화살 버튼 클릭 이벤트 리스너(이벤트 받을 준비) / 이벤트 핸들러(이벤트 실행하는 주체)
$(".prev-btn").on({
click : function(e){
e.preventDefault();
if( !$(".slide-wrap").is(":animated") ){
prevSlideCountFn();
};
}
});
//4-1-1.indicator button(page-btn); 이벤트 함수 (해당 슬라이드 버튼에 표시되게 하는 것)
function pageBtnFn(){ // 선택자 : JS용 따로 안 만들었으면 그냥 써
$(".page-btn-wrap li").removeClass("addPage"); //addClass된 모든 요소들->초기값 만들어줌
$(".page-btn-wrap li").eq(z).addClass("addPage");
// $(".page-btn-wrap li").eq(1).addClass("addPage");에서 eq값 = cnt랑 동일하니까 pageBtnFn은 main함수 밑에서 cnt 값을 받아와야
// 그 cnt 값을 전달받을 수 있음
//4-1-2. 삼항연산자(조건주석문) 넣기
// 4-1-1 상태에선 리턴이 되면 1번 페이지 버튼에 표시되지 않음 = main에서 cnt가 5까지 출력되기 때문에
// -> pageBtnFn에서의 문제니까 여기 함수 안에서 해결
// -> cnt라는 매개변수를 받을 전달인자 하나 만들어서 삼항연산자 연결해도 되고
// 그냥 z를 전역변수로 써도 됨 ( z>4? z=0 : z; )
};
//4-2.indicator button(page-btn); 클릭 이벤트리스너, 이벤트핸들러 (버튼 누르면 해당 슬라이드 돌려져서 옴)
$(".page-btn").each(function(index){
//console.log(index); // each에 사용할 요소들이 몇개인지 확인(test) = 여기 버튼 5개인거 확인
$(this).on({
click : function(e){
e.preventDefault(); // a링크가 본래 가지고있는 초기화 버튼을 막음
console.log(index)//내가 클릭한(이벤트 걸어놓은) 버튼이(요소가) 실행되는지 확인
cnt=index; //클릭한 슬라이드 번호 -> 전역변수 변경해줌 = 이 홈페이지 전체의 cnt가 내가 클릭한 것으로 바뀐거임
mainSlideFn();
}
});
});
///////////////////////////////////////////////////////////////// 1단계 완료 /////////////////////////////////////////////////////////////////
})(jQuery);
<file_sep>/README.md
# tjoeun_10_26-10_30_education
국비지원 더좋은컴퓨터아카데미 6주차 수업
| dda294f6d2e81f66404f980b176267a4f07ddbce | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | ps9610/tjoeun_10_26-10_30_education | 000e2d54841d517481b6519e7891756942d020b4 | 25423f5f44e4094f396b6bb819a63da6c9834c6e |
refs/heads/master | <file_sep>import React, { useEffect, useState } from 'react'
import './Nav.css'
function Nav() {
const [show, handleSow] = useState(false)
useEffect(() => {
window.addEventListener("scroll", () => {
if (window.scrollY > 100) {
handleSow(true);
} else {
handleSow(false);
}
});
return () => {
window.removeEventListener("scroll")
}
}, [])
return (
<div className={`nav ${show && "nav_black"}`}>
<img
className="nav_logo"
src="netflix.png" alt="Netflix Logo" />
<img
className="nav_avathar"
src="https://mir-s3-cdn-cf.behance.net/project_modules/disp/366be133850498.56ba69ac36858.png" alt="" />
</div>
)
}
export default Nav
<file_sep>// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "netflix-c49ff.firebaseapp.com",
databaseURL: "https://netflix-c49ff.firebaseio.com",
projectId: "netflix-c49ff",
storageBucket: "netflix-c49ff.appspot.com",
messagingSenderId: "210523230158",
appId: "1:210523230158:web:d219ea1283061be2dce59f",
measurementId: "G-KZV654PDDD"
}; | dda42910db42ad2ed4790674a5874245ecd16648 | [
"JavaScript"
] | 2 | JavaScript | premchanduyerra/netflix | 77025685406407dec0a6869f67afc3199a1894ef | 5960d12fae656a5f0c5b56af2dfdc4dd5f9f6443 |
refs/heads/master | <repo_name>litao527/WeiXin<file_sep>/Common/Log.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public class Log
{
static string logDir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
static string logName = string.Format("{0}.txt", DateTime.Now.ToString("yyyyMMdd"));
static string logpath = System.IO.Path.Combine(logDir, logName);
private static readonly Object thisLock = new Object();
public static void Error(string msg)
{
CreateLogFile();
lock (thisLock)
{
using (StreamWriter SW = File.AppendText(logpath))
{
SW.WriteLine(buildMessage(msg));
SW.Close();
}
}
}
public static void Error(string tag, string msg)
{
CreateLogFile();
lock (thisLock)
{
using (StreamWriter SW = File.AppendText(logpath))
{
SW.WriteLine(buildMessage(tag, msg));
SW.Close();
}
}
}
private static void CreateLogFile()
{
if (!System.IO.Directory.Exists(logDir))
{
System.IO.Directory.CreateDirectory(logDir);
}
if (!File.Exists(logpath))
{
StreamWriter SW;
SW = File.CreateText(logpath);
SW.WriteLine("Log created at: " +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
SW.Close();
}
}
private static string buildMessage(string msg)
{
StackTrace trace = new StackTrace();
StringBuilder sb = new StringBuilder();
MethodBase methodName = null;
if (trace.FrameCount > 1)
{
methodName = trace.GetFrame(2).GetMethod();
}
else
{
methodName = trace.GetFrame(1).GetMethod();
}
sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sb.Append("[").Append(methodName.ReflectedType.Name).Append(".").Append(methodName.Name).Append("]");
sb.Append(msg);
return sb.ToString();
}
private static string buildMessage(string tag, string msg)
{
StackTrace trace = new StackTrace();
StringBuilder sb = new StringBuilder();
MethodBase methodName = null;
if (trace.FrameCount > 1)
{
methodName = trace.GetFrame(2).GetMethod();
}
else
{
methodName = trace.GetFrame(1).GetMethod();
}
sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sb.Append("[").Append(tag).Append("]");
sb.Append("[");
sb.Append("[").Append(methodName.ReflectedType.Name).Append(".").Append(methodName.Name).Append("]");
sb.Append(msg);
return sb.ToString();
}
}
}
<file_sep>/weixin/weixin.ashx.cs
using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Xml;
namespace weixin
{
/// <summary>
/// weixin 的摘要说明
/// </summary>
public class weixin : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string sToken = "<PASSWORD>";
string sAppID = "wx414ca95a24d4d83e";
string appSecret = "<KEY>";
string sEncodingAESKey = "<KEY>";
if (context.Request.HttpMethod != "POST")
{
//验证微信开发者接入
try
{
string token = "<PASSWORD>";
string echoStr = context.Request.QueryString["echoStr"];
string signature = context.Request.QueryString["signature"];
string timestamp = context.Request.QueryString["timestamp"];
string nonce = context.Request.QueryString["nonce"];
bool result = Common.WeiXinOperation.ValidUrl(token, echoStr, signature, timestamp, nonce);
if (result)
{
if (!string.IsNullOrEmpty(echoStr))
{
context.Response.Write(echoStr);
}
}
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
throw;
}
}
else
{
Common.wxApi.WXBizMsgCrypt wxcpt = new Common.wxApi.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);
//接收消息
string sReqData = "";
Stream s = context.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
sReqData = Encoding.UTF8.GetString(b);
string encrypt_type = context.Request.QueryString["encrypt_type"];
string sReqMsgSig = context.Request.QueryString["msg_signature"];
string sReqTimeStamp = context.Request.QueryString["timestamp"];
string sReqNonce = context.Request.QueryString["nonce"];
string sMsg = ""; //解析之后的明文
int ret = 0;
ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg);
if (ret != 0)
{
Common.Log.Error("ERR: Decrypt fail, ret: " + ret);
return;
}
Common.Log.Error("接收到的微信消息:" + sMsg);
//string msgType = Common.XmlOperation.GetMsgType(sMsg);
//Model.Message blogModel = Common.XmlOperation.XmlToEntity(sMsg);
//记录到数据库
//DAL.DataAcess.Add(blogModel);
//回复消息
XmlDocument rdoc = new XmlDocument();
rdoc.LoadXml(sMsg);
XmlNode rRoot = rdoc.FirstChild;
string openId = rRoot["FromUserName"].InnerText;
string sendId = rRoot["ToUserName"].InnerText;
string msgType = rRoot["MsgType"].InnerText;
if (msgType == "text")
{
string content = rRoot["Content"].InnerText;
switch (content)
{
case "1":
string textContent = Common.WeiXinOperation.GetTextContent(openId, sendId);
string textEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(textContent, sReqTimeStamp, sReqNonce, ref textEncryptMsg);
context.Response.Write(textEncryptMsg);
context.Response.End();
break;
case "2":
string newsContent = Common.WeiXinOperation.GetNewsContent(openId, sendId);
string newsEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(newsContent, sReqTimeStamp, sReqNonce, ref newsEncryptMsg);
context.Response.Write(newsEncryptMsg);
context.Response.End();
break;
case "3":
string musicContent = Common.WeiXinOperation.GetMusicContent(openId, sendId);
string musicEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(musicContent, sReqTimeStamp, sReqNonce, ref musicEncryptMsg);
context.Response.Write(musicEncryptMsg);
context.Response.End();
break;
case "4":
string voiceContent = Common.WeiXinOperation.GetVoiceContent(openId, sendId);
string voiceEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(voiceContent, sReqTimeStamp, sReqNonce, ref voiceEncryptMsg);
context.Response.Write(voiceEncryptMsg);
context.Response.End();
break;
case "5":
string videoContent = Common.WeiXinOperation.GetVideoContent(openId, sendId);
string videoEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(videoContent, sReqTimeStamp, sReqNonce, ref videoEncryptMsg);
context.Response.Write(videoEncryptMsg);
context.Response.End();
break;
default:
string defaultContent = Common.WeiXinOperation.GetDefaultContent(openId, sendId);
string defaultEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(defaultContent, sReqTimeStamp, sReqNonce, ref defaultEncryptMsg);
context.Response.Write(defaultEncryptMsg);
context.Response.End();
break;
}
}
else if (msgType == "image")
{
string imageContent = Common.WeiXinOperation.GetImageContent(openId, sendId);
string imageEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(imageContent, sReqTimeStamp, sReqNonce, ref imageEncryptMsg);
context.Response.Write(imageEncryptMsg);
context.Response.End();
}
else if (msgType == "voice")
{
string voiceContent = Common.WeiXinOperation.GetVoiceContent(openId, sendId);
string voiceEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(voiceContent, sReqTimeStamp, sReqNonce, ref voiceEncryptMsg);
context.Response.Write(voiceEncryptMsg);
context.Response.End();
}
else if (msgType == "event")
{
//subscribe为关注,unsubscribe为取消关注
string getevent = rRoot["Event"].InnerText;
if (getevent == "subscribe")
{
//关注事件
string subscribeContent = Common.WeiXinOperation.GetSubscribeContent(openId, sendId);
string subscribeEncryptMsg = ""; //xml格式的密文
ret = wxcpt.EncryptMsg(subscribeContent, sReqTimeStamp, sReqNonce, ref subscribeEncryptMsg);
context.Response.Write(subscribeEncryptMsg);
context.Response.End();
}
}
else
{
string defaultContent = Common.WeiXinOperation.GetDefaultContent(openId, sendId);
context.Response.Write(defaultContent);
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}<file_sep>/Common/XmlOperation.cs
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Common
{
public class XmlOperation
{
public static Message XmlToEntity(string sMsg)
{
try
{
XmlDocument rdoc = new XmlDocument();
rdoc.LoadXml(sMsg);
XmlNode rRoot = rdoc.FirstChild;
Message model = new Message();
model.ToUserName = rRoot["ToUserName"].InnerText;
model.FromUserName = rRoot["FromUserName"].InnerText;
model.MsgId = rRoot["MsgId"].InnerText;
model.MsgType = rRoot["MsgType"].InnerText;
model.Content = rRoot["Content"].InnerText;
model.CreateTime = rRoot["CreateTime"].InnerText;
model.Type = "send";
return model;
}
catch (Exception ex)
{
Log.Error(ex.Message);
throw;
}
}
public static string GetMsgType(string sMsg)
{
try
{
string result = "";
if (!string.IsNullOrEmpty(sMsg))
{
XmlDocument rdoc = new XmlDocument();
rdoc.LoadXml(sMsg);
XmlNode rRoot = rdoc.FirstChild;
result = rRoot["MsgType"].InnerText;
}
return result;
}
catch (Exception ex)
{
Log.Error(ex.Message);
throw;
}
}
}
}
<file_sep>/Common/CnblogsOperation.cs
using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Common
{
public class CnblogsOperation
{
public static List<CnBlog> GetCnblogInfo()
{
try
{
/*
新闻目录
热门新闻:http://wcf.open.cnblogs.com/news/hot/10
数字表示当前页要加载的新闻数目
最近新闻:http://wcf.open.cnblogs.com/news/recent/10
数字表示当前页要加载的新闻数目
推荐新闻: http://wcf.open.cnblogs.com/news/recommend/paged/1/5
数字表示当前页要加载的新闻数目,可同过改变数字加载更多。
新闻内容
http://wcf.open.cnblogs.com/news/item/199054
数字表示要获取的当前新闻的id。
新闻评论
http://wcf.open.cnblogs.com/news/item/199054/comments/1/5
199054表示新闻id(新闻的id可以通过新闻目录接口获取的数据中获取),1表示评论的页数,5表示每页要加载的评论数。
博客目录
所有博客:1.http://wcf.open.cnblogs.com/blog/sitehome/recent/5。
2.http://wcf.open.cnblogs.com/blog/sitehome/paged/1/10
48小时阅读排行:http://wcf.open.cnblogs.com/blog/48HoursTopViewPosts/5
十天推荐排行: http://wcf.open.cnblogs.com/blog/TenDaysTopDiggPosts/5
5代表当前页要加载的数目,当前只能加一页,可以累加数字加载更多。
博客内容:http://wcf.open.cnblogs.com/blog/post/body/3535626
335626代表的博客的的id,博客id可以通过获取的博客目录中获得。
博客评论:http://wcf.open.cnblogs.com/blog/post/3535784/comments/1/5
335626代表的博客的的id,1代表页数,5代表当前页加载的评论数,可以他能够过改变1或者5来加载更多。
5.搜索博主
http://wcf.open.cnblogs.com/blog/bloggers/search?t=721881283
t后面跟的是博客园的帐号
*/
string blogUrl = "http://wcf.open.cnblogs.com/blog/sitehome/recent/5";
HttpWebRequest webRequest = WebRequest.Create(blogUrl) as HttpWebRequest;
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
string data = responseReader.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNode root = doc.DocumentElement;
XmlNodeList listNodes = root.ChildNodes;
List<CnBlog> cnblogs = new List<CnBlog>();
foreach (var item in listNodes)
{
XmlElement xe = item as XmlElement;
if (xe.Name == "entry")
{
CnBlog entry = new CnBlog();
foreach (XmlNode xmlNode in xe.ChildNodes)
{
if (xmlNode.Name == "id")
{
entry.ArticleId = xmlNode.InnerText;
}
if (xmlNode.Name == "title")
{
entry.Title = xmlNode.InnerText;
}
if (xmlNode.Name == "summary")
{
entry.Summary = xmlNode.InnerText;
}
if (xmlNode.Name == "link")
{
entry.Link = xmlNode.Attributes.Item(1).Value;
}
if (xmlNode.Name == "published")
{
entry.Published = xmlNode.InnerText;
}
if (xmlNode.Name == "updated")
{
entry.Updated = xmlNode.InnerText;
}
}
cnblogs.Add(entry);
}
}
//生成静态页
List<CnBlog> newListBlogs = new List<CnBlog>();
if (cnblogs != null && cnblogs.Count > 0)
{
newListBlogs = CnblogsOperation.GenerationBlogToHtml(cnblogs);
}
return newListBlogs;
//return cnblogs;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
throw;
}
}
public static List<CnBlog> GenerationBlogToHtml(List<CnBlog> listBlogs)
{
try
{
List<CnBlog> newListBlogs = new List<CnBlog>();
if (listBlogs != null && listBlogs.Count > 0)
{
foreach (var item in listBlogs)
{
string blogUrl = "http://wcf.open.cnblogs.com/blog/post/body/";
//HttpWebRequest webRequest = null;
//StreamReader responseReader = null;
//blogUrl += item.ArticleId;
//webRequest = WebRequest.Create(blogUrl) as HttpWebRequest;
//responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
//data = responseReader.ReadToEnd();
//XmlDocument doc = new XmlDocument();
//doc.LoadXml(data);
//XmlNode node = doc.SelectSingleNode("/string");
//string content = node.InnerText;
blogUrl += item.ArticleId;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(blogUrl);
HttpWebResponse res;
Encoding strEncode = Encoding.GetEncoding("UTF-8");
try
{
res = (HttpWebResponse)req.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr1 = new StreamReader(res.GetResponseStream(), strEncode);
string strHtml = sr1.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(strHtml);
XmlNode node = doc.SelectSingleNode("/string");
string content = node.InnerText;
//生成静态页
Encoding encode = Encoding.GetEncoding("UTF-8");
string htmlDir = AppDomain.CurrentDomain.BaseDirectory + "blogs\\";
if (!Directory.Exists(htmlDir))
{
Directory.CreateDirectory(htmlDir);
}
string templatePath = htmlDir + "template.html";
StreamReader sr = new StreamReader(templatePath, encode);
string templateText = sr.ReadToEnd();
string htmlText = templateText.Replace("@title@", item.Title);
htmlText = htmlText.Replace("@blogsUrl@", item.Link);
htmlText = htmlText.Replace("@content@", content);
string htmlfilename = item.ArticleId + ".html";
string htmlPath = htmlDir + htmlfilename;
StreamWriter sw = new StreamWriter(htmlPath, false, encode);
sw.Write(htmlText);
sw.Flush();
sr.Close();
sw.Close();
item.StaticLink = "http://www.litao.u-notebook.com/blogs/" + item.ArticleId + ".html";
newListBlogs.Add(item);
}
DAL.DataAcess.AddBlogs(newListBlogs);
//return newListBlogs;
}
return newListBlogs;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
throw;
}
}
}
}
<file_sep>/Common/WeiXinOperation.cs
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public class WeiXinOperation
{
/// <summary>
/// 验证url权限, 接入服务器
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public static bool ValidUrl(string token, string echoStr, string signature, string timestamp, string nonce)
{
try
{
if (CheckSignature(token, signature, timestamp, nonce))
{
if (!string.IsNullOrEmpty(echoStr))
{
//Utils.ResponseWrite(echoStr);
return true;
}
}
return false;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
throw;
}
}
/// <summary>
/// 验证微信签名
/// </summary>
/// * 将token、timestamp、nonce三个参数进行字典序排序
/// * 将三个参数字符串拼接成一个字符串进行sha1加密
/// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
/// <returns></returns>
private static bool CheckSignature(string token, string signature, string timestamp, string nonce)
{
try
{
string[] ArrTmp = { token, timestamp, nonce };
Array.Sort(ArrTmp); //字典排序
string tmpStr = string.Join("", ArrTmp);
tmpStr = HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
Common.Log.Error("tmpStr=" + tmpStr);
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
throw;
}
}
/// <summary>
/// 根据指定的密码和哈希算法生成一个适合于存储在配置文件中的哈希密码
/// </summary>
/// <param name="str">要进行哈希运算的密码</param>
/// <param name="type"> 要使用的哈希算法</param>
/// <returns>经过哈希运算的密码</returns>
private static string HashPasswordForStoringInConfigFile(string str, string type)
{
return HashPasswordForStoringInConfigFile(str, type);
}
/// <summary>
/// 获取关注回复内容
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetSubscribeContent(string openId, string sendId)
{
string result = "";
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
string items = GetSubscribeItem();
StringBuilder sb = new StringBuilder();
string msgType = "news";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<ArticleCount>");
sb.Append("1");
sb.Append("</ArticleCount>");
sb.Append("<Articles>");
sb.Append(items);
sb.Append("</Articles>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
private static string GetSubscribeItem()
{
StringBuilder sb = new StringBuilder();
sb.Append("<item>");
sb.Append("<Title><![CDATA[");
sb.Append("欢迎关注海霓科技,u-notebook改变你的生活");
sb.Append("]]></Title>");
sb.Append("<Description><![CDATA[");
sb.Append("最省时间:操作简单 提高工作效率,掌握时间,才能掌握未来。信息时代,速度就是财富。 在数码本上随心书写的同时,也可保存成电子文档。整篇手写真迹一次识别成电子文档,免去重新打字输入的麻烦,为工作节省更多时间,提高工作效率");
sb.Append("]]></Description>");
sb.Append("<PicUrl><![CDATA[");
sb.Append("http://mmbiz.qpic.cn/mmbiz/fBhianiadNmOG6Z27rpNtq27iaQXaUEmArd4UTicaxRAks3nYS1hmtcnqusBiaZvlXyibyQOPvsnMCQkgJlXzSBjWsmA/0");
sb.Append("]]></PicUrl>");
sb.Append("<Url><![CDATA[");
sb.Append("http://www.u-notebook.com");
sb.Append("]]></Url>");
sb.Append("</item>");
return sb.ToString();
}
/// <summary>
/// 获取默认回复内容
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetDefaultContent(string openId, string sendId)
{
string result = "";
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
StringBuilder sb = new StringBuilder();
string content = "回复[1]查看文本消息\r\n回复[2]查看图文消息\r\n回复[3]听首歌吧\r\n回复[4]听听故事\r\n回复[5]看段激情小视频";
string msgType = "text";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<Content><![CDATA[");
sb.Append(content);
sb.Append("]]></Content>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
/// <summary>
/// 获取文本信息
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetTextContent(string openId, string sendId)
{
string result = "";
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
StringBuilder sb = new StringBuilder();
string content = "您好!我是马兄,现在给你返回的是文本信息";
string msgType = "text";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<Content><![CDATA[");
sb.Append(content);
sb.Append("]]></Content>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
/// <summary>
/// 获取图片信息
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetImageContent(string openId, string sendId)
{
string result = "";
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
StringBuilder sb = new StringBuilder();
string picUrl = "http://mmbiz.qpic.cn/mmbiz/fBhianiadNmOG6Z27rpNtq27iaQXaUEmArdpWWdtnlrOnQic1DPNGUxLS2VVLVTUeFibqtAviclK7UduGBKmTQCfZ9Gw/0";
string mediaId = "Jj8xFxZUhi-JIrZ-0LhJSqK1ZIx8rUzVmqaVP_6GjsVV-3UB839dAE25OL3DAD9Q";
string msgType = "image";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<Image>");
sb.Append("<MediaId><![CDATA[");
sb.Append(mediaId);
sb.Append("]]></MediaId>");
sb.Append("</Image>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
/// <summary>
/// 获取图文信息
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetNewsContent(string openId, string sendId)
{
string result = "";
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
List<CnBlog> list = CnblogsOperation.GetCnblogInfo();
int count = 0;
string items = GetPicContent(list, out count);
StringBuilder sb = new StringBuilder();
string msgType = "news";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<ArticleCount>");
sb.Append(count);
sb.Append("</ArticleCount>");
sb.Append("<Articles>");
sb.Append(items);
sb.Append("</Articles>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
/// <summary>
/// 获取音乐信息
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetMusicContent(string openId, string sendId)
{
string result = "";
List<CnBlog> listBlogs = null;
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
List<CnBlog> list = CnblogsOperation.GetCnblogInfo();
int count = 0;
string items = GetPicContent(list, out count);
StringBuilder sb = new StringBuilder();
string msgType = "music";
string musicTitle = "我的歌声里";
string description = "曲婉婷";
string musicUrl = "http://weixincourse-weixincourse.stor.sinaapp.com/mysongs.mp3";
string hqMusicUrl = "http://weixincourse-weixincourse.stor.sinaapp.com/mysongs.mp3";
string thumbMediaId = "Jj8xFxZUhi-JIrZ-0LhJSqK1ZIx8rUzVmqaVP_6GjsVV-3UB839dAE25OL3DAD9Q";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<Music>");
sb.Append("<Title><![CDATA[");
sb.Append(musicTitle);
sb.Append("]]></Title>");
sb.Append("<Description><![CDATA[");
sb.Append(description);
sb.Append("]]></Description>");
sb.Append("<MusicUrl><![CDATA[");
sb.Append(musicUrl);
sb.Append("]]></MusicUrl>");
sb.Append("<HQMusicUrl><![CDATA[");
sb.Append(hqMusicUrl);
sb.Append("]]></HQMusicUrl>");
sb.Append("<ThumbMediaId><![CDATA[");
sb.Append(thumbMediaId);
sb.Append("]]></ThumbMediaId>");
sb.Append("</Music>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
listBlogs = list;
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
/// <summary>
/// 获取语音信息
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetVoiceContent(string openId, string sendId)
{
string result = "";
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
List<CnBlog> list = CnblogsOperation.GetCnblogInfo();
int count = 0;
string items = GetPicContent(list, out count);
StringBuilder sb = new StringBuilder();
string msgType = "voice";
string media_id = "HmFJuR3GgK3Ip8G6_Yj-wDXx4k2OmApgYTDbiB6j6bL2DzKjWSX7c1wyWQ48v3Nj";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<Voice>");
sb.Append("<MediaId><![CDATA[");
sb.Append(media_id);
sb.Append("]]></MediaId>");
sb.Append("</Voice>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
/// <summary>
/// 获取视频信息
/// </summary>
/// <param name="openId">微信接收者</param>
/// <param name="sendId">微信发送者</param>
/// <returns></returns>
public static string GetVideoContent(string openId, string sendId)
{
string result = "";
try
{
if (!string.IsNullOrEmpty(openId) && !string.IsNullOrEmpty(sendId))
{
List<CnBlog> list = CnblogsOperation.GetCnblogInfo();
int count = 0;
string items = GetPicContent(list, out count);
StringBuilder sb = new StringBuilder();
string msgType = "video";
string title = "张国荣《这些年来》";
string description = "经典!张国荣《这些年来》唱尽深情与眷恋!(他的离去,从未让他远去!)";
string media_id = "204128847";
sb.Append("<xml><ToUserName><![CDATA[");
sb.Append(openId);
sb.Append("]]></ToUserName><FromUserName><![CDATA[");
sb.Append(sendId);
sb.Append("]]></FromUserName><CreateTime>");
sb.Append(GetTimeStamp());
sb.Append("</CreateTime><MsgType><![CDATA[");
sb.Append(msgType);
sb.Append("]]></MsgType>");
sb.Append("<Video>");
sb.Append("<MediaId><![CDATA[");
sb.Append(media_id);
sb.Append("]]></MediaId>");
sb.Append("<Title><![CDATA[");
sb.Append(title);
sb.Append("]]></Title>");
sb.Append("<Description><![CDATA[");
sb.Append(description);
sb.Append("]]></Description>");
sb.Append("</Video>");
sb.Append("<MsgId></MsgId></xml>");
result = sb.ToString();
}
return result;
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
return result;
}
}
private static string GetPicContent(List<CnBlog> list, out int count)
{
try
{
string[] picArray = new string[] {
"http://mmbiz.qpic.cn/mmbiz/fBhianiadNmOG6Z27rpNtq27iaQXaUEmArd4UTicaxRAks3nYS1hmtcnqusBiaZvlXyibyQOPvsnMCQkgJlXzSBjWsmA/0",
"http://mmbiz.qpic.cn/mmbiz/fBhianiadNmOG6Z27rpNtq27iaQXaUEmArdjChgRUTGaiaZQq38g2DCo3Saxy0HLI9wuIPx5GKFTgVcUyiaxQZfgfYw/0",
"http://mmbiz.qpic.cn/mmbiz/fBhianiadNmOG6Z27rpNtq27iaQXaUEmArdGea4gmzcN16xjTfq4ia36ibiag208muqwpw087Pl2ZOpxaQCVGhgcPxiaw/0",
"http://mmbiz.qpic.cn/mmbiz/fBhianiadNmOG6Z27rpNtq27iaQXaUEmArdnxTiapJfD9KD50GdbckzBjkOqxAraxgJrOjIGteJtBcvd0Au7WPWK7g/0",
"http://mmbiz.qpic.cn/mmbiz/fBhianiadNmOG6Z27rpNtq27iaQXaUEmArdBRRmlrvY6JiaS4leULRklptSd9vVtAe8ZhXCsuPu9DtFdOPy3dC8SHA/0"
};
StringBuilder sb = new StringBuilder();
if (list != null && list.Count > 0)
{
count = list.Count();
int i = 0;
foreach (var item in list)
{
sb.Append("<item>");
sb.Append("<Title><![CDATA[");
sb.Append(item.Title);
sb.Append("]]></Title>");
sb.Append("<Description><![CDATA[");
sb.Append(item.Summary);
sb.Append("]]></Description>");
sb.Append("<PicUrl><![CDATA[");
sb.Append(picArray[i]);
sb.Append("]]></PicUrl>");
sb.Append("<Url><![CDATA[");
sb.Append(item.StaticLink);
sb.Append("]]></Url>");
sb.Append("</item>");
i++;
if (i > 4)
{
i = 0;
}
}
}
else
{
count = 0;
}
return sb.ToString();
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
private static string GetTimeStamp()
{
try
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>/DAL/DataAcess.cs
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class DataAcess
{
static WeiXinEntities db = new WeiXinEntities();
public static int Add(Message model)
{
db.Message.Add(model);
return db.SaveChanges();
}
public static IEnumerable<Message> GetAllEntitys()
{
return db.Message.Where(c => c.Id != 0);
}
public static int AddBlogs(List<CnBlog> blogs)
{
try
{
if (blogs != null && blogs.Count > 0)
{
foreach (var item in blogs)
{
if (db.CnBlog.Where(c => c.ArticleId == item.ArticleId).Count() > 0)
{
continue;
}
else
{
db.CnBlog.Add(item);
}
}
return db.SaveChanges();
}
else
{
return 0;
}
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>/weixin/Controllers/WeiXinController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace weixin.Controllers
{
public class WeiXinController : Controller
{
// GET: WeiXin guPAaeyJM4yUGljNJgRfo8V4Uk0IUX3RCp477cBtPQY
public ActionResult Index()
{
try
{
//测试静态页
//int i = Common.CnblogsOperation.GenerationBlogToHtml(Common.CnblogsOperation.GetCnblogInfo());
var datas = DAL.DataAcess.GetAllEntitys().ToList();
ViewBag.Data = datas;
return View();
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
throw;
}
}
public JsonResult GetMsg()
{
try
{
var datas = DAL.DataAcess.GetAllEntitys().ToList();
return Json(datas, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Common.Log.Error(ex.Message);
throw;
}
}
}
} | 44b9c683c6a4211facf59795d9b8854b1e7e306f | [
"C#"
] | 7 | C# | litao527/WeiXin | e738ce532245e27dd658ec530420e00619c2a482 | 526923b1424dbf4b7c32ea3934c461651b0eb138 |
refs/heads/master | <repo_name>spotomatic/GlanceMaps-ino<file_sep>/hud_ino_oled.ino
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "base64.hpp"
//#include <SoftwareSerial.h>
//SoftwareSerial BTSerial(10, 11); // RX | TX
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define buffLength 256
char buff[buffLength];
int buffOffset = 0;
const unsigned char glanceMapsIcon [] PROGMEM = {
0x1f, 0xff, 0xff, 0xf8, 0x3f, 0xff, 0xff, 0xfc, 0x7f, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xc7, 0xff, 0xf8, 0xef, 0xc3, 0xff, 0xf0, 0xc7, 0x83, 0xff, 0xf0, 0x83, 0x83, 0xff,
0xf1, 0x83, 0x01, 0xff, 0xe1, 0x03, 0x01, 0xff, 0xe1, 0x06, 0x00, 0xff, 0xc3, 0x06, 0x00, 0xff,
0xc2, 0x06, 0x00, 0x7f, 0xc6, 0x0c, 0x00, 0x7f, 0x84, 0x0c, 0x00, 0x7f, 0xc4, 0x18, 0x00, 0x3f,
0xec, 0x18, 0x00, 0x3f, 0xf8, 0x30, 0x00, 0x1f, 0xf8, 0x30, 0x00, 0x1f, 0xf8, 0x30, 0x00, 0x0f,
0xf8, 0x60, 0x00, 0x0f, 0xfd, 0xe0, 0x00, 0x0f, 0xff, 0xc0, 0x00, 0x07, 0xff, 0xc0, 0x00, 0x07,
0xff, 0x80, 0x00, 0x03, 0xff, 0x80, 0x00, 0x03, 0xff, 0x80, 0x7c, 0x03, 0xff, 0x83, 0xff, 0x83,
0xff, 0xdf, 0xff, 0xf7, 0x7f, 0xff, 0xff, 0xfe, 0x3f, 0xff, 0xff, 0xfc, 0x1f, 0xff, 0xff, 0xf8
};
void setup() {
Serial.begin(9600);
// BTSerial.begin(9600); // HC-05 default speed in AT command more
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.display();
display.cp437(true); // Use full 256 char 'Code Page 437' font
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Draw white text
Serial.println("STARTED");
}
long lastCmdMs = millis();
void loop(){
if (millis() - lastCmdMs > 5000) {
display.clearDisplay();
lastCmdMs = millis();
display.setTextSize(2); // Normal 1:1 pixel scale
display.setCursor(0, 0);
display.println("Glance");
display.setTextSize(1); // Normal 1:1 pixel scale
display.setCursor(0, 15);
display.println("Maps");
display.drawBitmap(
128-32,
0,
glanceMapsIcon, 32, 32, 1);
display.display();
}
if (Serial.available()) {
String s1 = Serial.readStringUntil('\0');
processCommand(s1);
}
// while (Serial.available()) {
// char character = Serial.read();
//
// if (character == '\0' || character == '\n') {
// buff[buffOffset+1] = '\0';
// buffOffset = 0;
//
// processCommand(String(buff));
// break;
// } else {
// buff[buffOffset] = character;
// buffOffset++;
// }
// }
}
void drawPerLine(String cmd, unsigned int line) {
char *idk; // Karna nested strtok, perlu make strtok_r
int l = cmd.length() + 1;
char str[l];
cmd.toCharArray(str,l);
char delim[] = ",";
char *ptr = strtok_r(str, delim, &idk);
// Nilai pertama
int _start = String(ptr).toInt();
// Nilai kedua
ptr = strtok_r(NULL, delim, &idk);
int _end = String(ptr).toInt();
// Warna
ptr = strtok_r(NULL, delim, &idk);
String _warna = String(ptr);
//
// Serial.print("ENTAH ");
// Serial.print(_start);
// Serial.print(" ");
// Serial.print(_end);
// Serial.print(" ");
// Serial.println(_warna);
if (_warna == "w") {
display.drawLine(128-32 + _start, line, 128-32 + _end, line, SSD1306_WHITE);
} else {
display.drawLine(128-32 + _start, line, 128-32 + _end, line, SSD1306_BLACK);
}
}
void processCommand(String cmd) {
// Serial.println(cmd);
lastCmdMs = millis();
if (cmd[0] == 'a') {
display.setTextSize(2); // Normal 1:1 pixel scale
display.fillRect(0,0,96,15,SSD1306_BLACK); // Untuk ngeclear
display.setCursor(0, 0);
display.println(cmd.substring(1));
display.display();
}
if (cmd[0] == 'b') {
display.setTextSize(1); // Normal 1:1 pixel scale
display.fillRect(0,15,96,10,SSD1306_BLACK); // Untuk ngeclear
display.setCursor(0, 15);
display.println(cmd.substring(1));
display.display();
}
if (cmd[0] == 'd') {
display.setTextSize(1); // Normal 1:1 pixel scale
display.fillRect(0,24,96,8,SSD1306_BLACK); // Untuk ngeclear
display.setCursor(0, 24);
display.println(cmd.substring(1));
display.display();
}
if (cmd[0] == 'c') {
int _fromIn = cmd.indexOf(':') - 1;
String _offStr = cmd.substring(1, _fromIn + 1);
int _from = _offStr.toInt();
// Ini untuk ngerequest line selanjutnya, DIPERLUKAN
Serial.println("c" + _offStr + ":");
String renderCmd = cmd.substring(_fromIn+2);
int renderCmdLen = renderCmd.length() + 1;
char renderChar[renderCmdLen];
renderCmd.toCharArray(renderChar, renderCmdLen);
// Serial.println(renderChar);
char delim[] = " ";
char *ptr = strtok(renderChar, delim);
while(ptr != NULL)
{
// Serial.println(ptr);
drawPerLine(String(ptr), _from);
ptr = strtok(NULL, delim);
}
display.display();
}
}
| faadce08d511ab7acc3cf37811a79d0dbe6b3873 | [
"C++"
] | 1 | C++ | spotomatic/GlanceMaps-ino | ed47bea31af8d3617c7dd7e05199a64dd9eefd62 | 7da03a75ae02051ddc89b959d3d9aed2639ffe9a |
refs/heads/master | <file_sep>import * as assert from 'power-assert';
import * as sinon from 'sinon';
import { conditional } from '../src/index';
function createClassDecorator(name: string, value: string): (clazz: Function) => Function {
'use strict';
return clazz => {
clazz.prototype[name] = value;
return clazz;
};
}
let statusDecorator = createClassDecorator('status', 'status 1');
let spyWithTrue = sinon.spy(statusDecorator);
let spyWithFalse = sinon.spy(statusDecorator);
@conditional(true, spyWithTrue)
class ClazzSpiedWithTrue {
status: string;
}
@conditional(false, spyWithFalse)
class ClazzSpiedWithFalse {
status: string;
}
function checkClassName(clazz: Function): boolean {
'use strict';
return (<any>clazz).name === 'ClassSpiedWithFunctionReturningTrue';
}
let statusDecorator2 = createClassDecorator('status', 'status 2');
let spyWithFunctionReturningTrue = sinon.spy(statusDecorator2);
let spyWithFunctionReturningFalse = sinon.spy(statusDecorator2);
@conditional(checkClassName, spyWithFunctionReturningTrue)
class ClassSpiedWithFunctionReturningTrue {
status: string;
}
@conditional(checkClassName, spyWithFunctionReturningFalse)
class ClassSpiedWithFunctionReturningFalse {
status: string;
}
let deepDecorator = createClassDecorator('status', 'yes');
let deepSpy = sinon.spy(deepDecorator);
@conditional(
true,
conditional(
true,
conditional(
true,
conditional(
true,
deepSpy
)
)
)
)
class HeavilyDecoratedClass {
status: string;
}
describe('conditional', () => {
describe('as class decorator', () => {
describe('(test: boolean, decorator: ClassDecorator) => ClassDecorator', () => {
it('decorates if test is truthy', () => {
assert(spyWithTrue.callCount === 1);
assert(new ClazzSpiedWithTrue().status === 'status 1');
assert(deepSpy.callCount === 1);
assert(new HeavilyDecoratedClass().status === 'yes');
});
it('doesn\'t decorate if test is falsy', () => {
assert(spyWithFalse.callCount === 0);
assert(new ClazzSpiedWithFalse().status === undefined);
});
});
describe('(test: (clazz?: Function) => boolean, decorator: ClassDecorator): ClassDecorator', () => {
it('decorates if test function returns true', () => {
assert(spyWithFunctionReturningTrue.callCount === 1);
assert(new ClassSpiedWithFunctionReturningTrue().status === 'status 2');
});
it('doesn\'t decorate if test function returns false', () => {
assert(spyWithFunctionReturningFalse.callCount === 0);
assert(new ClassSpiedWithFunctionReturningFalse().status === undefined);
});
});
});
});
<file_sep>import * as assert from 'power-assert';
import * as sinon from 'sinon';
import { conditional } from '../src/index';
function createParameterDecorator(spy: Sinon.SinonSpy): ParameterDecorator {
'use strict';
return function decorator(target: Object, propertyKey: string|symbol, parameterIndex: number): void {
'use strict';
spy.apply(spy, arguments);
};
}
const spy1 = sinon.spy();
const decor1 = createParameterDecorator(spy1);
const spy2 = sinon.spy();
const decor2 = createParameterDecorator(spy2);
const spy3 = sinon.spy();
const decor3 = createParameterDecorator(spy3);
const spy4 = sinon.spy();
const decor4 = createParameterDecorator(spy4);
const spy5 = sinon.spy();
const decor5 = createParameterDecorator(spy5);
const spy6 = sinon.spy();
const decor6 = createParameterDecorator(spy6);
function testParameter(target: Object, propertyKey: string|symbol, parameterIndex: number): boolean {
'use strict';
return propertyKey === 'methodOk' && parameterIndex === 1;
}
class TargetClass {
method1(@conditional(true, decor1) param1: number,
@conditional(false, decor2) param2: string) {
return;
}
methodOk(@conditional(testParameter, decor3) param1: number,
@conditional(testParameter, decor4) param2: string) {
return;
}
methodNg(@conditional(testParameter, decor5) param1: number,
@conditional(testParameter, decor6) param2: string) {
return;
}
}
describe('conditional', () => {
describe('as parameter decorator', () => {
describe('(test: boolean, decorator: ParameterDecorator): ParameterDecorator', () => {
it('decorates if test is truthy', () => {
assert(spy1.callCount === 1);
assert(spy1.getCall(0).args[0] === TargetClass.prototype);
assert(spy1.getCall(0).args[1] === 'method1');
assert(spy1.getCall(0).args[2] === 0);
});
it('doesn\'t decorate if test is falsy', () => {
assert(spy2.callCount === 0);
});
});
describe(
'(test: (target?: Object, key?: string|symbol, index?: number) => boolean, decorator: ParameterDecorator): ParameterDecorator',
() => {
it('decorates if test function returns true', () => {
assert(spy4.callCount === 1);
assert(spy4.getCall(0).args[0] === TargetClass.prototype);
assert(spy4.getCall(0).args[1] === 'methodOk');
assert(spy4.getCall(0).args[2] === 1);
});
it('doesn\'t decorate if test function returns false', () => {
assert(spy3.callCount === 0);
assert(spy5.callCount === 0);
assert(spy6.callCount === 0);
});
});
});
});
<file_sep>export interface ClassDecorator {
<TFunction extends Function>(target: TFunction): TFunction | void;
}
export interface PropertyDecorator {
(target: Object, propertyKey: string | symbol): void;
}
export interface MethodDecorator {
<T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;
}
export interface ParameterDecorator {
(target: Object, propertyKey: string | symbol, parameterIndex: number): void;
}
/**
* Enum for decorator type
*/
export declare enum DecoratorType {
Class = 0,
Parameter = 1,
Property = 2,
Method = 3,
None = 4,
}
/**
* Guesses which kind of decorator from its functional arguments
* @param args
* @returns {DecoratorType}
*/
export declare function getDecoratorTypeFromArguments(args: IArguments): DecoratorType;
/**
* Guesses whether the given function is a class decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export declare function isClassDecorator(decorator: Function, args: IArguments): decorator is ClassDecorator;
/**
* Guesses whether the given function is a method parameter decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export declare function isParameterDecorator(decorator: Function, args: IArguments): decorator is ParameterDecorator;
/**
* Guesses whether the given function is a property decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export declare function isPropertyDecorator(decorator: Function, args: IArguments): decorator is PropertyDecorator;
/**
* Guesses whether the given function is a method decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export declare function isMethodDecorator(decorator: Function, args: IArguments): decorator is MethodDecorator;
<file_sep>import * as utils from './utils';
/**
* Apply `decorator` on a class if `test` is true
* @param test
* @param decorator
*/
function conditional(test: boolean, decorator: ClassDecorator): ClassDecorator;
/**
* Apply `decorator` on a class if `test` function returns true
* @param test function which receives a target class itself as an argument and returns boolean value
* @param decorator
*/
function conditional(test: (clazz?: Function) => boolean, decorator: ClassDecorator): ClassDecorator;
/**
* Apply `decorator` on a property if `test` is true
* @param test
* @param decorator
*/
function conditional(test: boolean, decorator: PropertyDecorator): PropertyDecorator;
/**
* Apply `decorator` on a property if `test` function returns true
* @param test function which receives a class' prototype and property name as arguments and returns boolean value
* @param decorator
*/
function conditional(test: (target?: Object, key?: string|symbol) => boolean,
decorator: PropertyDecorator): PropertyDecorator;
/**
* Apply `decorator` on a method parameter if `test` is true
* @param test
* @param decorator
*/
function conditional(test: boolean, decorator: ParameterDecorator): ParameterDecorator;
/**
* Apply `decorator` on a method parameter if `test` function returns true
* @param test function which receives a class' prototype, property name and parameter position as arguments and returns boolean value
* @param decorator
*/
function conditional(test: (target?: Object, key?: string|symbol, index?: number) => boolean,
decorator: ParameterDecorator): ParameterDecorator;
/**
* Apply `decorator` on a method (which includes property accessor) if `test` is true
* @param test
* @param decorator
*/
function conditional(test: boolean, decorator: MethodDecorator): MethodDecorator;
/**
* Apply `decorator` on a method (which includes property accessor) if `test` function returns true
* @param test function which receives a class' prototype, method name and property descriptor as arguments and returns boolean value
* @param decorator
*/
function conditional(test: (target?: Object, key?: string|symbol, desc?: PropertyDescriptor) => boolean,
decorator: MethodDecorator): MethodDecorator;
function conditional(test: any, decorator: Function): any {
'use strict';
return function (target: Object, key: string|symbol, value: any): any {
if (utils.isClassDecorator(decorator, arguments)) {
let clazz: Function = target as Function;
let shouldDecorate: boolean = typeof test === 'function' ? test(clazz) : test;
if (shouldDecorate && decorator) {
return decorator(clazz);
}
return clazz;
}
if (utils.isParameterDecorator(decorator, arguments)) {
let index: number = value as number;
let shouldDecorate: boolean = typeof test === 'function' ? test(target, key, index) : test;
if (shouldDecorate && decorator) {
decorator(target, key, index);
}
}
if (utils.isPropertyDecorator(decorator, arguments)) {
let shouldDecorate: boolean = typeof test === 'function' ? test(target, key) : test;
if (shouldDecorate && decorator) {
decorator(target, key);
}
}
if (utils.isMethodDecorator(decorator, arguments)) {
let desc: PropertyDescriptor = value as PropertyDescriptor;
let shouldDecorate: boolean = typeof test === 'function' ? test(target, key, desc) : test;
if (shouldDecorate && decorator) {
return decorator(target, key, desc);
}
return desc;
}
};
}
export default conditional;
<file_sep>/**
* Apply `decorator` on a class if `test` is true
* @param test
* @param decorator
*/
declare function conditional(test: boolean, decorator: ClassDecorator): ClassDecorator;
/**
* Apply `decorator` on a class if `test` function returns true
* @param test function which receives a target class itself as an argument and returns boolean value
* @param decorator
*/
declare function conditional(test: (clazz?: Function) => boolean, decorator: ClassDecorator): ClassDecorator;
/**
* Apply `decorator` on a property if `test` is true
* @param test
* @param decorator
*/
declare function conditional(test: boolean, decorator: PropertyDecorator): PropertyDecorator;
/**
* Apply `decorator` on a property if `test` function returns true
* @param test function which receives a class' prototype and property name as arguments and returns boolean value
* @param decorator
*/
declare function conditional(test: (target?: Object, key?: string | symbol) => boolean, decorator: PropertyDecorator): PropertyDecorator;
/**
* Apply `decorator` on a method parameter if `test` is true
* @param test
* @param decorator
*/
declare function conditional(test: boolean, decorator: ParameterDecorator): ParameterDecorator;
/**
* Apply `decorator` on a method parameter if `test` function returns true
* @param test function which receives a class' prototype, property name and parameter position as arguments and returns boolean value
* @param decorator
*/
declare function conditional(test: (target?: Object, key?: string | symbol, index?: number) => boolean, decorator: ParameterDecorator): ParameterDecorator;
/**
* Apply `decorator` on a method (which includes property accessor) if `test` is true
* @param test
* @param decorator
*/
declare function conditional(test: boolean, decorator: MethodDecorator): MethodDecorator;
/**
* Apply `decorator` on a method (which includes property accessor) if `test` function returns true
* @param test function which receives a class' prototype, method name and property descriptor as arguments and returns boolean value
* @param decorator
*/
declare function conditional(test: (target?: Object, key?: string | symbol, desc?: PropertyDescriptor) => boolean, decorator: MethodDecorator): MethodDecorator;
export default conditional;
<file_sep># Conditional Decorator
[](http://badge.fury.io/js/conditional-decorator)
[](https://travis-ci.org/tkqubo/conditional-decorator)

[](https://codeclimate.com/github/tkqubo/conditional-decorator/coverage)
[](https://codeclimate.com/github/tkqubo/conditional-decorator)
[](http://doge.mit-license.org)
A decorator which can wrap other decorator
## Installation
```sh
npm install conditional-decorator
```
## Usage
```js
import { conditional } from 'conditional-decorator';
import { logger } from './logger';
class Foo {
@logger
bar() {
// ...
}
@conditional(__DEBUG__, logger)
baz() {
// ...
}
}
```
## API
You can read [TypeDoc](http://typedoc.io/)-generated documentation [here](http://tkqubo.github.io/conditional-decorator/)
## Using with TypeScript
*TBD*
## Todo
- Test for:
- Object Literal Method Declaration
- Object Literal Accessor Declaration
Both are unavailable in TypeScript 1.6.2, so test should be done in Babel with `es6.decorators` option
<file_sep>import * as assert from 'power-assert';
import * as sinon from 'sinon';
import { conditional } from '../src/index';
enum PropertyType {
Set, Get, Value,
}
function getDecoratee<T>(type: PropertyType, descriptor: TypedPropertyDescriptor<T>): any {
'use strict';
switch (type) {
case PropertyType.Get:
return descriptor.get;
case PropertyType.Set:
return descriptor.set;
case PropertyType.Value:
return descriptor.value;
default:
return null;
}
}
function setDecoratee<T>(type: PropertyType, descriptor: TypedPropertyDescriptor<T>, decoratee: any): any {
'use strict';
switch (type) {
case PropertyType.Get:
descriptor.get = decoratee;
return;
case PropertyType.Set:
descriptor.set = decoratee;
return;
case PropertyType.Value:
descriptor.value = decoratee;
return;
default:
return;
}
}
function createSideEffectMethodDecorator(applicationSpy: Sinon.SinonSpy,
invocationSpy: Sinon.SinonSpy,
type: PropertyType): MethodDecorator {
'use strict';
return function <T>(target: Object,
propertyKey: string|symbol,
descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> {
'use strict';
applicationSpy.apply(applicationSpy, arguments);
let decoratee = getDecoratee(type, descriptor);
setDecoratee(type, descriptor, (...args: any[]) => {
invocationSpy.apply(invocationSpy, args);
return decoratee.call(target, ...args);
});
return descriptor;
};
}
function testMethodName(target?: Object, key?: string|symbol, desc?: PropertyDescriptor): boolean {
'use strict';
return key === 'decoratableMethod';
}
const applicationSpy1 = sinon.spy();
const invocationSpy1 = sinon.spy();
const instanceMethodSpy1 = sinon.spy();
const decor1 = createSideEffectMethodDecorator(applicationSpy1, invocationSpy1, PropertyType.Value);
const applicationSpy2 = sinon.spy();
const invocationSpy2 = sinon.spy();
const instanceMethodSpy2 = sinon.spy();
const decor2 = createSideEffectMethodDecorator(applicationSpy2, invocationSpy2, PropertyType.Value);
const applicationSpy3 = sinon.spy();
const invocationSpy3 = sinon.spy();
const instanceMethodSpy3 = sinon.spy();
const decor3 = createSideEffectMethodDecorator(applicationSpy3, invocationSpy3, PropertyType.Value);
const applicationSpy4 = sinon.spy();
const invocationSpy4 = sinon.spy();
const instanceMethodSpy4 = sinon.spy();
const decor4 = createSideEffectMethodDecorator(applicationSpy4, invocationSpy4, PropertyType.Value);
const applicationSpy5 = sinon.spy();
const invocationSpy5 = sinon.spy();
const instanceMethodSpy5 = sinon.spy();
const decor5 = createSideEffectMethodDecorator(applicationSpy5, invocationSpy5, PropertyType.Get);
const applicationSpy6 = sinon.spy();
const invocationSpy6 = sinon.spy();
const instanceMethodSpy6 = sinon.spy();
const decor6 = createSideEffectMethodDecorator(applicationSpy6, invocationSpy6, PropertyType.Get);
const applicationSpy7 = sinon.spy();
const invocationSpy7 = sinon.spy();
const instanceMethodSpy7 = sinon.spy();
const decor7 = createSideEffectMethodDecorator(applicationSpy7, invocationSpy7, PropertyType.Set);
const applicationSpy8 = sinon.spy();
const invocationSpy8 = sinon.spy();
const instanceMethodSpy8 = sinon.spy();
const decor8 = createSideEffectMethodDecorator(applicationSpy8, invocationSpy8, PropertyType.Set);
class TargetClass {
@conditional(true, decor1)
method1(name: string) {
instanceMethodSpy1.apply(instanceMethodSpy1, arguments);
}
@conditional(false, decor2)
method2(name: string) {
instanceMethodSpy2.apply(instanceMethodSpy2, arguments);
}
@conditional(testMethodName, decor3)
decoratableMethod(name: string) {
instanceMethodSpy3.apply(instanceMethodSpy3, arguments);
}
@conditional(testMethodName, decor4)
undecoratableMethod(name: string) {
instanceMethodSpy4.apply(instanceMethodSpy4, arguments);
}
@conditional(true, decor5)
get age(): number {
instanceMethodSpy5.apply(instanceMethodSpy5, arguments);
return 42;
}
@conditional(false, decor6)
get sex(): boolean {
instanceMethodSpy6.apply(instanceMethodSpy6, arguments);
return true;
}
@conditional(true, decor7)
set id(id: number) {
instanceMethodSpy7.apply(instanceMethodSpy7, arguments);
}
@conditional(false, decor8)
set country(country: string) {
instanceMethodSpy8.apply(instanceMethodSpy8, arguments);
}
}
describe('conditional', () => {
describe('as a method decorator', () => {
describe('(test: boolean, decorator: MethodDecorator): MethodDecorator', () => {
describe('for ordinary method', () => {
it('decorates if test is truthy', () => {
assert(applicationSpy1.callCount === 1);
assert(applicationSpy1.getCall(0).args[0] === TargetClass.prototype);
assert(applicationSpy1.getCall(0).args[1] === 'method1');
assert(invocationSpy1.callCount === 0);
assert(instanceMethodSpy1.callCount === 0);
new TargetClass().method1('hello');
assert(invocationSpy1.callCount === 1);
assert(invocationSpy1.getCall(0).args.length === 1);
assert(invocationSpy1.getCall(0).args[0] === 'hello');
assert(instanceMethodSpy1.callCount === 1);
assert(instanceMethodSpy1.getCall(0).args.length === 1);
assert(instanceMethodSpy1.getCall(0).args[0] === 'hello');
});
it('doesn\'t decorate if test is falsy', () => {
assert(applicationSpy2.callCount === 0);
assert(invocationSpy2.callCount === 0);
assert(instanceMethodSpy2.callCount === 0);
new TargetClass().method2('world');
assert(applicationSpy2.callCount === 0);
assert(invocationSpy2.callCount === 0);
assert(instanceMethodSpy2.callCount === 1);
assert(instanceMethodSpy2.getCall(0).args.length === 1);
assert(instanceMethodSpy2.getCall(0).args[0] === 'world');
});
});
describe('for getter', () => {
it('decorates if test is truthy', () => {
assert(applicationSpy5.callCount === 1);
assert(applicationSpy5.getCall(0).args[0] === TargetClass.prototype);
assert(applicationSpy5.getCall(0).args[1] === 'age');
assert(invocationSpy5.callCount === 0);
assert(instanceMethodSpy5.callCount === 0);
let age = new TargetClass().age;
assert(age === 42);
assert(invocationSpy5.callCount === 1);
assert(invocationSpy5.getCall(0).args.length === 0);
assert(instanceMethodSpy5.callCount === 1);
assert(instanceMethodSpy5.getCall(0).args.length === 0);
});
it('doesn\'t decorate if test is falsy', () => {
assert(applicationSpy6.callCount === 0);
assert(invocationSpy6.callCount === 0);
assert(instanceMethodSpy6.callCount === 0);
let sex = new TargetClass().sex;
assert(sex === true);
assert(applicationSpy6.callCount === 0);
assert(invocationSpy6.callCount === 0);
assert(instanceMethodSpy6.callCount === 1);
assert(instanceMethodSpy6.getCall(0).args.length === 0);
});
});
describe('for setter', () => {
it('decorates if test is truthy', () => {
assert(applicationSpy7.callCount === 1);
assert(applicationSpy7.getCall(0).args[0] === TargetClass.prototype);
assert(applicationSpy7.getCall(0).args[1] === 'id');
assert(invocationSpy7.callCount === 0);
assert(instanceMethodSpy7.callCount === 0);
new TargetClass().id = 999;
assert(invocationSpy7.callCount === 1);
assert(invocationSpy7.getCall(0).args.length === 1);
assert(invocationSpy7.getCall(0).args[0] === 999);
assert(instanceMethodSpy7.callCount === 1);
assert(instanceMethodSpy7.getCall(0).args.length === 1);
assert(instanceMethodSpy7.getCall(0).args[0] === 999);
});
it('doesn\'t decorate if test is falsy', () => {
assert(applicationSpy8.callCount === 0);
assert(invocationSpy8.callCount === 0);
assert(instanceMethodSpy8.callCount === 0);
new TargetClass().country = 'Japan';
assert(applicationSpy8.callCount === 0);
assert(invocationSpy8.callCount === 0);
assert(instanceMethodSpy8.callCount === 1);
assert(instanceMethodSpy8.getCall(0).args.length === 1);
assert(instanceMethodSpy8.getCall(0).args[0] === 'Japan');
});
});
});
describe(
'(test: (target?: Object, key?: string|symbol, desc?: PropertyDescriptor) => boolean, decorator: MethodDecorator): MethodDecorator',
() => {
it('decorates if test function returns true', () => {
assert(applicationSpy3.callCount === 1);
assert(applicationSpy3.getCall(0).args[0] === TargetClass.prototype);
assert(applicationSpy3.getCall(0).args[1] === 'decoratableMethod');
assert(invocationSpy3.callCount === 0);
assert(instanceMethodSpy3.callCount === 0);
new TargetClass().decoratableMethod('hello');
assert(invocationSpy3.callCount === 1);
assert(invocationSpy3.getCall(0).args.length === 1);
assert(invocationSpy3.getCall(0).args[0] === 'hello');
assert(instanceMethodSpy3.callCount === 1);
assert(instanceMethodSpy3.getCall(0).args.length === 1);
assert(instanceMethodSpy3.getCall(0).args[0] === 'hello');
});
it('doesn\'t decorate if test function returns false', () => {
assert(applicationSpy4.callCount === 0);
assert(invocationSpy4.callCount === 0);
assert(instanceMethodSpy4.callCount === 0);
new TargetClass().undecoratableMethod('world');
assert(applicationSpy4.callCount === 0);
assert(invocationSpy4.callCount === 0);
assert(instanceMethodSpy4.callCount === 1);
assert(instanceMethodSpy4.getCall(0).args.length === 1);
assert(instanceMethodSpy4.getCall(0).args[0] === 'world');
});
});
});
});
<file_sep>import * as assert from 'power-assert';
import * as sinon from 'sinon';
import { conditional } from '../src/index';
function createPropertyDecorator(spy: Sinon.SinonSpy): PropertyDecorator {
'use strict';
return function decorator(target?: Object, key?: string|symbol): void {
'use strict';
spy.apply(spy, arguments);
};
}
const spy1 = sinon.spy();
const decor1: PropertyDecorator = createPropertyDecorator(spy1);
const spy2 = sinon.spy();
const decor2 = createPropertyDecorator(spy2);
class TargetClass1 {
@conditional(true, decor1)
name: string;
@conditional(false, decor2)
age: number;
}
const spy3 = sinon.spy();
const decor3 = createPropertyDecorator(spy3);
const spy4 = sinon.spy();
const decor4 = createPropertyDecorator(spy4);
class TargetClass2 {
@conditional(testProperty, decor3) name: string;
@conditional(testProperty, decor4) age: number;
}
function testProperty(target?: Object, key?: string|symbol): boolean {
'use strict';
return key === 'name';
}
describe('conditional', () => {
describe('as a property decorator', () => {
describe('(test: boolean, decorator: PropertyDecorator): PropertyDecorator', () => {
it('decorates if test is truthy', () => {
assert(spy1.callCount === 1);
assert(spy1.getCall(0).args[0] === TargetClass1.prototype);
assert(spy1.getCall(0).args[1] === 'name');
});
it('doesn\'t decorate if test is falsy', () => {
assert(spy2.callCount === 0);
});
});
describe('(test: (target?: Object, key?: string|symbol) => boolean, decorator: PropertyDecorator): PropertyDecorator', () => {
it('decorates if test function returns true', () => {
assert(spy3.callCount === 1);
assert(spy3.getCall(0).args[0] === TargetClass2.prototype);
assert(spy3.getCall(0).args[1] === 'name');
});
it('doesn\'t decorate if test function returns false', () => {
assert(spy4.callCount === 0);
});
});
});
});
<file_sep>export interface ClassDecorator {
<TFunction extends Function>(target: TFunction): TFunction|void;
}
export interface PropertyDecorator {
(target: Object, propertyKey: string|symbol): void;
}
export interface MethodDecorator {
<T>(target: Object, propertyKey: string|symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T>|void;
}
export interface ParameterDecorator {
(target: Object, propertyKey: string|symbol, parameterIndex: number): void;
}
/**
* Enum for decorator type
*/
export enum DecoratorType {
Class,
Parameter,
Property,
Method,
None,
}
/**
* Guesses which kind of decorator from its functional arguments
* @param args
* @returns {DecoratorType}
*/
export function getDecoratorTypeFromArguments(args: IArguments): DecoratorType {
'use strict';
if (args.length === 0 || args.length > 3) {
return DecoratorType.None;
}
let kind: string = typeof (args.length === 1 ? args[0] : args[2]);
switch (kind) {
case 'function':
return DecoratorType.Class;
case 'number':
return DecoratorType.Parameter;
case 'undefined':
return DecoratorType.Property;
case 'object':
return DecoratorType.Method;
default:
return DecoratorType.None;
}
}
/**
* Guesses whether the given function is a class decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export function isClassDecorator(decorator: Function, args: IArguments): decorator is ClassDecorator {
'use strict';
return getDecoratorTypeFromArguments(args) === DecoratorType.Class;
}
/**
* Guesses whether the given function is a method parameter decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export function isParameterDecorator(decorator: Function, args: IArguments): decorator is ParameterDecorator {
'use strict';
return getDecoratorTypeFromArguments(args) === DecoratorType.Parameter;
}
/**
* Guesses whether the given function is a property decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export function isPropertyDecorator(decorator: Function, args: IArguments): decorator is PropertyDecorator {
'use strict';
return getDecoratorTypeFromArguments(args) === DecoratorType.Property;
}
/**
* Guesses whether the given function is a method decorator
* @param decorator
* @param args
* @returns {boolean}
*/
export function isMethodDecorator(decorator: Function, args: IArguments): decorator is MethodDecorator {
'use strict';
return getDecoratorTypeFromArguments(args) === DecoratorType.Method;
}
<file_sep>///<reference path="./dist/index.d.ts"/>
<file_sep>export { default as conditional } from './conditional';
<file_sep>import * as assert from 'power-assert';
import {
DecoratorType,
getDecoratorTypeFromArguments,
isClassDecorator,
isMethodDecorator,
isParameterDecorator,
isPropertyDecorator
} from '../src/utils';
class Clazz {
prop: any;
method(param: any) {
return;
}
}
let injectedArguments: IArguments;
function classDecorator(clazz: Function): Function {
'use strict';
injectedArguments = arguments;
return clazz;
}
function methodDecorator<T>(target: Object,
propertyKey: string|symbol,
descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T>|void {
'use strict';
injectedArguments = arguments;
return null;
}
function parameterDecorator(target: Object, propertyKey: string|symbol, parameterIndex: number): void {
'use strict';
injectedArguments = arguments;
}
function propertyDecorator(target: Object, propertyKey: string|symbol): void {
'use strict';
injectedArguments = arguments;
}
function nonDecorator(): void {
'use strict';
injectedArguments = arguments;
}
function yetAnotherNonDecorator(arg1: string, arg2: string, arg3: string): void {
'use strict';
injectedArguments = arguments;
}
const DecoratorTypes = [
DecoratorType.Class,
DecoratorType.Method,
DecoratorType.Parameter,
DecoratorType.Property,
DecoratorType.None
];
function invokeDecorator(type: DecoratorType) {
'use strict';
switch (type) {
case DecoratorType.Class:
classDecorator(Clazz);
return;
case DecoratorType.Method:
methodDecorator(Clazz.prototype, 'method', Object.getOwnPropertyDescriptor(Clazz.prototype, 'method'));
return;
case DecoratorType.Parameter:
parameterDecorator(Clazz.prototype, 'method', 0);
return;
case DecoratorType.Property:
propertyDecorator(Clazz.prototype, 'method');
return;
case DecoratorType.None:
nonDecorator();
return;
default:
return;
}
}
function getDecoratorName(type: DecoratorType): string {
'use strict';
switch (type) {
case DecoratorType.Class:
return 'Class';
case DecoratorType.Method:
return 'MethodDecorator';
case DecoratorType.Parameter:
return 'ParameterDecorator';
case DecoratorType.Property:
return 'PropertyDecorator';
case DecoratorType.None:
return 'None';
default:
return null;
}
}
function getDecoratorText(type: DecoratorType): string {
'use strict';
switch (type) {
case DecoratorType.Class:
return 'class decorator';
case DecoratorType.Method:
return 'method decorator';
case DecoratorType.Parameter:
return 'method parameter decorator';
case DecoratorType.Property:
return 'property decorator';
case DecoratorType.None:
return 'non-decorator';
default:
return null;
}
}
function getDecorator(type: DecoratorType): Function {
'use strict';
switch (type) {
case DecoratorType.Class:
return classDecorator;
case DecoratorType.Method:
return methodDecorator;
case DecoratorType.Parameter:
return parameterDecorator;
case DecoratorType.Property:
return propertyDecorator;
case DecoratorType.None:
return nonDecorator;
default:
return null;
}
}
describe('utils', () => {
beforeEach(() => injectedArguments = null);
describe('getDecoratorTypeFromArguments', () => {
DecoratorTypes.forEach(type => {
it(`returns ${getDecoratorName(type)} for ${getDecoratorText(type)}`, () => {
invokeDecorator(type);
assert(getDecoratorTypeFromArguments(injectedArguments) === type);
});
});
it('returns None for another non-decorator', () => {
yetAnotherNonDecorator('foo', 'bar', 'baz');
assert(getDecoratorTypeFromArguments(injectedArguments) === DecoratorType.None);
});
});
class TestSuitConfig {
target: Function;
name: string;
expected: DecoratorType[];
}
let testSuitConfig: TestSuitConfig[] = [
{
target: isClassDecorator,
name: 'isClassDecorator',
expected: [DecoratorType.Class]
},
{
target: isMethodDecorator,
name: 'isMethodDecorator',
expected: [DecoratorType.Method]
},
{
target: isParameterDecorator,
name: 'isParameterDecorator',
expected: [DecoratorType.Parameter]
},
{
target: isPropertyDecorator,
name: 'isPropertyDecorator',
expected: [DecoratorType.Property]
}
];
testSuitConfig.forEach(config => {
describe(config.name, () => {
DecoratorTypes.forEach(type => {
let expected = config.expected.indexOf(type) !== -1;
it(`returns ${expected} for ${getDecoratorText(type)}`, () => {
invokeDecorator(type);
assert(config.target(getDecorator(type), injectedArguments) === expected);
});
});
it('returns false for non-decorator', () => {
nonDecorator();
assert(config.target(nonDecorator, injectedArguments) === false);
});
it('returns false for yet another non-decorator', () => {
yetAnotherNonDecorator('foo', 'bar', 'baz');
assert(config.target(yetAnotherNonDecorator, injectedArguments) === false);
});
});
});
});
| bad1b671bdddec5f186ea58cf35b02625972162c | [
"Markdown",
"TypeScript"
] | 12 | TypeScript | tkqubo/conditional-decorator | 9e19163d3c7bc5b0c9695a736ff8802c700b1ffc | 75b0dc256a91e9d335fa49de67ea7d26f25f4169 |
refs/heads/master | <repo_name>adamedery/Blockchain-Project<file_sep>/README.md
Blockchain server can be started by runnning the BlockchainServer.java file.
This is an independent project carried out in full by me.
Conducted in order to learn more about networking through a more modern lense, the blockchain.
The server is capable of handling the sharing of information between many machines
as long as each machine knows about at least one other machine in the network. Network is
capable of detecting differences in the information stored at each machine, deciding on a
consensus and performing updates on the right machines as required, while only sending the
minimum amount of information over the network to perform the update.
<file_sep>/BlockchainServerRunnable.java
import java.io.*;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Arrays;
public class BlockchainServerRunnable implements Runnable{
private Socket clientSocket;
private Blockchain blockchain;
private HashMap<ServerInfo, Date> serverStatus;
public BlockchainServerRunnable(Socket clientSocket, Blockchain blockchain, HashMap<ServerInfo, Date> serverStatus) {
this.clientSocket = clientSocket;
this.blockchain = blockchain;
this.serverStatus = serverStatus;
}
public void run() {
try {
serverHandler(clientSocket.getInputStream(), clientSocket.getOutputStream());
clientSocket.close();
} catch (IOException e) {
}
}
public void serverHandler(InputStream clientInputStream, OutputStream clientOutputStream) {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientInputStream));
PrintWriter outWriter = new PrintWriter(clientOutputStream, true);
int localPort = clientSocket.getLocalPort();
int remotePort = ((InetSocketAddress) clientSocket.getRemoteSocketAddress()).getPort();
String localIP = (((InetSocketAddress) clientSocket.getLocalSocketAddress()).getAddress()).toString().replace("/", "");
String remoteIP = (((InetSocketAddress) clientSocket.getRemoteSocketAddress()).getAddress()).toString().replace("/", "");
try {
while (true) {
String inputLine = inputReader.readLine();
if (inputLine == null) break;
String[] tokens = inputLine.split("\\|");
switch (tokens[0]) {
case "tx":
if (blockchain.addTransaction(inputLine))
outWriter.print("Accepted\n\n");
else
outWriter.print("Rejected\n\n");
outWriter.flush();
break;
case "pb":
outWriter.print(blockchain.toString() + "\n");
outWriter.flush();
break;
case "cc":
return;
case "hb":
ServerInfo callingServerhb = new ServerInfo(remoteIP, Integer.parseInt(tokens[1]));
boolean newServerhb = true;
clearOldEntries();
Iterator it2hb = serverStatus.entrySet().iterator();
while (it2hb.hasNext()) {
HashMap.Entry entry = (HashMap.Entry)it2hb.next();
if(entry.getKey().equals(callingServerhb)){
it2hb.remove();
serverStatus.put(callingServerhb, new Date());
newServerhb = false;
break;
}
}
if(newServerhb){
ArrayList<Thread> threadArrayList = new ArrayList<>();
for(ServerInfo server : serverStatus.keySet()){
if (server.getPort() == localPort) continue;
Thread thread = new Thread(new HeartBeatClientRunnable(server, "si|" + localPort + "|" + remoteIP + "|" + Integer.parseInt(tokens[1])));
threadArrayList.add(thread);
thread.start();
}
for (Thread thread : threadArrayList) {
try {
thread.join();
} catch (InterruptedException e) {}
}
serverStatus.put(callingServerhb, new Date());
}
break;
case "si":
if(tokens[2].equals("localhost")){
tokens[2] = "127.0.0.1";
}
ServerInfo callingServersi = new ServerInfo(remoteIP, Integer.parseInt(tokens[1]));
ServerInfo addedServersi = new ServerInfo(tokens[2], Integer.parseInt(tokens[3]));
boolean newServersi = true;
if(addedServersi.getPort() == localPort) break;
clearOldEntries();
Iterator it2si = serverStatus.entrySet().iterator();
while (it2si.hasNext()) {
HashMap.Entry entry = (HashMap.Entry)it2si.next();
if(entry.getKey().equals(addedServersi)){
newServersi = false;
break;
}
}
if(newServersi){
ArrayList<Thread> threadArrayList = new ArrayList<>();
for(ServerInfo server : serverStatus.keySet()){
if(server.equals(callingServersi) || server.getPort() == localPort) continue;
Thread thread = new Thread(new HeartBeatClientRunnable(server, "si|" + localPort + "|" + tokens[2] + "|" + tokens[3]));
threadArrayList.add(thread);
thread.start();
}
for (Thread thread : threadArrayList) {
try {
thread.join();
} catch (InterruptedException e) {}
}
serverStatus.put(addedServersi, new Date());
}
break;
case "lb":
int localChainLength = this.blockchain.getLength();
int remoteChainLength = Integer.parseInt(tokens[2]);
byte[] remoteChainHash = Base64.getDecoder().decode(tokens[3]);
if(remoteChainLength > localChainLength || (remoteChainLength == localChainLength && compareHash(remoteChainHash, blockchain.getHead().calculateHash()) < 0)) {
try{
Thread thread = new Thread(new CatchUpClientRunnable(new ServerInfo(remoteIP, Integer.parseInt(tokens[1])), blockchain));
thread.start();
thread.join();
}
catch(InterruptedException e){
}
}
break;
case "cu":
ObjectOutputStream objWriter = new ObjectOutputStream(clientOutputStream);
if(tokens.length == 1){
if(blockchain.getHead() != null){
objWriter.writeObject(blockchain.getHead());
objWriter.flush();
}
}
else{
if(blockchain.getHead() != null){
byte[] remoteBlockHash = Base64.getDecoder().decode(tokens[1]);
Block requestedBlock = blockchain.getHead();
while(compareHash(requestedBlock.calculateHash(), remoteBlockHash) != 0){
requestedBlock = requestedBlock.getPreviousBlock();
if(requestedBlock == null) break;
}
if(requestedBlock != null){
objWriter.writeObject(requestedBlock);
objWriter.flush();
}
}
}
break;
default:
outWriter.print("Error\n\n");
outWriter.flush();
}
}
} catch (IOException e) {
} //catch (InterruptedException e) {}
}
//returns true if the first byte array is smaller, false otherwise
public int compareHash(byte[] first, byte[] second){
if(first.length != second.length){
return 2;
}
else{
for(int i = 0; i < first.length; i++){
if(first[i] > second[i]){
return 1;
}
if(first[i] < second[i]){
return -1;
}
}
return 0;
}
}
public void clearOldEntries(){
Iterator it = serverStatus.entrySet().iterator();
while (it.hasNext()) {
HashMap.Entry entry = (HashMap.Entry)it.next();
if (new Date().getTime() - ((Date) entry.getValue()).getTime() > 6000) {
it.remove();
}
}
}
}
| 1aaad28f32391b7e8b83be468301c46299c17ef5 | [
"Markdown",
"Java"
] | 2 | Markdown | adamedery/Blockchain-Project | 4e134d3a5f0fc73802eb26987849f0b6aba3d018 | a497e651556bc828fd0dcf570aefdcdcb322d6c3 |
refs/heads/master | <file_sep>class Title <ActiveRecord::Base
has_many :figure_titles
has_many :figures , :through => :figure_titles
end | dc092bfbe8c1c756dd7a1d64c0a666ab004749e7 | [
"Ruby"
] | 1 | Ruby | fatihantep27/nyc-sinatra-cb-gh-000 | 1d4e59d094830285d5f8d44b3163fcc1dad56133 | 9c281ec21ce770dbbd6c7a23f84a0b6da5941f13 |
refs/heads/main | <repo_name>lotoussa/PixelAnimation<file_sep>/pkg/sprite/hole.go
package sprite
import (
"path"
"github.com/faiface/pixel"
)
type Hole struct {
Sprites []*pixel.Sprite
}
func NewHole() (*Hole, error) {
hole := &Hole{}
for _, picPath := range []string{"holeA.png", "holeB.png", "holeC.png"} {
pic, err := LoadPicture(path.Join("assets", picPath))
if err != nil {
return nil, err
}
hole.Sprites = append(hole.Sprites, pixel.NewSprite(pic, pic.Bounds()))
}
return hole, nil
}
<file_sep>/main.go
package main
// import with "github.com/lotoussa/PixelAnimation/pkg"
import (
"fmt"
_ "image/png"
"time"
"./pkg/camera"
"./pkg/sprite"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/faiface/pixel/text"
"golang.org/x/image/colornames"
"golang.org/x/image/font/basicfont"
)
func gameLoop(
win *pixelgl.Window,
cam *camera.Camera,
hole *sprite.Hole,
planet *sprite.Planet,
config pixelgl.WindowConfig,
basicTxt *text.Text,
) error {
last := time.Now()
dynamicDt := 0.0
for !win.Closed() {
cam.Cam = pixel.IM.Scaled(
win.Bounds().Center(), cam.Zoom).
Moved(pixel.ZV.Sub(cam.Pos))
win.SetMatrix(cam.Cam)
win.Clear(colornames.Black)
dt := time.Since(last).Seconds()
last = time.Now()
dynamicDt += 3 * dt
hole.Sprites[int(dynamicDt*2)%3].Draw(
win,
pixel.IM.Moved(win.Bounds().Center()),
)
if win.JustPressed(pixelgl.MouseButtonLeft) {
planet.AddPlanet(win.MousePosition(), *cam)
}
planet.DrawBatch(win, dynamicDt)
basicTxt.Draw(win, pixel.IM.Scaled(basicTxt.Orig, 1.45))
cam.Move(win, dt*500)
win.Update()
cam.PrintFps(win, config)
}
return nil
}
func run() {
config := pixelgl.WindowConfig{
Title: "Pixel Animation",
Bounds: pixel.R(0, 0, 1280, 768),
VSync: true,
}
win, err := pixelgl.NewWindow(config)
if err != nil {
panic(err)
}
win.SetSmooth(true)
basicAtlas := text.NewAtlas(basicfont.Face7x13, text.ASCII)
basicTxt := text.New(pixel.V(20, 20), basicAtlas)
basicTxt.LineHeight = basicAtlas.LineHeight() * 1.3
basicTxt.Color = colornames.Violet
_, err = fmt.Fprintf(basicTxt, "Camera movement: Arrows\n"+
"Camera zoom: Mouse scroll\n"+
"Camera reset: Key R\n"+
"Place Objects: Left click\n")
if err != nil {
panic(err)
}
cam := camera.NewCamera()
hole, err := sprite.NewHole()
if err != nil {
panic(err)
}
planet, err := sprite.InitPlanet()
if err != nil {
panic(err)
}
err = gameLoop(win, cam, hole, planet, config, basicTxt)
if err != nil {
panic(err)
}
}
func main() {
pixelgl.Run(run)
}
<file_sep>/pkg/camera/camera.go
package camera
import (
"fmt"
"math"
"time"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
)
type Camera struct {
Pos pixel.Vec
Speed float64
Zoom float64
InverseZoom float64
ZoomSpeed float64
Frames int
Second <-chan time.Time
Cam pixel.Matrix
}
func NewCamera() *Camera {
return &Camera{
Pos: pixel.ZV,
Speed: 0.72,
Zoom: 1.0,
InverseZoom: 1.0,
ZoomSpeed: 1.01,
Frames: 0,
Second: time.Tick(time.Second),
}
}
func (c *Camera) Move(win *pixelgl.Window, dt float64) {
if win.Pressed(pixelgl.KeyLeft) {
c.Pos.X -= c.Speed * dt
}
if win.Pressed(pixelgl.KeyRight) {
c.Pos.X += c.Speed * dt
}
if win.Pressed(pixelgl.KeyDown) {
c.Pos.Y -= c.Speed * dt
}
if win.Pressed(pixelgl.KeyUp) {
c.Pos.Y += c.Speed * dt
}
c.zoom(win)
c.reset(c, win)
}
func (c *Camera) zoom(win *pixelgl.Window) {
camZoom := math.Pow(c.ZoomSpeed, win.MouseScroll().Y)
c.Zoom *= camZoom
c.InverseZoom /= camZoom
}
func (c Camera) reset(currentCam *Camera, win *pixelgl.Window) {
if win.Pressed(pixelgl.KeyR) {
*currentCam = *NewCamera()
}
}
func (c *Camera) PrintFps(win *pixelgl.Window, config pixelgl.WindowConfig) {
c.Frames++
select {
case <-c.Second:
win.SetTitle(fmt.Sprintf("%s | Fps: %d", config.Title, c.Frames))
c.Frames = 0
default:
}
}
<file_sep>/pkg/sprite/planet.go
package sprite
import (
"path"
"../camera"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
)
type Planet struct {
Sprites []*pixel.Sprite
Matrices []pixel.Matrix
Batch *pixel.Batch
pic pixel.Picture
}
func InitPlanet() (*Planet, error) {
planet := &Planet{}
pic, err := LoadPicture(path.Join("assets", "planetA.png"))
if err != nil {
return nil, err
}
planet.Sprites = nil
planet.Matrices = nil
planet.Batch = pixel.NewBatch(&pixel.TrianglesData{}, pic)
planet.pic = pic
return planet, nil
}
func (p *Planet) AddPlanet(mousePosition pixel.Vec, cam camera.Camera) {
p.Sprites = append(
p.Sprites,
pixel.NewSprite(p.pic, p.pic.Bounds()),
)
mouse := cam.Cam.Unproject(mousePosition)
p.Matrices = append(
p.Matrices,
pixel.IM.Scaled(pixel.ZV, cam.InverseZoom).Moved(mouse),
)
}
func (p *Planet) DrawBatch(win *pixelgl.Window, dynamicDt float64) {
p.Batch.Clear()
for i, planet := range p.Sprites {
planet.Draw(p.Batch, p.Matrices[i].
Rotated(win.Bounds().Center(), dynamicDt))
//Moved(pixel.ZV.Add(pixel.V(dynamicDt*10, dynamicDt*10))),
}
p.Batch.Draw(win)
}
| 1f17499f61a00c716018873619a632de3f688115 | [
"Go"
] | 4 | Go | lotoussa/PixelAnimation | 26d837229b36d501ff271a277d96b936518356c8 | a07841bd0493bbb98b33b14f614310c42c639bfb |
refs/heads/master | <file_sep>(function(d){
var
ce=function(e,n){var a=document.createEvent("CustomEvent");a.initCustomEvent(n,true,true,e.target);e.target.dispatchEvent(a);a=null;return false},
nm=true,sp={x:0,y:0},ep={x:0,y:0},
touch={
touchstart:function(e){sp={x:e.touches[0].pageX,y:e.touches[0].pageY}},
touchmove:function(e){nm=false;ep={x:e.touches[0].pageX,y:e.touches[0].pageY}},
touchend:function(e){if(nm){ce(e,'fc')}else{var x=ep.x-sp.x,xr=Math.abs(x),y=ep.y-sp.y,yr=Math.abs(y);if(Math.max(xr,yr)>20){ce(e,(xr>yr?(x<0?'swl':'swr'):(y<0?'swu':'swd')))}};nm=true},
touchcancel:function(e){nm=false}
};
for(var a in touch){d.addEventListener(a,touch[a],false);}
})(document);
Rx_deepmerge = (function () {
function isMergeableObject(val) {
var nonNullObject = val && typeof val === 'object'
return nonNullObject
&& Object.prototype.toString.call(val) !== '[object RegExp]'
&& Object.prototype.toString.call(val) !== '[object Date]'
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {}
}
function cloneIfNecessary(value, optionsArgument) {
var clone = optionsArgument && optionsArgument.clone === true
return (clone && isMergeableObject(value)) ? deepmerge(emptyTarget(value), value, optionsArgument) : value
}
function defaultArrayMerge(target, source, optionsArgument) {
var destination = target.slice()
source.forEach(function (e, i) {
if (typeof destination[i] === 'undefined') {
destination[i] = cloneIfNecessary(e, optionsArgument)
} else if (isMergeableObject(e)) {
destination[i] = deepmerge(target[i], e, optionsArgument)
} else if (target.indexOf(e) === -1) {
destination.push(cloneIfNecessary(e, optionsArgument))
}
})
return destination
}
function mergeObject(target, source, optionsArgument) {
var destination = {}
if (isMergeableObject(target)) {
Object.keys(target).forEach(function (key) {
destination[key] = cloneIfNecessary(target[key], optionsArgument)
})
}
Object.keys(source).forEach(function (key) {
if (!isMergeableObject(source[key]) || !target[key]) {
destination[key] = cloneIfNecessary(source[key], optionsArgument)
} else {
destination[key] = deepmerge(target[key], source[key], optionsArgument)
}
})
return destination
}
function deepmerge(target, source, optionsArgument) {
var array = Array.isArray(source);
var options = optionsArgument || {arrayMerge: defaultArrayMerge}
var arrayMerge = options.arrayMerge || defaultArrayMerge
if (array) {
return Array.isArray(target) ? arrayMerge(target, source, optionsArgument) : cloneIfNecessary(source, optionsArgument)
} else {
return mergeObject(target, source, optionsArgument)
}
}
deepmerge.all = function deepmergeAll(array, optionsArgument) {
if (!Array.isArray(array) || array.length < 2) {
throw new Error('first argument should be an array with at least two elements')
}
// we are sure there are at least 2 values, so it is safe to have no initial value
return array.reduce(function (prev, next) {
return deepmerge(prev, next, optionsArgument)
})
}
return deepmerge;
})();
RxFlexModal = {
$modal: null,
__: {},
currentLayout: null,
init: function () {
var self = this.__, that = this, _id = 0;
self.layouts = [];
self.$modal_backdrop = $('.rx__flex_modal__backdrop');
self.$modal = $('#rx__flex_modal');
self.$body = $(document.body);
self.$layout_template = self.$modal.find('.rx__flex_modal__layout').clone();
self.$layer = self.$modal.find('.rx__flex_modal__layer');
self.$modal.find('.rx__flex_modal__layout').remove();
self.newID = function () {
return _id++;
};
$(window).resize(function () {
that.setSize();
});
self.close_on_backdrop_click = that.getConfig({}, 'popup_config.close_on_backdrop_click');
self.$modal_backdrop.click(function (e) {
if (self.close_on_backdrop_click) {
if ($(e.target).closest('.rx__flex_modal').length === 0 && !$(e.target).hasClass('.rx__flex_modal')) {
that.close();
}
}
});
self.closeLayer = function () {
self.$layer.addClass('hidden');
self.$layer.find('.rx__flex_modal__layer__content__textcontent').html("");
setTimeout(function () {
self.$layer.removeClass('_start_anim').removeClass('_as_menu');
self.layer_active = false;
}, 200);
setTimeout(function () {
self.layer_active = false;
}, 300);
};
self.showLayer = function () {
self.$layer.addClass('_start_anim');
setTimeout(function () {
self.$layer.removeClass('hidden');
self.layer_active = true;
}, 0);
};
self.$layer.click(function (e) {
if ($(e.target).closest('.rx__flex_modal__layer__content').length === 0 && !$(e.target).hasClass('.rx__flex_modal__layer__content')) {
self.closeLayer();
}
});
return that;
},
open: function (config) {
var self = this.__, that = this;
self._open = true;
self.scrollTop = window.scrollY;
if (config instanceof RxFlexModal.Layout) {
that.setPosition(that.getConfig(config.getMainConfig(), 'popup_config.position'));
self.close_on_backdrop_click = that.getConfig(config.getMainConfig(), 'popup_config.close_on_backdrop_click');
} else {
that.setPosition(that.getConfig(config, 'popup_config.position'));
self.close_on_backdrop_click = that.getConfig(config, 'popup_config.close_on_backdrop_click');
}
self.$modal_backdrop.addClass('__anim_start').show();
setTimeout(function () {
self.$modal.addClass('open');
self.$modal_backdrop.removeClass('__anim_start')
}, 0);
self.$body.addClass('rx_flex_open');
that.setSize();
if (config instanceof RxFlexModal.Layout) {
that.push(config);
} else {
that.currentLayout = new RxFlexModal.Layout(config || RxFlexModal.Layout.defaultConfig);
that.currentLayout.init({
layout: self.$layout_template.clone(),
parent: that,
id: self.newID()
});
self.layouts.map(function (_layout) {
_layout.remove();
});
self.layouts = [];
self.layouts.push(that.currentLayout);
that.currentLayout.show();
}
},
alert: function (options) {
var self = this.__, that = this;
self.$layer.removeClass('_as_menu');
var $content_text = self.$layer.find('.rx__flex_modal__layer__content__textcontent');
var $content_actions = self.$layer.find('.rx__flex_modal__layer__content__actionscontent');
if (typeof options === "string") {
$content_text.text(options);
$content_actions.html('<button data-action="ok">ok</button>');
} else if (typeof options === "object") {
if ('text' in options) {
$content_text.html(options.text);
} else {
$content_text.html(" ");
}
if ('actions' in options && Array.isArray(options.actions)) {
$content_actions.html("");
options.actions.map(function (item) {
var style = item.color?'style="color:'+item.color+';"':"";
$content_actions.append('<button '+style+' data-action="' + item.action + '">' + item.text + '</button>');
})
}
}
return new RxFlexModal.Promise(function (resoleve, reject) {
$content_actions.find('button').click(function (e) {
var data = {};
$content_text.find('[name]').each(function () {
data[$(this).attr('name')] = $(this).val();
});
if($content_text.find('[name]').length){
data['action'] = $(this).data('action');
resoleve(data);
}else {
resoleve($(this).data('action'));
}
self.closeLayer();
});
self.showLayer();
});
},
menu: function (options) {
var self = this.__, that = this;
self.$layer.addClass('_as_menu');
var $content_actions = self.$layer.find('.rx__flex_modal__layer__content__actionscontent');
if (typeof options === "object") {
if ('items' in options && Array.isArray(options.items)) {
$content_actions.html("");
options.items.map(function (item) {
$content_actions.append('<button data-action="' + item.action + '">' + item.text + '</button>');
})
}
}
return new RxFlexModal.Promise(function (resoleve, reject) {
$content_actions.find('button').click(function (e) {
self.closeLayer();
resoleve($(this).data('action'));
});
self.showLayer();
});
},
setSize: function () {
var self = this.__, that = this;
if (window.innerWidth < 600) {
self.$body.addClass('rx_modal_full_screen');
} else {
self.$body.removeClass('rx_modal_full_screen');
}
},
setPosition: function (position) {
var self = this.__, that = this;
self.$modal_backdrop.removeClass('rx__flex_modal__backdrop__left')
.removeClass('rx__flex_modal__backdrop__right')
.removeClass('rx__flex_modal__backdrop__center');
switch (position) {
case RxFlexModal.CONST.POSITION_LEFT:
self.$modal_backdrop.addClass('rx__flex_modal__backdrop__left');
break;
case RxFlexModal.CONST.POSITION_CENTER:
self.$modal_backdrop.addClass('rx__flex_modal__backdrop__center');
break;
case RxFlexModal.CONST.POSITION_RIGHT:
self.$modal_backdrop.addClass('rx__flex_modal__backdrop__right');
break;
default:
self.$modal_backdrop.addClass('rx__flex_modal__backdrop__center');
break;
}
},
push: function (layout) {
var self = this.__, that = this;
if (layout instanceof RxFlexModal.Layout) {
if (layout.isRemoved()) {
throw new Error("Layout was removed use 'permanently:true' in config!");
}
if (!layout.isInitialized()) {
layout.init({
layout: self.$layout_template.clone(),
parent: that,
id: self.newID()
});
}
if (layout.isDetached()) {
layout.attach();
}
that.currentLayout = layout;
}
self.layouts.map(function (_layout) {
_layout.hide();
});
self.layouts.push(that.currentLayout);
that.currentLayout.show();
},
close: function () {
var self = this.__, that = this;
self._open = false;
self.$modal.removeClass('open').removeClass('full_screen');
self.$body.removeClass('rx_flex_open');
window.scrollTo(0, self.scrollTop || 0);
self.$modal_backdrop.addClass('__anim_start');
setTimeout(function () {
self.$modal_backdrop.hide();
}, 300);
self.layouts.map(function (_layout, index) {
if (_layout.isPermanently()) {
_layout.detach();
} else
_layout.remove();
});
self.layouts = [];
},
_handleBack: function (layout) {
var self = this.__, that = this;
if (layout) {
if (layout.isPermanently()) {
layout.hide();
layout.detach();
} else
layout.remove();
self.layouts.map(function (_layout, index) {
_layout.hide();
if (_layout.id === layout.id) {
self.layouts.splice(index, 1);
}
});
}
if (self.layouts.length > 0) {
that.currentLayout = self.layouts[self.layouts.length - 1];
} else {
self.layouts = [];
that.currentLayout = null;
that.close();
}
that.currentLayout && that.currentLayout.show();
},
getConfig: function (config, name) {
var conf = Rx_deepmerge(RxFlexModal.Layout.defaultConfig, config || {});
var path = name.split('.');
var tmp = conf;
path.map(function (prop) {
if (tmp)
tmp = tmp[prop];
});
return tmp;
},
isOpen: function () {
var self = this.__;
return self._open;
}
};
RxFlexModal.CONST = {
POSITION_LEFT: 1,
POSITION_RIGHT: 2,
POSITION_CENTER: 3,
TYPE_OF_COMPONENT_MODAL: 111
};
RxFlexModal.Layout = function (config) {
var self = this,
$layout = null,
Parent = {},
initialized = false,
removed = false,
detached = false,
attached = false,
_sticky = null,
LayoutEvents = new RxFlexModal.RxListenerManager();
self.loader = {
on: function () {
self.$loader.removeClass('hidden');
},
off: function () {
self.$loader.addClass('hidden');
},
};
self.refs = {};
self._actions = {
handleBack: function (e) {
LayoutEvents.dispatch("onBack", self);
Parent._handleBack(self);
console.log("Back");
},
handleClose: function (e) {
Parent.close();
}
};
self.dispatch = function(){
LayoutEvents.dispatch.apply(null,arguments);
};
self.onBack = function (clback) {
LayoutEvents.on("onBack", clback)
};
self.onDestroy = function (clback) {
LayoutEvents.on("onDestroy", clback)
};
self.onSetContent = function (clback) {
LayoutEvents.on("onSetContent", clback)
};
self.onHide = function (clback) {
LayoutEvents.on("onHide", clback)
};
self.onShow = function (clback) {
LayoutEvents.on("onShow", clback)
};
self.on = function (event_name, clback) {
LayoutEvents.on(event_name, clback)
};
self.isInitialized = function () {
return initialized;
};
self.isDetached = function () {
return detached;
};
self.isRemoved = function () {
return removed;
};
self.isPermanently = function () {
return config.config && config.config.permanently;
};
self.init = function (params) {
if (!initialized) {
LayoutEvents.clear();
self.id = params.id;
$layout = self.$wrapper = params.layout;
Parent = params.parent;
self.$loader = $layout.find('.rx__flex_modal__loader');
self.$header = $layout.find('.rx__flex_modal__header');
self.$header_left = $layout.find('.rx__flex_modal__header__left');
self.$header_center = $layout.find('.rx__flex_modal__header__center');
self.$header_right = $layout.find('.rx__flex_modal__header__right');
self.$header_backbutton = $layout.find('.rx__flex_modal__header__left .sprtrx-icon-left-open-big');
self.$header_closebutton = $layout.find('.rx__flex_modal__header__left .sprtrx-icon-cancel');
self.$header_title = $layout.find('.rx__flex_modal__header__center__title');
self.$footer = $layout.find('.rx__flex_modal__footer');
self.$content = $layout.find('.rx__flex_modal__content__content');
/*init events*/
self.$header_backbutton.click(self._actions.handleBack.bind(self));
self.$header_closebutton.click(self._actions.handleClose.bind(self));
self.setConfig(config.config);
self.attach();
if (config.content_script && typeof config.content_script === 'function') {
config.content_script(self);
}
if (self.$content.length && self.$content[0]) {
self.$content[0].addEventListener('touchmove', function (e) {
self.$content.focus();
}, false);
}
}
initialized = true;
};
self.setContent = function ($content) {
if ($content instanceof RxFlexModal.Promise) {
self.loader.on();
$content.then(function (content) {
self.$content.html(content);
self.loader.off();
LayoutEvents.dispatch("onSetContent", self);
});
} else {
self.$content.html($content);
LayoutEvents.dispatch("onSetContent", self);
}
return self;
};
self.hide = function () {
$layout && $layout.addClass('hidden');
LayoutEvents.dispatch("onHide", self);
};
self.show = function () {
console.log("Show");
$layout && $layout.removeClass('hidden');
LayoutEvents.dispatch("onShow", self);
};
self.remove = function () {
self.hide();
setTimeout(function () {
LayoutEvents.dispatch("onDestroy", self);
$layout && $layout.remove();
removed = true;
attached = false;
}, 300);
};
self.detach = function () {
self.hide();
setTimeout(function () {
LayoutEvents.dispatch("onDestroy", self);
if ($layout) {
$layout = $layout.detach();
detached = true;
attached = false;
}
}, 300);
};
self.attach = function () {
if ($layout && !attached) {
Parent.__.$modal.append($layout);
attached = true;
}
};
self.getMainConfig = function () {
return config || {};
};
self.getConfig = function (config, name) {
var conf = Rx_deepmerge(RxFlexModal.Layout.defaultConfig.config, config || {});
var path = name.split('.');
var tmp = conf;
path.map(function (prop) {
if (tmp)
tmp = tmp[prop];
});
return tmp;
};
self.setConfig = function (config) {
/*Footer*/
if (self.getConfig(config, 'footer.visible')) {
self.$footer.removeClass('hidden');
} else {
self.$footer.addClass('hidden');
}
if (self.getConfig(config, 'footer.height')) {
self.$footer.css('height', self.getConfig(config, 'footer.height'));
}
/*Header*/
if (self.getConfig(config, 'header.visible')) {
self.$header.removeClass('hidden');
} else {
self.$header.addClass('hidden');
}
if (self.getConfig(config, 'header.height')) {
self.$header.css('height', self.getConfig(config, 'header.height'));
}
if (self.getConfig(config, 'header.back_button')) {
self.$header_backbutton.removeClass('hidden');
} else {
self.$header_backbutton.addClass('hidden');
}
if (self.getConfig(config, 'header.close_button')) {
self.$header_closebutton.removeClass('hidden');
} else {
self.$header_closebutton.addClass('hidden');
}
if (typeof self.getConfig(config, 'header.title') === 'string') {
self.$header_title.text(self.getConfig(config, 'header.title'));
}
if (self.getConfig(config, 'header.right')) {
self.setHeaderRight(self.getConfig(config, 'header.right'));
}
if (self.$header_right.children().length) {
self.$header_center.removeClass('right_empty');
} else {
self.$header_center.addClass('right_empty');
}
if (self.getConfig(config, 'header.left')) {
self.setHeaderLeft(self.getConfig(config, 'header.left'));
}
if (self.getConfig(config, 'header.center')) {
self.setHeaderCenter(self.getConfig(config, 'header.center'));
}
self.setSticky(self.getConfig(config, 'header.sticky'));
};
/*Methods*/
self.setHeaderCenter = function (content) {
if (typeof content === 'object' && ('__typeofcomponent' in content) && content.__typeofcomponent === RxFlexModal.CONST.TYPE_OF_COMPONENT_MODAL) {
content.init(self, LayoutEvents);
self.$header_center.html(content.html());
} else
self.$header_center.html(content);
};
self.setHeaderLeft = function (content) {
if (Array.isArray(content)) {
self.$header_left.html();
content.map(function (el) {
if (el instanceof RxFlexModal.HeaderButton) {
el.init(self, LayoutEvents);
self.$header_left.append(el.html())
}
});
} else {
self.$header_left.html(content);
}
};
self.setHeaderRight = function (content) {
if (Array.isArray(content)) {
self.$header_right.html();
content.map(function (el) {
if (el instanceof RxFlexModal.HeaderButton) {
el.init(self, LayoutEvents);
self.$header_right.append(el.html())
}
});
} else {
self.$header_right.html(content);
}
};
self.get_scroll_function = function () {
var header_height = self.getConfig(config.config, 'header.height'), prevPos = 0;
var scrollHeight = 0;
var __sticky = true;
return function () {
if (_sticky && __sticky) {
scrollHeight = this.scrollHeight - this.clientHeight;
var m = parseInt(self.$header.css('margin-top'));
if (this.scrollTop < scrollHeight) {
if (this.scrollTop > 0) {
self.$header.css('margin-top', Math.min(0, Math.max((header_height * (-1)), m - (this.scrollTop - prevPos))));
} else {
self.$header.css('margin-top', 0);
}
} else {
self.$header.css('margin-top', (header_height * (-1)));
}
prevPos = this.scrollTop;
}
}
};
self.returnHeader = function(){
self.$header.animate({'margin-top': 0},300);
};
self.setSticky = function (sticky) {
_sticky = sticky;
if (_sticky) {
self.$content.scroll(self.get_scroll_function());
} else {
self.$header.css('margin-top', 0);
}
};
/*Getters*/
self.getHeaderCenter = function () {
return self.$header_center;
};
self.getHeaderLeft = function () {
return self.$header_left;
};
self.getHeaderRight = function () {
return self.$header_right;
};
};
RxFlexModal.Layout.defaultConfig = {
popup_config: {
position: RxFlexModal.CONST.POSITION_CENTER,
close_on_backdrop_click: true
},
config: {
header: {
visible: true,
sticky: false,
height: 70,
title: "",
close_button: false,
back_button: false,
right: [],
left: null
},
footer: {
visible: false,
height: 70
},
center: null
}
};
RxFlexModal.Promise = Promise;
RxFlexModal.HeaderButton = function (params) {
var self = this, $html = null;
this.init = function (Layout, LayoutEvents) {
if (params.type === 'icon') {
$html = $('<span class="' + params.icon + '"></span>');
}
if (params.type === 'button') {
$html = $('<button class="rx__flex_modal__header__button">' + params.text + '</button>');
}
if ($html && params.dispatchEvent) {
$html.click(function (e) {
LayoutEvents.dispatch(params.dispatchEvent, e)
})
}
if ($html && params.ref) {
Layout.refs[params.ref] = $html;
}
};
this.html = function () {
return $html;
};
this.__typeofcomponent = RxFlexModal.CONST.TYPE_OF_COMPONENT_MODAL;
};
RxFlexModal.HorizontalScrollableElement = function (params) {
var self = this, $html = null;
this.init = function (Layout, LayoutEvents) {
$html = $('<div class="rx__flex_modal__HorizontalScrollableElement"></div>');
if (typeof params.renderItem === 'function' && Array.isArray(params.items)) {
params.items.map(function (item, index) {
var $item = $('<div class="rx__flex_modal__HorizontalScrollableElement_item"></div>');
$item.css('width', params.width || 100);
$item.html(params.renderItem(item, index) || "");
$item.click(function (e) {
LayoutEvents.dispatch(params.dispatchEvent_item_click, e)
});
$html.append($item);
});
}
if ($html && params.ref) {
Layout.refs[params.ref] = $html;
}
};
this.html = function () {
return $html;
};
this.__typeofcomponent = RxFlexModal.CONST.TYPE_OF_COMPONENT_MODAL;
};
RxFlexModal.HeaderTab = function (params) {
var self = this, $html = null;
this.init = function (Layout, LayoutEvents) {
$html = $('<div class="rx__flex_modal__HeaderTab"></div>');
if (typeof params.renderItem === 'function' && Array.isArray(params.items)) {
params.items.map(function (item, index) {
var $item = $('<div class="rx__flex_modal__HeaderTab_item"></div>');
$item.html(params.renderItem(item, index) || "");
$item.click(function (e) {
LayoutEvents.dispatch(params.dispatchEvent_item_click, e)
});
$html.append($item);
});
}
if ($html && params.ref) {
Layout.refs[params.ref] = $html;
}
};
this.html = function () {
return $html;
};
this.__typeofcomponent = RxFlexModal.CONST.TYPE_OF_COMPONENT_MODAL;
};
RxFlexModal.RxListenerManager = function () {
var events = {};
var eventStates = {};
this.on = function (eventName, callback) {
events[eventName] && events[eventName].push(callback);
(!events[eventName]) && (events[eventName] = [callback]);
};
this.dispatch = function (_eventName, _param) {
var eventName = Array.prototype.shift.apply(arguments);
var main_arguments = arguments;
if (!!events[eventName] && Array.isArray(events[eventName])) {
events[eventName].map(function (fn) {
fn.apply(null, main_arguments);
});
eventStates[eventName] = (+eventStates[eventName] || 0) + 1;
}
};
this.clear = function () {
events = {};
eventStates = {};
};
};
RxFlexModal.init(); | 0b26153998d7af99e768edba4b3f3e4e03d759e9 | [
"JavaScript"
] | 1 | JavaScript | Kalyskin/rx_flex_modal | dc471ac413359e7b5439f3219530c3c0b0365584 | ddc2335c3d4d8bfc14820b7f359530bf390a3244 |
refs/heads/master | <repo_name>WiliamsPerez/proyectofinal<file_sep>/product/models.py
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100, verbose_name="Nombre")
created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación")
updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de edición")
class Meta:
verbose_name = "categoria"
verbose_name_plural = "categorias"
ordering = ["-created"]
def __str__(self):
return self.name
class Product(models.Model):
image = models.ImageField(verbose_name="Imagen")
name = models.CharField(max_length=100, verbose_name="Nombre")
description = models.TextField(max_length=500, verbose_name="Descripcion")
price = models.FloatField(verbose_name="Precio")
categories = models.ManyToManyField(Category, verbose_name="Categorias", related_name="get_product")
created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación")
updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de edición")
class Meta:
verbose_name = "producto"
verbose_name_plural = "productos"
ordering = ["-created"]
def __str__(self):
return self.name<file_sep>/product/views.py
from django.shortcuts import render, get_object_or_404
from .models import Product, Category
# Create your views here.
def product(request):
product = Product.objects.all()
return render(request, "core/home.html", {'product':product})
def category(request, category_id):
category = get_object_or_404(Category, id=category_id)
return render(request, "product/category.html", {'category':category})<file_sep>/product/admin.py
from django.contrib import admin
from .models import Product, Category
# Register your models here.
class CategoryAdmin(admin.ModelAdmin):
readonly_fields = ('created', 'updated')
class ProductAdmin(admin.ModelAdmin):
readonly_fields = ('created', 'updated')
list_display = ('name', 'description', 'price', 'product_categories')
def product_categories(self, obj):
return ", ".join([c.name for c in obj.categories.all().order_by("name")])
product_categories.short_description = "Categorias"
admin.site.register(Category, CategoryAdmin)
admin.site.register(Product, ProductAdmin)<file_sep>/aranda.sql
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 10-08-2020 a las 00:08:28
-- Versión del servidor: 10.4.11-MariaDB
-- Versión de PHP: 7.2.31
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `aranda`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `auth_group`
--
CREATE TABLE `auth_group` (
`id` int(11) NOT NULL,
`name` varchar(150) COLLATE utf8_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `auth_group_permissions`
--
CREATE TABLE `auth_group_permissions` (
`id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `auth_permission`
--
CREATE TABLE `auth_permission` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`content_type_id` int(11) NOT NULL,
`codename` varchar(100) COLLATE utf8_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `auth_permission`
--
INSERT INTO `auth_permission` (`id`, `name`, `content_type_id`, `codename`) VALUES
(1, 'Can add log entry', 1, 'add_logentry'),
(2, 'Can change log entry', 1, 'change_logentry'),
(3, 'Can delete log entry', 1, 'delete_logentry'),
(4, 'Can view log entry', 1, 'view_logentry'),
(5, 'Can add permission', 2, 'add_permission'),
(6, 'Can change permission', 2, 'change_permission'),
(7, 'Can delete permission', 2, 'delete_permission'),
(8, 'Can view permission', 2, 'view_permission'),
(9, 'Can add group', 3, 'add_group'),
(10, 'Can change group', 3, 'change_group'),
(11, 'Can delete group', 3, 'delete_group'),
(12, 'Can view group', 3, 'view_group'),
(13, 'Can add user', 4, 'add_user'),
(14, 'Can change user', 4, 'change_user'),
(15, 'Can delete user', 4, 'delete_user'),
(16, 'Can view user', 4, 'view_user'),
(17, 'Can add content type', 5, 'add_contenttype'),
(18, 'Can change content type', 5, 'change_contenttype'),
(19, 'Can delete content type', 5, 'delete_contenttype'),
(20, 'Can view content type', 5, 'view_contenttype'),
(21, 'Can add session', 6, 'add_session'),
(22, 'Can change session', 6, 'change_session'),
(23, 'Can delete session', 6, 'delete_session'),
(24, 'Can view session', 6, 'view_session'),
(25, 'Can add producto', 7, 'add_product'),
(26, 'Can change producto', 7, 'change_product'),
(27, 'Can delete producto', 7, 'delete_product'),
(28, 'Can view producto', 7, 'view_product'),
(29, 'Can add categoria', 8, 'add_category'),
(30, 'Can change categoria', 8, 'change_category'),
(31, 'Can delete categoria', 8, 'delete_category'),
(32, 'Can view categoria', 8, 'view_category'),
(33, 'Can add enlace', 9, 'add_link'),
(34, 'Can change enlace', 9, 'change_link'),
(35, 'Can delete enlace', 9, 'delete_link'),
(36, 'Can view enlace', 9, 'view_link');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `auth_user`
--
CREATE TABLE `auth_user` (
`id` int(11) NOT NULL,
`password` varchar(128) COLLATE utf8_spanish_ci NOT NULL,
`last_login` datetime(6) DEFAULT NULL,
`is_superuser` tinyint(1) NOT NULL,
`username` varchar(150) COLLATE utf8_spanish_ci NOT NULL,
`first_name` varchar(30) COLLATE utf8_spanish_ci NOT NULL,
`last_name` varchar(150) COLLATE utf8_spanish_ci NOT NULL,
`email` varchar(254) COLLATE utf8_spanish_ci NOT NULL,
`is_staff` tinyint(1) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`date_joined` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `auth_user`
--
INSERT INTO `auth_user` (`id`, `password`, `last_login`, `is_superuser`, `username`, `first_name`, `last_name`, `email`, `is_staff`, `is_active`, `date_joined`) VALUES
(1, 'pbkdf2_sha256$180000$fWZVjgBaPSmQ$SKwfc6xtmPlaC2TFXA40ihy9orsPAajt96V2OmJdOhY=', '2020-08-03 19:09:46.421473', 1, 'wili', '', '', '<EMAIL>', 1, 1, '2020-08-03 18:15:38.093056');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `auth_user_groups`
--
CREATE TABLE `auth_user_groups` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `auth_user_user_permissions`
--
CREATE TABLE `auth_user_user_permissions` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`permission_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `django_admin_log`
--
CREATE TABLE `django_admin_log` (
`id` int(11) NOT NULL,
`action_time` datetime(6) NOT NULL,
`object_id` longtext COLLATE utf8_spanish_ci DEFAULT NULL,
`object_repr` varchar(200) COLLATE utf8_spanish_ci NOT NULL,
`action_flag` smallint(5) UNSIGNED NOT NULL CHECK (`action_flag` >= 0),
`change_message` longtext COLLATE utf8_spanish_ci NOT NULL,
`content_type_id` int(11) DEFAULT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `django_admin_log`
--
INSERT INTO `django_admin_log` (`id`, `action_time`, `object_id`, `object_repr`, `action_flag`, `change_message`, `content_type_id`, `user_id`) VALUES
(1, '2020-08-03 18:17:21.492642', '1', 'Muebles', 1, '[{\"added\": {}}]', 8, 1),
(2, '2020-08-03 18:17:32.264726', '1', 'mesa', 1, '[{\"added\": {}}]', 7, 1),
(3, '2020-08-03 19:10:11.774954', '1', 'FACEBOOK', 1, '[{\"added\": {}}]', 9, 1),
(4, '2020-08-03 19:11:32.069991', '1', 'FACEBOOK', 2, '[]', 9, 1),
(5, '2020-08-05 01:17:28.618253', '1', 'FACEBOOK', 2, '[{\"changed\": {\"fields\": [\"Enlace\"]}}]', 9, 1),
(6, '2020-08-05 01:18:17.073818', '2', 'Mesa', 1, '[{\"added\": {}}]', 7, 1),
(7, '2020-08-05 01:19:55.941649', '1', 'mesa', 3, '', 7, 1),
(8, '2020-08-05 01:20:27.585374', '3', 'Tocador', 1, '[{\"added\": {}}]', 7, 1),
(9, '2020-08-05 01:21:05.242334', '4', 'Mueble 3', 1, '[{\"added\": {}}]', 7, 1),
(10, '2020-08-05 01:22:08.753253', '5', 'Mueble 4', 1, '[{\"added\": {}}]', 7, 1),
(11, '2020-08-05 01:22:41.701604', '6', 'Cuadros de madera', 1, '[{\"added\": {}}]', 7, 1),
(12, '2020-08-09 21:49:49.935068', '4', 'Mueble 3', 2, '[{\"changed\": {\"fields\": [\"Imagen\"]}}]', 7, 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `django_content_type`
--
CREATE TABLE `django_content_type` (
`id` int(11) NOT NULL,
`app_label` varchar(100) COLLATE utf8_spanish_ci NOT NULL,
`model` varchar(100) COLLATE utf8_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `django_content_type`
--
INSERT INTO `django_content_type` (`id`, `app_label`, `model`) VALUES
(1, 'admin', 'logentry'),
(3, 'auth', 'group'),
(2, 'auth', 'permission'),
(4, 'auth', 'user'),
(5, 'contenttypes', 'contenttype'),
(8, 'product', 'category'),
(7, 'product', 'product'),
(6, 'sessions', 'session'),
(9, 'social', 'link');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `django_migrations`
--
CREATE TABLE `django_migrations` (
`id` int(11) NOT NULL,
`app` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`name` varchar(255) COLLATE utf8_spanish_ci NOT NULL,
`applied` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `django_migrations`
--
INSERT INTO `django_migrations` (`id`, `app`, `name`, `applied`) VALUES
(1, 'contenttypes', '0001_initial', '2020-08-03 18:02:03.209212'),
(2, 'auth', '0001_initial', '2020-08-03 18:02:06.042421'),
(3, 'admin', '0001_initial', '2020-08-03 18:02:15.169050'),
(4, 'admin', '0002_logentry_remove_auto_add', '2020-08-03 18:02:17.092204'),
(5, 'admin', '0003_logentry_add_action_flag_choices', '2020-08-03 18:02:17.138207'),
(6, 'contenttypes', '0002_remove_content_type_name', '2020-08-03 18:02:18.744338'),
(7, 'auth', '0002_alter_permission_name_max_length', '2020-08-03 18:02:19.810418'),
(8, 'auth', '0003_alter_user_email_max_length', '2020-08-03 18:02:20.708845'),
(9, 'auth', '0004_alter_user_username_opts', '2020-08-03 18:02:20.804852'),
(10, 'auth', '0005_alter_user_last_login_null', '2020-08-03 18:02:21.664915'),
(11, 'auth', '0006_require_contenttypes_0002', '2020-08-03 18:02:21.698920'),
(12, 'auth', '0007_alter_validators_add_error_messages', '2020-08-03 18:02:21.753924'),
(13, 'auth', '0008_alter_user_username_max_length', '2020-08-03 18:02:21.937937'),
(14, 'auth', '0009_alter_user_last_name_max_length', '2020-08-03 18:02:22.066945'),
(15, 'auth', '0010_alter_group_name_max_length', '2020-08-03 18:02:23.054020'),
(16, 'auth', '0011_update_proxy_permissions', '2020-08-03 18:02:23.121027'),
(17, 'product', '0001_initial', '2020-08-03 18:02:23.545057'),
(18, 'product', '0002_auto_20190812_2242', '2020-08-03 18:02:24.160103'),
(19, 'sessions', '0001_initial', '2020-08-03 18:02:27.916335'),
(20, 'social', '0001_initial', '2020-08-03 18:02:28.611387');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `django_session`
--
CREATE TABLE `django_session` (
`session_key` varchar(40) COLLATE utf8_spanish_ci NOT NULL,
`session_data` longtext COLLATE utf8_spanish_ci NOT NULL,
`expire_date` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `django_session`
--
INSERT INTO `django_session` (`session_key`, `session_data`, `expire_date`) VALUES
('pflwv1727sds2918xdiindss91cbqptl', '<KEY> '2020-08-17 19:09:46.480488'),
('<KEY>', '<KEY> '2020-08-17 18:16:15.151721');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `product_category`
--
CREATE TABLE `product_category` (
`id` int(11) NOT NULL,
`name` varchar(100) COLLATE utf8_spanish_ci NOT NULL,
`created` datetime(6) NOT NULL,
`updated` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `product_category`
--
INSERT INTO `product_category` (`id`, `name`, `created`, `updated`) VALUES
(1, 'Muebles', '2020-08-03 18:17:21.390637', '2020-08-03 18:17:21.390637');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `product_product`
--
CREATE TABLE `product_product` (
`id` int(11) NOT NULL,
`image` varchar(100) COLLATE utf8_spanish_ci NOT NULL,
`name` varchar(100) COLLATE utf8_spanish_ci NOT NULL,
`description` longtext COLLATE utf8_spanish_ci NOT NULL,
`price` double NOT NULL,
`created` datetime(6) NOT NULL,
`updated` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `product_product`
--
INSERT INTO `product_product` (`id`, `image`, `name`, `description`, `price`, `created`, `updated`) VALUES
(2, 'mueble1.jpg', 'Mesa', 'Mesa de centro', 400, '2020-08-05 01:18:17.056818', '2020-08-05 01:18:17.056818'),
(3, 'mueble3.jpg', 'Tocador', 'Bonito tocador para cuarto', 1200, '2020-08-05 01:20:27.482368', '2020-08-05 01:20:27.482368'),
(4, 'IMG-20191226-WA0074.jpg', 'Mueble 3', 'Bonito mueble para su hogar', 1500, '2020-08-05 01:21:05.003318', '2020-08-09 21:49:49.903066'),
(5, 'mueble5.jpg', 'Mueble 4', 'Bi}onito mueble para casa', 2000, '2020-08-05 01:22:08.735252', '2020-08-05 01:22:08.735252'),
(6, 'mueble4.jpg', 'Cuadros de madera', 'bonitos cuadros de madera para su hogar', 50, '2020-08-05 01:22:41.510591', '2020-08-05 01:22:41.510591');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `product_product_categories`
--
CREATE TABLE `product_product_categories` (
`id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `product_product_categories`
--
INSERT INTO `product_product_categories` (`id`, `product_id`, `category_id`) VALUES
(2, 2, 1),
(3, 3, 1),
(4, 4, 1),
(5, 5, 1),
(6, 6, 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `social_link`
--
CREATE TABLE `social_link` (
`id` int(11) NOT NULL,
`key` varchar(100) COLLATE utf8_spanish_ci NOT NULL,
`name` varchar(200) COLLATE utf8_spanish_ci NOT NULL,
`url` varchar(200) COLLATE utf8_spanish_ci DEFAULT NULL,
`created` datetime(6) NOT NULL,
`updated` datetime(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
--
-- Volcado de datos para la tabla `social_link`
--
INSERT INTO `social_link` (`id`, `key`, `name`, `url`, `created`, `updated`) VALUES
(1, 'LINK_FACEBOOK', 'FACEBOOK', 'http://facebook.com/', '2020-08-03 19:10:11.758953', '2020-08-05 01:17:28.616252');
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `auth_group`
--
ALTER TABLE `auth_group`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);
--
-- Indices de la tabla `auth_group_permissions`
--
ALTER TABLE `auth_group_permissions`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_group_permissions_group_id_permission_id_0cd325b0_uniq` (`group_id`,`permission_id`),
ADD KEY `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` (`permission_id`);
--
-- Indices de la tabla `auth_permission`
--
ALTER TABLE `auth_permission`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_permission_content_type_id_codename_01ab375a_uniq` (`content_type_id`,`codename`);
--
-- Indices de la tabla `auth_user`
--
ALTER TABLE `auth_user`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
--
-- Indices de la tabla `auth_user_groups`
--
ALTER TABLE `auth_user_groups`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_user_groups_user_id_group_id_94350c0c_uniq` (`user_id`,`group_id`),
ADD KEY `auth_user_groups_group_id_97559544_fk_auth_group_id` (`group_id`);
--
-- Indices de la tabla `auth_user_user_permissions`
--
ALTER TABLE `auth_user_user_permissions`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `auth_user_user_permissions_user_id_permission_id_14a6b632_uniq` (`user_id`,`permission_id`),
ADD KEY `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` (`permission_id`);
--
-- Indices de la tabla `django_admin_log`
--
ALTER TABLE `django_admin_log`
ADD PRIMARY KEY (`id`),
ADD KEY `django_admin_log_content_type_id_c4bce8eb_fk_django_co` (`content_type_id`),
ADD KEY `django_admin_log_user_id_c564eba6_fk_auth_user_id` (`user_id`);
--
-- Indices de la tabla `django_content_type`
--
ALTER TABLE `django_content_type`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `django_content_type_app_label_model_76bd3d3b_uniq` (`app_label`,`model`);
--
-- Indices de la tabla `django_migrations`
--
ALTER TABLE `django_migrations`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `django_session`
--
ALTER TABLE `django_session`
ADD PRIMARY KEY (`session_key`),
ADD KEY `django_session_expire_date_a5c62663` (`expire_date`);
--
-- Indices de la tabla `product_category`
--
ALTER TABLE `product_category`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `product_product`
--
ALTER TABLE `product_product`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `product_product_categories`
--
ALTER TABLE `product_product_categories`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `product_product_categories_product_id_category_id_fdd1154c_uniq` (`product_id`,`category_id`),
ADD KEY `product_product_cate_category_id_edc0e025_fk_product_c` (`category_id`);
--
-- Indices de la tabla `social_link`
--
ALTER TABLE `social_link`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `key` (`key`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `auth_group`
--
ALTER TABLE `auth_group`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `auth_group_permissions`
--
ALTER TABLE `auth_group_permissions`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `auth_permission`
--
ALTER TABLE `auth_permission`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;
--
-- AUTO_INCREMENT de la tabla `auth_user`
--
ALTER TABLE `auth_user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `auth_user_groups`
--
ALTER TABLE `auth_user_groups`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `auth_user_user_permissions`
--
ALTER TABLE `auth_user_user_permissions`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `django_admin_log`
--
ALTER TABLE `django_admin_log`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT de la tabla `django_content_type`
--
ALTER TABLE `django_content_type`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT de la tabla `django_migrations`
--
ALTER TABLE `django_migrations`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT de la tabla `product_category`
--
ALTER TABLE `product_category`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `product_product`
--
ALTER TABLE `product_product`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT de la tabla `product_product_categories`
--
ALTER TABLE `product_product_categories`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT de la tabla `social_link`
--
ALTER TABLE `social_link`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `auth_group_permissions`
--
ALTER TABLE `auth_group_permissions`
ADD CONSTRAINT `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`),
ADD CONSTRAINT `auth_group_permissions_group_id_b120cbf9_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`);
--
-- Filtros para la tabla `auth_permission`
--
ALTER TABLE `auth_permission`
ADD CONSTRAINT `auth_permission_content_type_id_2f476e4b_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`);
--
-- Filtros para la tabla `auth_user_groups`
--
ALTER TABLE `auth_user_groups`
ADD CONSTRAINT `auth_user_groups_group_id_97559544_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`),
ADD CONSTRAINT `auth_user_groups_user_id_6a12ed8b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
--
-- Filtros para la tabla `auth_user_user_permissions`
--
ALTER TABLE `auth_user_user_permissions`
ADD CONSTRAINT `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`),
ADD CONSTRAINT `auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
--
-- Filtros para la tabla `django_admin_log`
--
ALTER TABLE `django_admin_log`
ADD CONSTRAINT `django_admin_log_content_type_id_c4bce8eb_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`),
ADD CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
--
-- Filtros para la tabla `product_product_categories`
--
ALTER TABLE `product_product_categories`
ADD CONSTRAINT `product_product_cate_category_id_edc0e025_fk_product_c` FOREIGN KEY (`category_id`) REFERENCES `product_category` (`id`),
ADD CONSTRAINT `product_product_cate_product_id_f73e32d0_fk_product_p` FOREIGN KEY (`product_id`) REFERENCES `product_product` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 52666987ea3055c27238c3bd2cd2f5076a1f95d6 | [
"SQL",
"Python"
] | 4 | Python | WiliamsPerez/proyectofinal | 944ffa64daab1828a2a1d0a6e6ffc6c5632cc2df | 4dd538fc21967cc952b0c1c27dc3182901e4e2d8 |
refs/heads/master | <file_sep>#!/usr/bin/python3
'''build api routes'''
from api.v1.views import app_views
from flask import jsonify, abort, request
from models.city import City
from models.state import State
from models.place import Place
from models import storage
@app_views.route('/cities/<city_id>/places', methods=['GET'])
def list_places(city_id):
''' Return a json with all the places for cities objects '''
city = storage.get(City, city_id)
if not city:
abort(404)
places = [place.to_dict() for place in city.places]
return jsonify(places)
@app_views.route('/cities/<city_id>/places', methods=['POST'])
def places_post(city_id):
''' Return a new Json object'''
city = storage.get(City, city_id)
if not city:
abort(404)
data = request.get_json()
if not data:
abort(400, "Not a JSON")
if 'user_id' not in data:
abort(400, "Missing user_id")
user = storage.get(User, data['user_id'])
if not user:
abort(404)
if 'name' not in request.get_json():
abort(400, description="Missing name")
data["city_id"] = city_id
instance = Place(**data)
instance.save()
return make_response(jsonify(instance.to_dict()), 201)
@app_views.route('/places/<place_id>', methods=['GET'])
def list_place(place_id):
''' Return a json with all the cities objects '''
place = storage.get(Place, place_id)
if not place:
abort(404)
return jsonify(place.to_dict())
@app_views.route('/places/<place_id>', methods=['DELETE'])
def place_get(place_id):
''' Delte a place '''
place = storage.get(Place, place_id)
if not place:
abort(404)
storage.delete(place)
storage.save()
return make_response(jsonify({}), 200)
@app_views.route('/places/<place_id>', methods=['PUT'])
def place_update(place_id):
''' Update a Place '''
place = storage.get(Place, place_id)
if not place:
abort(404)
data = request.get_json()
if not data:
abort(400, "Not a JSON")
ignore = ['id', 'user_id', 'city_id', 'created_at', 'updated_at']
for key, value in data.items():
if key not in ignore:
setattr(place, key, value)
storage.save()
return make_response(jsonify(place.to_dict()), 200)
<file_sep>#!/usr/bin/python3
'''build api routes'''
from api.v1.views import app_views
from flask import jsonify, abort, request
from models.user import User
from models import storage
@app_views.route('/users', methods=['GET', 'POST'])
def list_users():
''' return a json with all the users objects or update another one '''
if request.method == 'GET':
objects = storage.all(User)
list_objs = []
for obj in objects.items():
list_objs.append(obj[1].to_dict())
return jsonify(list_objs)
elif request.method == 'POST':
json_input = request.get_json()
if json_input and 'password' in json_input.keys() and 'email'\
in json_input.keys():
user_obj = User(**json_input)
user_obj.save()
return jsonify(user_obj.to_dict()), 201
elif 'email' not in json_input.keys():
return abort(400, "Missing email")
elif 'password' not in json_input.keys():
return abort(400, "Missing password")
elif json_input is None:
return abort(400, 'Not a JSON')
return abort(400, "Missing name")
@app_views.route('/users/<user_id>',
methods=['GET', 'DELETE', 'POST', 'PUT'])
def users_requests(user_id):
''' Get users by id, delete them, put a new one, and update. '''
if request.method == 'GET':
objects = storage.all(User)
for obj in objects.items():
if user_id == obj[1].id:
return jsonify(obj[1].to_dict())
return abort(404)
elif request.method == 'DELETE':
user_obj = storage.get(User, user_id)
if user_obj:
storage.delete(user_obj)
storage.save()
return jsonify({}), 200
return abort(404)
elif request.method == 'PUT':
json_input = request.get_json()
if json_input is None:
return abort(400, 'Not a JSON')
ignored_keys = ["id", "created_at", "updated_at", "email"]
user_obj = storage.get(User, user_id)
if user_obj:
for k, v in json_input.items():
if k not in ignored_keys:
setattr(user_obj, k, v)
user_obj.save()
return jsonify(user_obj.to_dict()), 200
return abort(404)
<file_sep>#!/usr/bin/python3
'''build api routes'''
from api.v1.views import app_views
from flask import jsonify, abort, request
from models.state import State
from models import storage
@app_views.route('/states', methods=['GET', 'POST'])
def list_states():
''' return a json with all the states objects or update another one '''
if request.method == 'GET':
objects = storage.all(State)
list_objs = []
for obj in objects.items():
list_objs.append(obj[1].to_dict())
return jsonify(list_objs)
elif request.method == 'POST':
json_input = request.get_json()
if json_input and 'name' in json_input.keys():
state_obj = State(**json_input)
state_obj.save()
return jsonify(state_obj.to_dict()), 201
elif json_input is None:
return abort(400, 'Not a JSON')
return abort(400, "Missing name")
@app_views.route('/states/<state_id>',
methods=['GET', 'DELETE', 'POST', 'PUT'])
def states_requests(state_id):
''' Get states by id, delete them, put a new one, and update. '''
if request.method == 'GET':
objects = storage.all(State)
for obj in objects.items():
if state_id == obj[1].id:
return jsonify(obj[1].to_dict())
return abort(404)
elif request.method == 'DELETE':
state_obj = storage.get(State, state_id)
if state_obj:
storage.delete(state_obj)
storage.save()
return jsonify({})
return abort(404)
elif request.method == 'PUT':
json_input = request.get_json()
if json_input is None:
abort(400, 'Not a JSON')
ignored_keys = ["id", "created_at", "updated_at"]
state_obj = storage.get(State, state_id)
if state_obj:
for k, v in json_input.items():
if k not in ignored_keys:
setattr(state_obj, k, v)
state_obj.save()
return jsonify(state_obj.to_dict())
return abort(404)
<file_sep>#!/usr/bin/python3
'''build api routes'''
from api.v1.views import app_views
from flask import jsonify, abort, request
from models.city import City
from models.state import State
from models import storage
@app_views.route('/states/<state_id>/cities', methods=['GET', 'POST'],
strict_slashes=False)
def list_cities(state_id):
''' return a json with all the cities for states objects '''
if request.method == 'GET':
state = storage.get(State, state_id)
if not state:
abort(404)
list_objs = []
for city in state.cities:
list_objs.append(city.to_dict())
return jsonify(list_objs)
elif request.method == 'POST':
json_input = request.get_json()
if json_input:
if 'name' in json_input.keys():
if storage.get(State, state_id):
json_input['state_id'] = state_id
new_obj = City(**json_input)
new_obj.save()
return jsonify(new_obj.to_dict()), 201
return abort(404)
return abort(400, "Missing name")
return abort(400, 'Not a JSON')
@app_views.route('/cities/<city_id>', methods=['GET', 'DELETE', 'PUT'])
def list_city(city_id):
''' return a json with all the cities objects '''
if request.method == 'GET':
objects = storage.all(City)
for obj in objects.items():
city_obj = obj[1].to_dict()
if city_obj['id'] == city_id:
return jsonify(city_obj)
return abort(404)
if request.method == 'DELETE':
objects = storage.all(City)
for obj in objects.items():
city_obj = obj[1].to_dict()
if city_obj['id'] == city_id:
storage.delete(obj[1])
storage.save()
return {}, 200
return abort(404)
if request.method == 'PUT':
json_input = request.get_json()
ignored_keys = ['id', 'state_id', 'created_at', 'updated_at']
if json_input:
city_obj = storage.get(City, city_id)
if city_obj:
for k, v in json_input.items():
if k not in ignored_keys:
setattr(city_obj, k, v)
city_obj.save()
return jsonify(city_obj.to_dict()), 200
return abort(404)
return abort(400, 'Not a JSON')
<file_sep>#!/usr/bin/python3
'''build api routes'''
from api.v1.views import app_views
from flask import jsonify, abort, request
from models.amenity import Amenity
from models import storage
@app_views.route('/amenities', methods=['GET'])
def ameniy_get():
''' Return a json with all the amenities objects '''
objects = storage.all(Amenity)
list_objs = []
for obj in objects.items():
list_objs.append(obj[1].to_dict())
return jsonify(list_objs)
@app_views.route('/amenities', methods=['POST'])
def amenity_post():
json_input = request.get_json()
if json_input and 'name' in json_input.keys():
state_obj = Amenity(**json_input)
state_obj.save()
return jsonify(state_obj.to_dict()), 201
elif json_input is None:
return abort(400, 'Not a JSON')
return abort(400, "Missing name")
@app_views.route('/amenities/<amenity_id>', methods=['GET'])
def amenities_get(amenity_id):
''' Get amenities by id '''
objects = storage.all(Amenity)
for obj in objects.items():
if amenity_id == obj[1].id:
return jsonify(obj[1].to_dict())
return abort(404)
@app_views.route('/amenities/<amenity_id>', methods=['DELETE'])
def amenities_delete(amenity_id):
''' Delete amenity '''
state_obj = storage.get(Amenity, amenity_id)
if state_obj:
storage.delete(state_obj)
storage.save()
return jsonify({})
return abort(404)
@app_views.route('/amenities/<amenity_id>', methods=['PUT'])
def amenity_put(amenity_id):
''' Update amenity '''
json_input = request.get_json()
if json_input is None:
abort(400, 'Not a JSON')
ignored_keys = ["id", "created_at", "updated_at"]
state_obj = storage.get(Amenity, amenity_id)
if state_obj:
for k, v in json_input.items():
if k not in ignored_keys:
setattr(state_obj, k, v)
state_obj.save()
return jsonify(state_obj.to_dict())
return abort(404)
| 7030fd20234cb535587e957cafb35f9a1add932d | [
"Python"
] | 5 | Python | Nicolasopf/AirBnB_clone_v3 | 40346071a5246f721ac1cb74bd6f61b341d98d17 | 9f9584143c2ca868744cb51bff6d3f70754b6cc6 |
refs/heads/master | <repo_name>ggxz88/Springboot<file_sep>/Project/src/main/java/org/hdcd/controller/BannerController.java
package org.hdcd.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
import org.hdcd.domain.Banner;
import org.hdcd.service.BannerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/banner")
public class BannerController {
private static final Logger logger = LoggerFactory.getLogger(BannerController.class);
@Autowired
private BannerService service;
@Value("${upload.path}")
private String uploadPath;
@RequestMapping(value = "/register", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String registerForm(Model model) throws Exception {
logger.info("Banner RegisterForm");
Banner banner = new Banner();
model.addAttribute(banner);
return "banner/register";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String register(Banner banner, RedirectAttributes rttr) throws Exception {
logger.info("Banner Register");
MultipartFile bannerPictureFile = banner.getBannerPicture();
String createdBannerPictureFilename = uploadFile(bannerPictureFile.getOriginalFilename(), bannerPictureFile.getBytes());
banner.setBannerPictureUrl(createdBannerPictureFilename);
service.register(banner);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/banner/list";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public void list(Model model) throws Exception {
logger.info("Banner List");
List<Banner> bannerList = service.list();
model.addAttribute("list", bannerList);
}
@RequestMapping(value = "/read", method = RequestMethod.GET)
public String read(Integer bannerNo, Model model) throws Exception {
logger.info("Banner Read");
Banner banner = service.read(bannerNo);
model.addAttribute(banner);
return "banner/read";
}
@RequestMapping(value = "/remove", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String removeForm(Integer bannerNo, Model model) throws Exception {
logger.info("Banner RemoveForm");
Banner banner = service.read(bannerNo);
model.addAttribute(banner);
return "banner/remove";
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String remove(Banner banner, RedirectAttributes rttr) throws Exception {
logger.info("Banner Remove");
service.remove(banner.getBannerNo());
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/banner/list";
}
@RequestMapping(value = "/modify", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String modifyForm(Integer bannerNo, Model model) throws Exception {
logger.info("Banner ModifyForm");
Banner banner = service.read(bannerNo);
model.addAttribute(banner);
return "banner/modify";
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String modify(Banner banner, RedirectAttributes rttr) throws Exception {
logger.info("Banner Modify");
MultipartFile bannerPictureFile = banner.getBannerPicture();
if(bannerPictureFile != null && bannerPictureFile.getSize() > 0) {
String createFilename = uploadFile(bannerPictureFile.getOriginalFilename(), bannerPictureFile.getBytes());
banner.setBannerPictureUrl(createFilename);
}
service.modify(banner);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/banner/list";
}
private String uploadFile(String originalName, byte[] fileData) throws Exception {
logger.info("Banner uploadFile");
UUID uid = UUID.randomUUID();
String createdFileName = uid.toString() + "_" + originalName;
File target = new File(uploadPath, createdFileName);
FileCopyUtils.copy(fileData, target);
return createdFileName;
}
@ResponseBody
@RequestMapping("/display")
public ResponseEntity<byte[]> displayFile(Integer bannerNo) throws Exception {
logger.info("Banner Display");
InputStream in = null;
ResponseEntity<byte[]> entity = null;
String bannerPictureFile = service.getBannerPic(bannerNo);
try {
String formatName = bannerPictureFile.substring(bannerPictureFile.lastIndexOf(".") + 1);
MediaType mType = getMediaType(formatName);
HttpHeaders headers = new HttpHeaders();
in = new FileInputStream(uploadPath + File.separator + bannerPictureFile);
if (mType != null) {
headers.setContentType(mType);
}
entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
entity = new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
} finally {
in.close();
}
return entity;
}
private MediaType getMediaType(String formatName) {
if(formatName != null) {
if(formatName.equals("JPG")) {
return MediaType.IMAGE_JPEG;
}
if(formatName.equals("GIF")) {
return MediaType.IMAGE_GIF;
}
if(formatName.equals("PNG")) {
return MediaType.IMAGE_PNG;
}
}
return null;
}
}
<file_sep>/DevProject/src/main/java/org/hdcd/common/aop/TimeCheckerAdvice.java
package org.hdcd.common.aop;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TimeCheckerAdvice {
private static final Logger logger = LoggerFactory.getLogger(TimeCheckerAdvice.class);
//14. AOP
//Around 어드바이스
//org.hdcd.service.BoardService 클래스에 속한 임의의 메소드를 대상으로 한다.
@Around("execution(* org.hdcd.service.BoardService*.*(..))")
public Object timeLog(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
logger.info(Arrays.toString(pjp.getArgs()));
Object result = pjp.proceed();
long endTime = System.currentTimeMillis();
logger.info(pjp.getSignature().getName() + " : " + (endTime - startTime));
return result;
}
//메서드 정보 획득
@Before("execution(* org.hdcd.service.BoardService*.*(..))")
public void log(JoinPoint jp) {
//프락시가 입혀지기 전의 원본 대상 객체를 가져온다.
Object targetObject = jp.getTarget();
logger.info("targetObject = " + targetObject);
//프락시를 가져온다.
Object thisObject = jp.getThis();
logger.info("thisObject = " + thisObject);
//인수를 가져온다.
Object[] args = jp.getArgs();
logger.info("args.length = " + args.length);
}
}
<file_sep>/Project/src/main/java/org/hdcd/service/SeatService.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.Seat;
public interface SeatService {
public Seat read(Integer seatNo) throws Exception;
public void modify(Seat seat) throws Exception;
public List<Seat> list(String city, String screenName) throws Exception;
}
<file_sep>/Project/src/main/java/org/hdcd/service/ReplyService.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.Reply;
public interface ReplyService {
public void register(Reply reply) throws Exception;
public Reply read(Integer replyNo) throws Exception;
public void modify(Reply reply) throws Exception;
public void remove(int replyNo) throws Exception;
public List<Reply> list(int boardNo) throws Exception;
}
<file_sep>/Project/src/main/java/org/hdcd/ProjectApplication.java
package org.hdcd;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "org.hdcd.mapper")
public class ProjectApplication {
@PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul"));
}
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
<file_sep>/Project/src/main/java/org/hdcd/service/TheaterService.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.Theater;
public interface TheaterService {
public void register(Theater theater) throws Exception;
public Theater read(Integer theaterNo) throws Exception;
public void modify(Theater theater) throws Exception;
public void remove(Integer theaterNo) throws Exception;
public List<Theater> list() throws Exception;
}
<file_sep>/Project/src/main/java/org/hdcd/service/TimeService.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.common.domain.CodeLabelValue;
import org.hdcd.domain.Time;
public interface TimeService {
public void register(Time time) throws Exception;
public Time read(Integer timeNo) throws Exception;
public void modify(Time time) throws Exception;
public void remove(Integer timeNo) throws Exception;
public List<Time> list() throws Exception;
public List<CodeLabelValue> screenList(String city) throws Exception;
public List<CodeLabelValue> movieList() throws Exception;
}
<file_sep>/DevProject/src/main/java/org/hdcd/service/BoardServiceImpl.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.dao.BoardDAO;
import org.hdcd.domain.Board;
import org.hdcd.exception.BoardRecordNotFoundException;
import org.hdcd.mapper.BoardMapper;
import org.hdcd.repository.BoardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BoardServiceImpl implements BoardService {
//스프링 JDBC
/*
@Autowired
private BoardDAO dao;
*/
//JPA
@Autowired
private BoardRepository boardRepository;
private BoardMapper mapper;
@Override
public void register(Board board) throws Exception {
//dao.create(board);
mapper.create(board);
}
/*
@Override
public Board read(Integer boardNo) throws Exception {
//return dao.read(boardNo);
return mapper.read(boardNo);
}
*/
//16. 예외 처리
//예외 상황
@Override
public Board read(Integer boardNo) throws Exception {
Board board = mapper.read(boardNo);
//게시판의 글이 존재하지 않으면 사용자가 정의한 예외를 발생시킨다.
if(board == null) {
throw new BoardRecordNotFoundException("Not Found boardNo = " + boardNo);
}
return board;
}
@Override
public void modify(Board board) throws Exception {
//dao.update(board);
mapper.update(board);
}
@Override
public void remove(Integer boardNo) throws Exception {
//dao.delete(boardNo);
mapper.delete(boardNo);
}
@Override
public List<Board> list() throws Exception {
//return dao.list();
return mapper.list();
}
@Override
public List<Board> search(String title) throws Exception {
return mapper.search(title);
}
}
<file_sep>/Project/src/main/java/org/hdcd/controller/TheaterController.java
package org.hdcd.controller;
import org.hdcd.domain.Theater;
import org.hdcd.service.TheaterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/theater")
public class TheaterController {
private static final Logger logger = LoggerFactory.getLogger(BannerController.class);
@Autowired
private TheaterService theaterService;
@RequestMapping(value = "/register", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void registerForm(Model model) throws Exception {
logger.info("Theater RegisterForm");
Theater theater = new Theater();
model.addAttribute(theater);
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String register(Theater theater, RedirectAttributes rttr) throws Exception {
logger.info("Theater Register");
theaterService.register(theater);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/theater/list";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void list(Model model) throws Exception {
logger.info("Theater List");
model.addAttribute("list", theaterService.list());
}
@RequestMapping(value = "/read", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void read(int theaterNo, Model model) throws Exception {
logger.info("Theater Read");
Theater theater = theaterService.read(theaterNo);
model.addAttribute(theater);
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String remove(int theaterNo, RedirectAttributes rttr) throws Exception {
logger.info("Theater Remove");
theaterService.remove(theaterNo);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/theater/list";
}
@RequestMapping(value = "/modify", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void modifyForm(int theaterNo, Model model) throws Exception {
logger.info("Theater ModifyForm");
Theater theater = theaterService.read(theaterNo);
model.addAttribute(theater);
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String modify(Theater theater, RedirectAttributes rttr) throws Exception {
logger.info("Theater Modify");
theaterService.modify(theater);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/theater/list";
}
}
<file_sep>/Project/src/main/java/org/hdcd/controller/PointController.java
package org.hdcd.controller;
import java.util.Locale;
import org.hdcd.common.security.domain.CustomUser;
import org.hdcd.domain.ChargePoint;
import org.hdcd.domain.Member;
import org.hdcd.service.PointService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/point")
public class PointController {
private static final Logger logger = LoggerFactory.getLogger(PointController.class);
@Autowired
private PointService service;
@Autowired
private MessageSource messageSource;
@RequestMapping(value = "/charge", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_MEMBER')")
public void chargeForm(Model model) throws Exception {
logger.info("chargeForm");
ChargePoint chargePoint = new ChargePoint();
chargePoint.setAmount(1000);
model.addAttribute(chargePoint);
}
@RequestMapping(value = "/charge", method= RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_MEMBER')")
public String charge(int amount, RedirectAttributes rttr, Authentication authentication) throws Exception {
logger.info("charge");
CustomUser customUser = (CustomUser) authentication.getPrincipal();
Member member = customUser.getMember();
String userId = member.getUserId();
ChargePoint chargePoint = new ChargePoint();
chargePoint.setUserId(userId);
chargePoint.setAmount(amount);
service.charge(chargePoint);
String message = messageSource.getMessage("point.chargingComplete", null, Locale.KOREAN);
rttr.addFlashAttribute("msg", message);
return "redirect:/point/success";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_MEMBER')")
public void list(Model model, Authentication authentication) throws Exception {
logger.info("list");
CustomUser customUser = (CustomUser) authentication.getPrincipal();
Member member = customUser.getMember();
String userId = member.getUserId();
model.addAttribute("list", service.list(userId));
}
@RequestMapping(value = "/success", method = RequestMethod.GET)
public String success() throws Exception {
return "point/success";
}
@RequestMapping(value = "/notEnoughPoint", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_MEMBER')")
public void notEnoughPoint(Model model) throws Exception {
logger.info("notEnoughPoint");
}
@RequestMapping(value = "/listPay", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_MEMBER')")
public void listPayHistory(Model model, Authentication authentication) throws Exception {
CustomUser customUser = (CustomUser)authentication.getPrincipal();
Member member = customUser.getMember();
String userId = member.getUserId();
model.addAttribute("list", service.listPayHistory(userId));
}
}
<file_sep>/Project/src/main/resources/messages.properties
action.charge = \uCDA9\uC804
action.edit = \uD3B8\uC9D1
action.home = \uD648
action.list = \uBAA9\uB85D
action.login = \uB85C\uADF8\uC778
action.logout = \uB85C\uADF8\uC544\uC6C3
action.modify = \uC218\uC815
action.new = \uAE00\uC4F0\uAE30
action.read = \uBCF4\uAE30
action.register = \uB4F1\uB85D
action.remove = \uC0AD\uC81C
action.search = \uAC80\uC0C9
auth.header.login = \uB85C\uADF8\uC778
auth.header.logout = \uB85C\uADF8\uC544\uC6C3
auth.rememberMe = \uB85C\uADF8\uC778 \uC0C1\uD0DC \uC720\uC9C0
banner.bannerName = \uBC30\uB108 \uC774\uB984
banner.bannerNo = \uBC30\uB108 \uBC88\uD638
banner.bannerPicture = \uD64D\uBCF4 \uBC30\uB108 \uC0AC\uC9C4
banner.bannerPictureFile = \uD64D\uBCF4 \uBC30\uB108 \uC0AC\uC9C4 \uD30C\uC77C
banner.list = \uD64D\uBCF4 \uBC30\uB108 \uBAA9\uB85D
banner.new = \uD64D\uBCF4 \uBC30\uB108 \uB4F1\uB85D
banner.movieNo = \uC601\uD654 \uBC88\uD638
banner.movieTitle = \uC601\uD654 \uC81C\uBAA9
board.content = \uB0B4\uC6A9
board.list = \uD68C\uC6D0 \uAC8C\uC2DC\uD310
board.new = \uAE00\uC4F0\uAE30
board.no = \uBC88\uD638
board.title = \uC81C\uBAA9
board.regDate = \uB4F1\uB85D\uC77C\uC790
board.writer = \uC791\uC131\uC790
city.list = \uC601\uD654\uAD00 \uBAA9\uB85D
city.name = \uADF9\uC7A5
city.new = \uADF9\uC7A5 \uB4F1\uB85D
common.error.accessDeniedPage = \uC811\uADFC \uAC70\uBD80 \uC5D0\uB7EC\uAC00 \uBC1C\uC0DD\uD558\uC600\uC2B5\uB2C8\uB2E4.
common.error.backPage = \uC774\uC804\uD398\uC774\uC9C0
common.error.errorOccurred = \uC5D0\uB7EC\uAC00 \uBC1C\uC0DD\uD558\uC600\uC2B5\uB2C8\uB2E4.
common.error.defaultErrorOccurred = \uC5D0\uB7EC\uAC00 \uBC1C\uC0DD\uD558\uC600\uC2B5\uB2C8\uB2E4.
common.error.returnHome = \uD648\uC73C\uB85C \uB3CC\uC544\uAC00\uAE30
common.error.urlNotFound = \uD574\uB2F9 URL\uC740 \uC874\uC7AC\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.
common.listEmpty = \uBAA9\uB85D\uC774 \uBE44\uC5C8\uC2B5\uB2C8\uB2E4.
common.welcome = \uD658\uC601\uD569\uB2C8\uB2E4.
common.joinMemberSuccess = {0}\uB2D8, \uAC00\uC785\uC744 \uCD95\uD558\uB4DC\uB9BD\uB2C8\uB2E4.
header.joinMember = \uD68C\uC6D0\uAC00\uC785
header.login = \uB85C\uADF8\uC778
header.logout = \uB85C\uADF8\uC544\uC6C3
header.mypage = MY
inquiry.content = \uB0B4\uC6A9
inquiry.list = 1:1 \uBB38\uC758 \uBAA9\uB85D
inquiry.new = \uBB38\uC758 \uD558\uAE30
inquiry.no = \uBC88\uD638
inquiry.title = \uC81C\uBAA9
inquiry.regDate = \uB4F1\uB85D\uC77C\uC790
inquiry.replyinquiryno = \uBB38\uC758 \uBC88\uD638
inquiry.replynew = \uB2F5\uBCC0\uD558\uAE30
inquiry.writer = \uC791\uC131\uC790
notice.content = \uB0B4\uC6A9
notice.list = \uACF5\uC9C0\uC0AC\uD56D \uBAA9\uB85D
notice.new = \uACF5\uC9C0\uC0AC\uD56D \uB4F1\uB85D
notice.no = \uBC88\uD638
notice.regDate = \uB4F1\uB85D\uC77C\uC790
notice.title = \uC81C\uBAA9
menu.movie = \uC601\uD654
menu.reservelist = \uC608\uB9E4 \uAD00\uB9AC
menu.reserve = \uC608\uB9E4
menu.theater = \uADF9\uC7A5
movie.actors = \uCD9C\uC5F0
movie.director = \uAC10\uB3C5
movie.enabled = \uC601\uD654 \uC0C1\uC601 \uC0C1\uD0DC
movie.genre = \uC7A5\uB974
movie.list = \uC601\uD654 \uAD00\uB9AC
movie.nation = \uAD6D\uAC00
movie.new = \uC601\uD654 \uB4F1\uB85D
movie.no = \uBC88\uD638
movie.openningDays = \uAC1C\uBD09 \uC77C\uC790
movie.poster = \uC601\uD654 \uD3EC\uC2A4\uD130
movie.posterFile = \uD3EC\uC2A4\uD130 \uD30C\uC77C
movie.ratings = \uC2EC\uC758 \uB4F1\uAE09
movie.runningTime = \uC0C1\uC601 \uC2DC\uAC04
movie.still1 = \uC2A4\uD2F8\uCEF71
movie.still1File = \uC2A4\uD2F8\uCEF7 \uD30C\uC77C 1
movie.still2 = \uC2A4\uD2F8\uCEF72
movie.still2File = \uC2A4\uD2F8\uCEF7 \uD30C\uC77C 2
movie.still3 = \uC2A4\uD2F8\uCEF73
movie.still3File = \uC2A4\uD2F8\uCEF7 \uD30C\uC77C 3
movie.still4 = \uC2A4\uD2F8\uCEF74
movie.still4File = \uC2A4\uD2F8\uCEF7 \uD30C\uC77C 4
movie.summary = \uC601\uD654 \uC904\uAC70\uB9AC
movie.title = \uC601\uD654 \uC81C\uBAA9
mypage.admin.banner = \uD64D\uBCF4 \uBC30\uB108 \uAD00\uB9AC
mypage.admin.board = \uAC8C\uC2DC\uD310 \uAD00\uB9AC
mypage.admin.inquiry = 1:1 \uBB38\uC758 \uAD00\uB9AC
mypage.admin.notice = \uACF5\uC9C0\uC0AC\uD56D \uAD00\uB9AC
mypage.admin.movie = \uC601\uD654 \uAD00\uB9AC
mypage.admin.province = \uC601\uD654\uAD00 \uC9C0\uC5ED \uAD00\uB9AC
mypage.admin.screen = \uC0C1\uC601\uAD00 \uAD00\uB9AC
mypage.admin.theater = \uC601\uD654\uAD00 \uAD00\uB9AC
mypage.admin.time = \uC0C1\uC601 \uAD00\uB9AC
mypage.admin.user = \uD68C\uC6D0 \uAD00\uB9AC
mypage.user.board = \uD68C\uC6D0 \uAC8C\uC2DC\uD310
mypage.user.bill = \uC0AC\uC6A9 \uB0B4\uC5ED
mypage.user.charge = \uCDA9\uC804 \uB0B4\uC5ED
mypage.user.info = \uD68C\uC6D0 \uC815\uBCF4
mypage.user.inquiry = 1:1 \uBB38\uC758
mypage.user.notice = \uACF5\uC9C0\uC0AC\uD56D
mypage.user.modifyPw = \uBE44\uBC00\uBC88\uD638 \uBCC0\uACBD
mypage.user.movie = \uC601\uD654
mypage.user.pay = \uAD6C\uB9E4 \uB0B4\uC5ED
mypage.user.reserveList = \uC608\uB9E4 \uD655\uC778
mypage.user.reserve = \uC601\uD654 \uC608\uB9E4
pay.amount = \uC0AC\uC6A9 \uAE08\uC561
pay.no = \uC0AC\uC6A9 \uBC88\uD638
pay.regDate = \uC0AC\uC6A9 \uB0A0\uC9DC
pay.title = \uC601\uD654
point.amount = \uCDA9\uC804 \uAE08\uC561
point.charge = \uD3EC\uC778\uD2B8 \uCDA9\uC804
point.chargingComplete = \uCDA9\uC804\uC774 \uC644\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
point.header.chargePoint = \uD3EC\uC778\uD2B8 \uCDA9\uC804
point.list = \uCDA9\uC804 \uB0B4\uC5ED
point.no = \uCDA9\uC804 \uBC88\uD638
point.notEnoughPoint = \uD3EC\uC778\uD2B8\uAC00 \uBD80\uC871\uD569\uB2C8\uB2E4.
point.regDate = \uB4F1\uB85D\uC77C\uC790
province.list = \uC601\uD654\uAD00 \uC9C0\uC5ED\ \r\n \uAD00\uB9AC
province.name = \uC9C0\uC5ED
province.no = \uBC88\uD638
province.new = \uC9C0\uC5ED \uB4F1\uB85D
reply.list = \uC804\uCCB4 \uB313\uAE00
reply.register = \uB313\uAE00 \uC4F0\uAE30
reservation.city = \uC601\uD654\uAD00
reservation.movieReserveNo = \uC608\uB9E4 \uBC88\uD638
reservation.price = \uAC00\uACA9
reservation.province = \uC9C0\uC5ED
reserve.reservation = \uC601\uD654 \uC608\uB9E4
reservation.screenName = \uC0C1\uC601\uAD00
reservation.seatId = \uC88C\uC11D
reservation.title = \uC601\uD654
reservation.userId = \uC544\uC774\uB514
review.list = \uD6C4\uAE30 \uBAA9\uB85D
review.register = \uD6C4\uAE30 \uB4F1\uB85D
review.scores = \uD3C9\uC810
screen.col = \uD589
screen.list = \uC0C1\uC601\uAD00 \uAD00\uB9AC
screen.name = \uC0C1\uC601\uAD00 \uC774\uB984
screen.new = \uC0C1\uC601\uAD00 \uB4F1\uB85D
screen.row = \uC5F4
seat.seatId = \uC88C\uC11D\uBA85
seat.price = \uAC00\uACA9
time.city = \uC601\uD654\uAD00
time.date = \uC0C1\uC601\uC77C
time.list = \uC0C1\uC601 \uAD00\uB9AC
time.new = \uC0C1\uC601 \uB4F1\uB85D
time.movie = \uC601\uD654
time.screen = \uC0C1\uC601\uAD00
time.showDate = \uC0C1\uC601\uC77C
time.showTime = \uC0C1\uC601 \uC2DC\uAC04
time.time = \uC2DC\uAC04
time.title = \uC601\uD654
user.findId = \uC544\uC774\uB514 \uCC3E\uAE30
user.findPw = \uBE44\uBC00\uBC88\uD638 \uCC3E\uAE30
user.info = \uD68C\uC6D0 \uC815\uBCF4
user.list = \uD68C\uC6D0 \uBAA9\uB85D
user.new = \uD68C\uC6D0 \uB4F1\uB85D
user.newUserPw = <PASSWORD> \u<PASSWORD>\u<PASSWORD>\u<PASSWORD>\<PASSWORD>
user.modifyPw = \uBE44\uBC00\uBC88\uD638 \uBCC0\uACBD
user.userId = \uC544\uC774\uB514
user.userPw = <PASSWORD>
user.userPwConfirm = \uBE44\uBC00\uBC88\uD638 \uD655\uC778
user.userName = \uC774\uB984
user.userEmail = \uC774\uBA54\uC77C
user.userPhone = \uC804\uD654\uBC88\uD638
user.regDate = \uB4F1\uB85D\uC77C\uC790
<file_sep>/Project/src/main/java/org/hdcd/service/TimeServiceImpl.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.common.domain.CodeLabelValue;
import org.hdcd.domain.Time;
import org.hdcd.mapper.TimeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TimeServiceImpl implements TimeService {
@Autowired
private TimeMapper timeMapper;
@Override
public void register(Time time) throws Exception {
timeMapper.create(time);
}
@Override
public Time read(Integer timeNo) throws Exception {
return timeMapper.read(timeNo);
}
@Override
public void modify(Time time) throws Exception {
timeMapper.update(time);
}
@Override
public void remove(Integer timeNo) throws Exception {
timeMapper.delete(timeNo);
}
@Override
public List<Time> list() throws Exception {
return timeMapper.list();
}
@Override
public List<CodeLabelValue> screenList(String city) throws Exception {
return timeMapper.screenList(city);
}
@Override
public List<CodeLabelValue> movieList() throws Exception {
return timeMapper.movieList();
}
}
<file_sep>/DevProject/src/main/java/org/hdcd/exception/BoardRecordNotFoundException.java
package org.hdcd.exception;
public class BoardRecordNotFoundException extends Exception {
public BoardRecordNotFoundException(String msg) {
super(msg);
}
}
<file_sep>/Project/src/main/java/org/hdcd/service/PointServiceImpl.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.ChargePoint;
import org.hdcd.domain.PayPoint;
import org.hdcd.mapper.PointMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PointServiceImpl implements PointService {
@Autowired
private PointMapper mapper;
@Override
public void charge(ChargePoint chargePoint) throws Exception {
mapper.charge(chargePoint);
mapper.create(chargePoint);
}
@Override
public List<ChargePoint> list(String userId) throws Exception {
return mapper.list(userId);
}
@Override
public List<PayPoint> listPayHistory(String userId) throws Exception {
return mapper.listPayHistory(userId);
}
}
<file_sep>/Project/src/main/java/org/hdcd/service/SeatServiceImpl.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.Seat;
import org.hdcd.mapper.SeatMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SeatServiceImpl implements SeatService {
@Autowired
private SeatMapper seatMapper;
@Override
public Seat read(Integer seatNo) throws Exception {
return seatMapper.read(seatNo);
}
@Override
public void modify(Seat seat) throws Exception {
seatMapper.update(seat);
}
@Override
public List<Seat> list(String city, String screenName) throws Exception {
return seatMapper.list(city, screenName);
}
}
<file_sep>/Project/src/main/java/org/hdcd/controller/MypageController.java
package org.hdcd.controller;
import org.hdcd.common.security.domain.CustomUser;
import org.hdcd.domain.Member;
import org.hdcd.service.MemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/mypage")
public class MypageController {
private static final Logger logger = LoggerFactory.getLogger(MypageController.class);
@Autowired
private MemberService memberService;
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String admin() {
logger.info("Adminpage");
return "mypage/admin";
}
@RequestMapping(value = "/my", method = RequestMethod.GET)
public String my(Model model, Authentication authentication) throws Exception {
logger.info("Mypage");
CustomUser customUser = (CustomUser) authentication.getPrincipal();
Member member = customUser.getMember();
String userId = member.getUserId();
model.addAttribute("mypoint", memberService.getPoint(userId));
model.addAttribute("member", memberService.read(userId));
return "mypage/my";
}
}
<file_sep>/Project/src/main/java/org/hdcd/domain/Screen.java
package org.hdcd.domain;
import java.io.Serializable;
public class Screen implements Serializable {
private static final long serialVersionUID = 5943467863325968361L;
private String provinceName; /*도시 이름*/
private String city; /*상세 도시*/
private int screenNo; /*영화 상영관 번호*/
private String screenName; /*영화 상영관 이름*/
private int screenCol; /*영화 상영관 행*/
private int screenRow; /*영화 상영관 열*/
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getScreenNo() {
return screenNo;
}
public void setScreenNo(int screenNo) {
this.screenNo = screenNo;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public int getScreenCol() {
return screenCol;
}
public void setScreenCol(int screenCol) {
this.screenCol = screenCol;
}
public int getScreenRow() {
return screenRow;
}
public void setScreenRow(int screenRow) {
this.screenRow = screenRow;
}
}
<file_sep>/Project/src/main/java/org/hdcd/controller/NoticeController.java
package org.hdcd.controller;
import java.util.ArrayList;
import java.util.List;
import org.hdcd.common.domain.CodeLabelValue;
import org.hdcd.common.domain.PageRequest;
import org.hdcd.common.domain.Pagination;
import org.hdcd.domain.Notice;
import org.hdcd.service.NoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/notice")
public class NoticeController {
private static final Logger logger = LoggerFactory.getLogger(NoticeController.class);
@Autowired
private NoticeService service;
@RequestMapping(value = "/register", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void registerForm(Model model, Authentication authentication) throws Exception {
logger.info("Notice RegisterForm");
Notice notice = new Notice();
model.addAttribute(notice);
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String register(Notice notice, RedirectAttributes rttr) throws Exception {
logger.info("Notice Register");
service.register(notice);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/notice/list";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public void list(@ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Notice List");
model.addAttribute("list", service.list(pageRequest));
Pagination pagination = new Pagination();
pagination.setPageRequest(pageRequest);
pagination.setTotalCount(service.count(pageRequest));
model.addAttribute("pagination", pagination);
List<CodeLabelValue> searchTypeCodeValueList = new ArrayList<CodeLabelValue>();
searchTypeCodeValueList.add(new CodeLabelValue("n", "---"));
searchTypeCodeValueList.add(new CodeLabelValue("t", "Title"));
searchTypeCodeValueList.add(new CodeLabelValue("c", "Content"));
searchTypeCodeValueList.add(new CodeLabelValue("tc", "Title OR Content"));
model.addAttribute("searchTypeCodeValueList", searchTypeCodeValueList);
}
@RequestMapping(value = "/read", method = RequestMethod.GET)
public void read(int noticeNo, @ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Notice Read");
Notice notice = service.read(noticeNo);
model.addAttribute(notice);
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String remove(int noticeNo, PageRequest pageRequest, RedirectAttributes rttr) throws Exception {
logger.info("Notice Remove");
service.remove(noticeNo);
rttr.addAttribute("page", pageRequest.getPage());
rttr.addAttribute("sizePerPage", pageRequest.getSizePerPage());
rttr.addAttribute("searchType", pageRequest.getSearchType());
rttr.addAttribute("keyword", pageRequest.getKeyword());
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/notice/list";
}
@RequestMapping(value = "/modify", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void modifyForm(int noticeNo, @ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Notice ModifyForm");
Notice notice = service.read(noticeNo);
model.addAttribute(notice);
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String modify(Notice notice, PageRequest pageRequest, RedirectAttributes rttr) throws Exception {
logger.info("Notice Modify");
service.modify(notice);
rttr.addAttribute("page", pageRequest.getPage());
rttr.addAttribute("sizePerPage", pageRequest.getSizePerPage());
rttr.addAttribute("searchType", pageRequest.getSearchType());
rttr.addAttribute("keyword", pageRequest.getKeyword());
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/notice/list";
}
}
<file_sep>/Project/src/main/java/org/hdcd/controller/BoardController.java
package org.hdcd.controller;
import java.util.ArrayList;
import java.util.List;
import org.hdcd.common.domain.CodeLabelValue;
import org.hdcd.common.domain.PageRequest;
import org.hdcd.common.domain.Pagination;
import org.hdcd.common.security.domain.CustomUser;
import org.hdcd.domain.Board;
import org.hdcd.domain.Member;
import org.hdcd.domain.Reply;
import org.hdcd.service.BoardService;
import org.hdcd.service.ReplyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/board")
public class BoardController {
private static final Logger logger = LoggerFactory.getLogger(BoardController.class);
@Autowired
private BoardService service;
@Autowired
private ReplyService replyService;
@RequestMapping(value = "/register", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_MEMBER')")
public void registerForm(Model model, Authentication authentication) throws Exception {
logger.info("Board RegisterForm");
CustomUser customUser = (CustomUser)authentication.getPrincipal();
Member member = customUser.getMember();
Board board = new Board();
board.setWriter(member.getUserId());
model.addAttribute(board);
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_MEMBER')")
public String register(Board board, RedirectAttributes rttr) throws Exception {
logger.info("Board Register");
service.register(board);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/list";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public void list(@ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Board List");
model.addAttribute("list", service.list(pageRequest));
Pagination pagination = new Pagination();
pagination.setPageRequest(pageRequest);
pagination.setTotalCount(service.count(pageRequest));
model.addAttribute("pagination", pagination);
List<CodeLabelValue> searchTypeCodeValueList = new ArrayList<CodeLabelValue>();
searchTypeCodeValueList.add(new CodeLabelValue("n", "---"));
searchTypeCodeValueList.add(new CodeLabelValue("t", "Title"));
searchTypeCodeValueList.add(new CodeLabelValue("c", "Content"));
searchTypeCodeValueList.add(new CodeLabelValue("w", "Writer"));
searchTypeCodeValueList.add(new CodeLabelValue("tc", "Title OR Content"));
searchTypeCodeValueList.add(new CodeLabelValue("cw", "Content OR Writer"));
searchTypeCodeValueList.add(new CodeLabelValue("tcw", "Title OR Content OR Writer"));
model.addAttribute("searchTypeCodeValueList", searchTypeCodeValueList);
}
@RequestMapping(value = "/read", method = RequestMethod.GET)
public void read(int boardNo, @ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Board Read");
Board board = service.read(boardNo);
model.addAttribute(board);
//댓글
logger.info("Board Replylist");
List<Reply> replyList = replyService.list(boardNo);
model.addAttribute("replyList", replyList);
model.addAttribute("reply", new Reply());
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public String remove(int boardNo, PageRequest pageRequest, RedirectAttributes rttr) throws Exception {
logger.info("Board Remove");
service.remove(boardNo);
rttr.addAttribute("page", pageRequest.getPage());
rttr.addAttribute("sizePerPage", pageRequest.getSizePerPage());
rttr.addAttribute("searchType", pageRequest.getSearchType());
rttr.addAttribute("keyword", pageRequest.getKeyword());
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/list";
}
@RequestMapping(value = "/modify", method = RequestMethod.GET)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public void modifyForm(int boardNo, @ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Board ModifyForm");
Board board = service.read(boardNo);
model.addAttribute(board);
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public String modify(Board board, PageRequest pageRequest, RedirectAttributes rttr) throws Exception {
logger.info("Board Modify");
service.modify(board);
rttr.addAttribute("page", pageRequest.getPage());
rttr.addAttribute("sizePerPage", pageRequest.getSizePerPage());
rttr.addAttribute("searchType", pageRequest.getSearchType());
rttr.addAttribute("keyword", pageRequest.getKeyword());
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/list";
}
//댓글
@RequestMapping(value = "/replyregister", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public String replyregister(Reply reply, @RequestParam int boardNo, PageRequest pageRequest, Model model, Authentication authentication, RedirectAttributes rttr) throws Exception {
logger.info("Board Replyregister");
CustomUser customUser = (CustomUser)authentication.getPrincipal();
Member member = customUser.getMember();
reply.setReplyWriter(member.getUserId());
replyService.register(reply);
rttr.addAttribute("page", pageRequest.getPage());
rttr.addAttribute("sizePerPage", pageRequest.getSizePerPage());
rttr.addAttribute("searchType", pageRequest.getSearchType());
rttr.addAttribute("keyword", pageRequest.getKeyword());
rttr.addAttribute("boardNo", boardNo);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/read";
}
@RequestMapping(value = "/replyremove", method = RequestMethod.GET)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public void replyremoveForm(@RequestParam int replyNo, @RequestParam int boardNo, @ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Board ReplyremoveForm");
Reply reply = replyService.read(replyNo);
model.addAttribute(reply);
}
@RequestMapping(value = "/replyremove", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public String replyremove(@RequestParam int replyNo, int boardNo, PageRequest pageRequest, RedirectAttributes rttr) throws Exception {
logger.info("Board Replyremove");
replyService.remove(replyNo);
rttr.addAttribute("page", pageRequest.getPage());
rttr.addAttribute("sizePerPage", pageRequest.getSizePerPage());
rttr.addAttribute("searchType", pageRequest.getSearchType());
rttr.addAttribute("keyword", pageRequest.getKeyword());
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/list";
}
@RequestMapping(value = "/replymodify", method = RequestMethod.GET)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public void replymodifyForm(@RequestParam int replyNo, @RequestParam int boardNo, @ModelAttribute("pgrq") PageRequest pageRequest, Model model) throws Exception {
logger.info("Board ReplymodifyForm");
Reply reply = replyService.read(replyNo);
model.addAttribute(reply);
}
@RequestMapping(value = "/replymodify", method = RequestMethod.POST)
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_MEMBER')")
public String replymodify(Reply reply, @RequestParam int boardNo, PageRequest pageRequest, RedirectAttributes rttr) throws Exception {
logger.info("Board Replymodify");
replyService.modify(reply);
rttr.addAttribute("page", pageRequest.getPage());
rttr.addAttribute("sizePerPage", pageRequest.getSizePerPage());
rttr.addAttribute("searchType", pageRequest.getSearchType());
rttr.addAttribute("keyword", pageRequest.getKeyword());
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/board/list";
}
}<file_sep>/Project/src/main/java/org/hdcd/mapper/PointMapper.java
package org.hdcd.mapper;
import java.util.List;
import org.hdcd.domain.ChargePoint;
import org.hdcd.domain.PayPoint;
public interface PointMapper {
public void create(ChargePoint chargePoint) throws Exception;
public void charge(ChargePoint chargePoint) throws Exception;
public List<ChargePoint> list(String userId) throws Exception;
public void createPayHistory(PayPoint payPoint) throws Exception;
public List<PayPoint> listPayHistory(String userId) throws Exception;
public void pay(PayPoint payPoint) throws Exception;
}
<file_sep>/README.md
# Springboot
스프링부트 연습하기
# 스프링부트 실전
프로젝트 계획서<br>
[계획서.pdf](https://github.com/ggxz88/Springboot/files/5379509/default.pdf)
(+)개발기간 수정<br>
4주차 (11월 01일 ~ 11월 07일) : 프로젝트 기능 제작(영화 관련 등) <br>
5주차 (11월 08일 ~ 11월 14일) : 프로젝트 기능 제작(영화 관련), 최종 테스트 <br>
11월 15일 ~ : 유지보수
<file_sep>/Project/src/main/java/org/hdcd/mapper/ReplyMapper.java
package org.hdcd.mapper;
import java.util.List;
import org.hdcd.domain.Reply;
public interface ReplyMapper {
public void create(Reply reply) throws Exception;
public Reply read(Integer replyNo) throws Exception;
public void update(Reply reply) throws Exception;
public void delete(Integer replyNo) throws Exception;
public List<Reply> list(Integer boardNo) throws Exception;
}
<file_sep>/DevProject/src/main/java/org/hdcd/controller/MemberController.java
package org.hdcd.controller;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.hdcd.domain.Address;
import org.hdcd.domain.Card;
import org.hdcd.domain.CodeLabelValue;
import org.hdcd.domain.FileMember;
import org.hdcd.domain.Member;
import org.hdcd.domain.MemberAuth;
import org.hdcd.domain.MultiFileMember;
import org.hdcd.mapper.MemberMapper;
import org.hdcd.service.MemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@RestController
@Controller
@RequestMapping("/user")
public class MemberController {
private static final Logger logger = LoggerFactory.getLogger(MemberController.class);
//5. 컨트롤러 요청 처리
//요청 처리
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String registerByParameter(String userId, String password) {
logger.info("registerByParameter");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("password = " + password);
// > password = <PASSWORD>
return "success";
}
@RequestMapping(value = "/register/{userId}", method = RequestMethod.GET)
public String registerByPath(String userId) {
logger.info("registerByPath");
logger.info("userId = " + userId);
// > userId = hongkd
return "success";
}
@RequestMapping(value = "/register01", method = RequestMethod.POST)
public String register01(String userId) {
logger.info("register01");
logger.info("userId = " + userId);
// > userId = hongkd
return "success";
}
@RequestMapping(value = "/register02", method = RequestMethod.POST)
public String register02(String userId, String password) {
logger.info("register02");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("password = " + password);
// > password = <PASSWORD>
return "success";
}
@RequestMapping(value = "/register03", method = RequestMethod.POST)
public String register03(String password, String userId) {
logger.info("register03");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("password = " + password);
// > password = <PASSWORD>
return "success";
}
@RequestMapping(value = "/register04", method = RequestMethod.POST)
public String register04(String userId, String password, String coin) {
logger.info("register04");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("password = " + password);
// > password = <PASSWORD>
logger.info("coin = " + coin);
// > coin = 100
return "success";
}
@RequestMapping(value = "/register05", method = RequestMethod.POST)
public String register05(String userId, String password, int coin) {
logger.info("register05");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("password = " + password);
// > password = <PASSWORD>
logger.info("coin = " + coin);
// > coin = 100
return "success";
}
*/
//요청 처리 데이터 애너테이션
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/register/{userId}", method = RequestMethod.GET)
public String registerByPath(String userId) {
logger.info("registerByPath");
logger.info("userId = " + userId);
// > userId = hongkd
return "success";
}
@RequestMapping(value = "/register/{userId}/{coin}", method = RequestMethod.GET)
public String registerByPath(@PathVariable("userId") String userId, @PathVariable("coin") int coin) {
logger.info("registerByPath");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("coin = " + coin);
// > coin = 100
return "success";
}
@RequestMapping(value = "/register01", method = RequestMethod.POST)
public String register01(String userId) {
logger.info("register01");
logger.info("userId = " + userId);
// > userId = hongkd
return "success";
}
@RequestMapping(value = "/register0201", method = RequestMethod.POST)
public String register0201(String username) {
logger.info("register0201");
logger.info("userId = " + username);
// > userId = null
return "success";
}
@RequestMapping(value = "/register0202", method = RequestMethod.POST)
public String register0202(@RequestParam("userId") String username) {
logger.info("register0202");
logger.info("userId = " + username);
// > userId = null
return "success";
}
@RequestMapping(value = "/register0301", method = RequestMethod.POST)
public String register0301(String memberId) {
logger.info("register0301");
logger.info("userId = " + memberId);
// > userId = null
return "success";
}
@RequestMapping(value = "/register0302", method = RequestMethod.POST)
public String register0302(@RequestParam("userId") String memberId) {
logger.info("register0302");
logger.info("userId = " + memberId);
// > userId = null
return "success";
}
*/
//요청 처리 자바빈즈
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/register01", method = RequestMethod.POST)
public String register01(Member member) {
logger.info("register01");
logger.info("member.getUserId() = " + member.getUserId());
// > member.getUserId() = hongkd
logger.info("member.getPassword() = " + member.getPassword());
// > member.getPassword() = <PASSWORD>
logger.info("member.getCoin() = " + member.getCoin());
// > member.getCoin() = 100
return "success";
}
@RequestMapping(value = "/register02", method = RequestMethod.POST)
public String register02(Member member, int coin) {
logger.info("register02");
logger.info("member.getUserId() = " + member.getUserId());
// > member.getUserId() = hongkd
logger.info("member.getPassword() = " + member.getPassword());
// > member.getPassword() = <PASSWORD>
logger.info("member.getCoin() = " + member.getCoin());
// > member.getCoin() = 100
logger.info("coin = " + coin);
// > coin = 100
return "success";
}
@RequestMapping(value = "/register03", method = RequestMethod.POST)
public String register03(int uid, Member member) {
logger.info("register03");
logger.info("uid = " + uid);
// > uid = 50
logger.info("member.getUserId() = " + member.getUserId());
// > member.getUserId() = hongkd
logger.info("member.getPassword() = " + member.getPassword());
// > member.getPassword() = <PASSWORD>
logger.info("member.getCoin() = " + member.getCoin());
// > member.getCoin() = 100
return "success";
}
*/
//Date 타입 처리
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/registerByGet01", method = RequestMethod.GET)
public String registerByGet01(String userId, Date dateOfBirth) {
logger.info("registerByGet01");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("dateOfBirth = " + dateOfBirth);
// > dateOfBirth = Sat Sep 08 00:00:00 KST 2018
return "success";
}
@RequestMapping(value = "/registerByGet02", method = RequestMethod.GET)
public String registerByGet02(Member member) {
logger.info("registerByGet02");
logger.info("member.getUserId() = " + member.getUserId());
// > member.getUserId() = hongkd
logger.info("member.getDateOfBirth() = " + member.getDateOfBirth());
// > member.getDateOfBirth() = Sat Sep 08 00:00:00 KST 2018
return "success";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getUserId() = " + member.getUserId());
// > member.getUserId() = hongkd
logger.info("member.getPassword() = " + member.getPassword());
// > member.getPassword() = <PASSWORD>
logger.info("member.getDateOfBirth() = " + member.getDateOfBirth());
// > member.getDateOfBirth() = Sat Sep 08 00:00:00 KST 2018
return "success";
}
*/
//@DateTimeFormat 애너테이션
/*
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getUserId() = " + member.getUserId());
// > member.getUserId() = hongkd
logger.info("member.getPassword() = " + member.getPassword());
// > member.getPassword() = <PASSWORD>
logger.info("member.getDateOfBirth() = " + member.getDateOfBirth());
// > member.getDateOfBirth() = Sat Sep 08 00:00:00 KST 2018
return "success";
}
@RequestMapping(value = "/registerByGet01", method = RequestMethod.GET)
public String registerByGet01(String userId, @DateTimeFormat(pattern="yyyMMdd") Date dateOfBirth) {
logger.info("registerByGet01");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("dateOfBirth = " + dateOfBirth);
// > dateOfBirth = Sat Sep 08 00:00:00 KST 2018
return "success";
}
@RequestMapping(value = "/registerByGet02", method = RequestMethod.GET)
public String registerByGet02(Member member) {
logger.info("registerByGet02");
logger.info("member.getUserId() = " + member.getUserId());
// > member.getUserId() = hongkd
logger.info("member.getDateOfBirth() = " + member.getDateOfBirth());
// > member.getDateOfBirth() = Sat Sep 08 00:00:00 KST 2018
return "success";
}
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
*/
//폼 방식 요청 처리
/*
@RequestMapping(value = "/registerAllForm", method = RequestMethod.GET)
public String registerAllForm() {
logger.info("registerAllForm");
return "registerAllForm";
}
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/registerMemberUserId", method = RequestMethod.POST)
public String registerMemberUserId(Member member) {
logger.info("registerUserId");
logger.info("member.getUserId() = " + member.getUserId());
return "registerForm";
}
@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public String registerUser(Member member) {
logger.info("registerUser");
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getGender() = " + member.getGender());
logger.info("member.getHobby() = " + member.getHobby());
logger.info("member.getForeigner() = " + member.getForeigner());
logger.info("member.getDeveloper() = " + member.getDeveloper());
logger.info("member.getDateOfBirth() = " + member.getDateOfBirth());
logger.info("member.getCars() = " + member.getCars());
logger.info("member.getIntroduction() = " + member.getIntroduction());
String[] hobbyArray = member.getHobbyArray();
if(hobbyArray != null) {
logger.info("hobbyArray.length = " + hobbyArray.length);
for(int i = 0; i< hobbyArray.length; i++) {
logger.info("hobbyArray[" + i +"] = " + hobbyArray[i]);
}
}
else {
logger.info("hobbyArray == null");
}
List<String> hobbyList = member.getHobbyList();
if(hobbyList != null) {
logger.info("hobbyList.size() = " + hobbyList.size());
for(int i = 0; i< hobbyList.size(); i++) {
logger.info("hobbyList(" + i +") = " + hobbyList.get(i));
}
}
else {
logger.info("hobbyList == null");
}
Address address = member.getAddress();
if(address != null) {
logger.info("address.getPostCode() = " + address.getPostCode());
logger.info("address.getLocation() = " + address.getLocation());
}
else {
logger.info("address == null");
}
List<Card> cardList = member.getCardList();
if(cardList != null) {
logger.info("cardList.size() = " + cardList.size());
for(int i = 0; i< cardList.size(); i++) {
Card card = cardList.get(i);
logger.info("card.getNo() = " + card.getNo());
logger.info("card.getValidMonth() = " + card.getValidMonth());
}
}
else {
logger.info("cardList == null");
}
String[] carArray = member.getCarArray();
if(carArray != null) {
logger.info("carArray.length = " + carArray.length);
for(int i = 0; i< carArray.length; i++) {
logger.info("carArray[" + i +"] = " + carArray[i]);
}
}
else {
logger.info("carArray == null");
}
List<String> carList = member.getCarList();
if(carList != null) {
logger.info("carList.size() = " + carList.size());
for(int i = 0; i< carList.size(); i++) {
logger.info("carList(" + i +") = " + carList.get(i));
}
}
else {
logger.info("carList == null");
}
return "success";
}
@RequestMapping(value= "/registerUserId", method = RequestMethod.POST)
public String registerUserId(String userId) {
logger.info("registerUserId");
logger.info("userId = " + userId);
return "success";
}
@RequestMapping(value= "/registerPassword", method = RequestMethod.POST)
public String registerPassword(String password) {
logger.info("registerPassword");
logger.info("password = " + password);
return "success";
}
@RequestMapping(value= "/registerTextArea", method = RequestMethod.POST)
public String registerTextArea(String introduction) {
logger.info("registerTextArea");
logger.info("introduction = " + introduction);
return "success";
}
@RequestMapping(value= "/registerRadio", method = RequestMethod.POST)
public String registerRadio(String gender) {
logger.info("registerRadio");
logger.info("gender = " + gender);
return "success";
}
@RequestMapping(value= "/registerCheckbox01", method = RequestMethod.POST)
public String registerCheckbox01(String hobby) {
logger.info("registerCheckbox01");
logger.info("hobby = " + hobby);
return "success";
}
@RequestMapping(value= "/registerCheckbox02", method = RequestMethod.POST)
public String registerCheckbox02(String[] hobbyArray) {
logger.info("registerCheckbox02");
if(hobbyArray != null) {
logger.info("hobbyArray.length = " + hobbyArray.length);
for(int i = 0; i< hobbyArray.length; i++) {
logger.info("hobbyArray[" + i +"] = " + hobbyArray[i]);
}
}
else {
logger.info("hobbyArray == null");
}
return "success";
}
@RequestMapping(value= "/registerCheckbox03", method = RequestMethod.POST)
public String registerCheckbox03(List<String> hobbyList) {
logger.info("registerCheckbox03");
if(hobbyList != null) {
logger.info("hobbyList.size() = " + hobbyList.size());
for(int i = 0; i< hobbyList.size(); i++) {
logger.info("hobbyList(" + i +") = " + hobbyList.get(i));
}
}
else {
logger.info("hobbyList == null");
}
return "success";
}
@RequestMapping(value= "/registerCheckbox04", method = RequestMethod.POST)
public String registerCheckbox04(String developer) {
logger.info("registerCheckbox04");
logger.info("developer = " + developer);
return "success";
}
@RequestMapping(value= "/registerCheckbox05", method = RequestMethod.POST)
public String registerCheckbox05(String foreigner) {
logger.info("registerCheckbox05");
logger.info("foreigner = " + foreigner);
return "success";
}
@RequestMapping(value= "/registerSelect", method = RequestMethod.POST)
public String registerSelect(String nationality) {
logger.info("registerSelect");
logger.info("nationality = " + nationality);
return "success";
}
@RequestMapping(value= "/registerMultipleSelect01", method = RequestMethod.POST)
public String registerMultipleSelect01(String cars) {
logger.info("registerMultipleSelect01");
logger.info("cars = " + cars);
return "success";
}
@RequestMapping(value= "/registerMultipleSelect02", method = RequestMethod.POST)
public String registerMultipleSelect02(String[] carArray) {
logger.info("registerMultipleSelect02");
if(carArray != null) {
logger.info("carArray.length = " + carArray.length);
for(int i = 0; i< carArray.length; i++) {
logger.info("carArray[" + i +"] = " + carArray[i]);
}
}
else {
logger.info("carArray == null");
}
return "success";
}
@RequestMapping(value= "/registerMultipleSelect03", method = RequestMethod.POST)
public String registerMultipleSelect03(ArrayList<String> carList) {
logger.info("registerMultipleSelect03");
if(carList != null) {
logger.info("carList.size() = " + carList.size());
for(int i = 0; i< carList.size(); i++) {
logger.info("carList(" + i +") = " + carList.get(i));
}
}
else {
logger.info("carList == null");
}
return "success";
}
@RequestMapping(value= "/registerAddress", method = RequestMethod.POST)
public String registerAddress(Address address) {
logger.info("registerAddress");
if(address != null) {
logger.info("address.getPostCode() = " + address.getPostCode());
logger.info("address.getLocation() = " + address.getLocation());
}
else {
logger.info("address == null");
}
return "success";
}
@RequestMapping(value= "/registerUserAddress", method = RequestMethod.POST)
public String registerUserAddress(Member member) {
logger.info("registerUserAddress");
Address address = member.getAddress();
if(address != null) {
logger.info("address.getPostCode() = " + address.getPostCode());
logger.info("address.getLocation() = " + address.getLocation());
}
else {
logger.info("address == null");
}
return "success";
}
@RequestMapping(value= "/registerUserCardList", method = RequestMethod.POST)
public String registerUserCardList(Member member) {
logger.info("registerUserCardList");
List<Card> cardList = member.getCardList();
if(cardList != null) {
logger.info("cardList.size() = " + cardList.size());
for(int i = 0; i< cardList.size(); i++) {
Card card = cardList.get(i);
logger.info("card.getNo() = " + card.getNo());
logger.info("card.getValidMonth() = " + card.getValidMonth());
}
}
else {
logger.info("cardList == null");
}
return "success";
}
@RequestMapping(value= "/registerDate01", method = RequestMethod.POST)
public String registerDate01(Date dateOfBirth) {
logger.info("registerDate01");
if(dateOfBirth != null) {
logger.info("dateOfBirth = " + dateOfBirth);
}
else {
logger.info("dateOfBirth == null");
}
return "success";
}
@RequestMapping(value= "/registerDate02", method = RequestMethod.POST)
public String registerDate02(@DateTimeFormat(pattern="yyyyMMdd") Date dateOfBirth) {
logger.info("registerDate02");
if(dateOfBirth != null) {
logger.info("dateOfBirth = " + dateOfBirth);
}
else {
logger.info("dateOfBirth == null");
}
return "success";
}
*/
//파일업로드 폼 방식 요청 처리
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/registerFile01", method = RequestMethod.POST)
public String registerFile01(MultipartFile picture) throws Exception {
logger.info("registerFile01");
logger.info("originalName: " + picture.getOriginalFilename());
logger.info("size: " + picture.getSize());
logger.info("contentTye: " + picture.getContentType());
return "success";
}
@RequestMapping(value = "/registerFile02", method = RequestMethod.POST)
public String registerFile02(String userId, String password, MultipartFile picture) throws Exception {
logger.info("registerFile02");
logger.info("userId = " + userId);
logger.info("password = " + password);
logger.info("originalName: " + picture.getOriginalFilename());
logger.info("size: " + picture.getSize());
logger.info("contentTye: " + picture.getContentType());
return "success";
}
@RequestMapping(value = "/registerFile03", method = RequestMethod.POST)
public String registerFile03(Member member, MultipartFile picture) throws Exception {
logger.info("registerFile03");
logger.info("userId = " + member.getUserId());
logger.info("password = " + member.getPassword());
logger.info("originalName: " + picture.getOriginalFilename());
logger.info("size: " + picture.getSize());
logger.info("contentTye: " + picture.getContentType());
return "success";
}
@RequestMapping(value = "/registerFile04", method = RequestMethod.POST)
public String registerFile04(FileMember fileMember) throws Exception {
logger.info("registerFile04");
logger.info("userId = " + fileMember.getUserId());
logger.info("password = " + fileMember.getPassword());
MultipartFile picture = fileMember.getPicture();
logger.info("originalName: " + picture.getOriginalFilename());
logger.info("size: " + picture.getSize());
logger.info("contentTye: " + picture.getContentType());
return "success";
}
@RequestMapping(value = "/registerFile05", method = RequestMethod.POST)
public String registerFile05(MultipartFile picture, MultipartFile picture2) throws Exception {
logger.info("registerFile05");
logger.info("originalName: " + picture.getOriginalFilename());
logger.info("size: " + picture.getSize());
logger.info("contentTye: " + picture.getContentType());
logger.info("originalName: " + picture2.getOriginalFilename());
logger.info("size: " + picture2.getSize());
logger.info("contentTye: " + picture2.getContentType());
return "success";
}
@RequestMapping(value = "/registerFile06", method = RequestMethod.POST)
public String registerFile06(List<MultipartFile> pictureList) throws Exception {
logger.info("registerFile06");
logger.info("registerFile06 pictureList.size() = " + pictureList.size());
for(MultipartFile picture : pictureList) {
logger.info("picture originalName: " + picture.getOriginalFilename());
logger.info("picture size: " + picture.getSize());
logger.info("picture contentTye: " + picture.getContentType());
}
return "success";
}
@RequestMapping(value = "/registerFile07", method = RequestMethod.POST)
public String registerFile07(MultiFileMember multiFileMember) throws Exception {
logger.info("registerFile07");
List<MultipartFile> pictureList = multiFileMember.getPictureList();
logger.info("registerFile07 pictureList.size() = " + pictureList.size());
for(MultipartFile picture : pictureList) {
logger.info("picture originalName: " + picture.getOriginalFilename());
logger.info("picture size: " + picture.getSize());
logger.info("picture contentTye: " + picture.getContentType());
}
return "success";
}
@RequestMapping(value = "/registerFile08", method = RequestMethod.POST)
public String registerFile08(MultipartFile[] pictureList) throws Exception {
logger.info("registerFile08");
logger.info("registerFile08 pictureList.length = " + pictureList.length);
for(MultipartFile picture : pictureList) {
logger.info("picture originalName: " + picture.getOriginalFilename());
logger.info("picture size: " + picture.getSize());
logger.info("picture contentTye: " + picture.getContentType());
}
return "success";
}
*/
//Ajax 방식 요청 처리
/*
@RequestMapping(value = "/register/{userId}", method = RequestMethod.GET)
public ResponseEntity<String> register01(@PathVariable("userId") String userId) {
logger.info("register01");
logger.info("userId = " + userId);
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value = "/register/{userId}/{password}", method = RequestMethod.POST)
public ResponseEntity<String> register02(@PathVariable("userId") String userId, @PathVariable("password") String password) {
logger.info("register02");
logger.info("userId = " + userId);
logger.info("password = " + password);
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value = "/register03", method = RequestMethod.POST)
public ResponseEntity<String> register03(@RequestBody Member member) {
logger.info("register03");
logger.info("userId = " + member.getUserId());
logger.info("password = " + member.getPassword());
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value = "/register04", method = RequestMethod.POST)
public ResponseEntity<String> register04(String userId) {
logger.info("register03");
logger.info("userId = " + userId);
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value = "/register05", method = RequestMethod.POST)
public ResponseEntity<String> register05(String userId, String password) {
logger.info("register05");
logger.info("userId = " + userId);
logger.info("password = " + password);
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value = "/register/{userId}", method = RequestMethod.POST)
public ResponseEntity<String> register06(@PathVariable("userId") String userId, @RequestBody Member member) {
logger.info("register06");
logger.info("userId = " + userId);
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getPassword() = " + member.getPassword());
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value = "/register07", method = RequestMethod.POST)
public ResponseEntity<String> register07(@RequestBody List<Member> memberList) {
logger.info("register07");
for(Member member : memberList) {
logger.info("userId = " + member.getUserId());
logger.info("password = " + member.getPassword());
}
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value= "/register08", method = RequestMethod.POST)
public ResponseEntity<String> register08(@RequestBody Member member) {
logger.info("register08");
logger.info("userId = " + member.getUserId());
logger.info("password = " + member.getPassword());
Address address = member.getAddress();
if(address != null) {
logger.info("address.getPostCode() = " + address.getPostCode());
logger.info("address.getLocation() = " + address.getLocation());
}
else {
logger.info("address == null");
}
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
@RequestMapping(value= "/register09", method = RequestMethod.POST)
public ResponseEntity<String> register09(@RequestBody Member member) {
logger.info("register09");
logger.info("userId = " + member.getUserId());
logger.info("password = " + member.getPassword());
List<Card> cardList = member.getCardList();
if(cardList != null) {
logger.info("cardList.size() = " + cardList.size());
for(int i = 0; i< cardList.size(); i++) {
Card card = cardList.get(i);
logger.info("card.getNo() = " + card.getNo());
logger.info("card.getValidMonth() = " + card.getValidMonth());
}
}
else {
logger.info("cardList == null");
}
ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
return entity;
}
*/
//파일업로드 Ajax 방식 요청 처리
/*
@RequestMapping(value = "/uploadAjax", method = RequestMethod.POST, produces = "text/plain; charset=UTF-8")
public ResponseEntity<String> uploadAjax(MultipartFile file) throws Exception {
String originalFilename = file.getOriginalFilename();
logger.info("originalName: " + originalFilename);
ResponseEntity<String> entity = new ResponseEntity<String>("UPLOAD SUCCESS" + originalFilename, HttpStatus.OK);
return entity;
}
*/
//6. 데이터 전달자 모델
//모델을 통한 데이터 전달
/*
@RequestMapping(value = "/read01", method = RequestMethod.GET)
public String read01(Model model) {
logger.info("read01");
model.addAttribute("userId", "hongkd");
model.addAttribute("password", "<PASSWORD>");
model.addAttribute("email", "<EMAIL>");
model.addAttribute("userName", "홍길동");
model.addAttribute("birthDay", "1989-09-07");
return "read01";
}
@RequestMapping(value = "/read02", method = RequestMethod.GET)
public String read02(Model model) {
logger.info("read02");
Member member = new Member();
member.setUserId("hongkd");
member.setPassword("<PASSWORD>");
member.setEmail("<EMAIL>");
member.setUserName("홍길동");
member.setBirthDay("1989-09-07");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DAY_OF_MONTH, 7);
member.setDateOfBirth(cal.getTime());
model.addAttribute(member);
return "read02";
}
@RequestMapping(value = "/read03", method = RequestMethod.GET)
public String read03(Model model) {
logger.info("read03");
Member member = new Member();
member.setUserId("hongkd");
member.setPassword("<PASSWORD>");
member.setEmail("<EMAIL>");
member.setUserName("홍길동");
member.setBirthDay("1989-09-07");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DAY_OF_MONTH, 7);
member.setDateOfBirth(cal.getTime());
model.addAttribute("user", member);
return "read03";
}
@RequestMapping(value = "/read04", method = RequestMethod.GET)
public String read04(Model model) {
logger.info("read04");
String[] carArray = {"saab", "audi"};
List<String> carList = new ArrayList<String>();
carList.add("saab");
carList.add("audi");
String[] hobbyArray = {"Music", "Movie"};
List<String> hobbyList = new ArrayList<String>();
hobbyList.add("Music");
hobbyList.add("Movie");
model.addAttribute("carArray", carArray);
model.addAttribute("carList", carList);
model.addAttribute("hobbyArray", hobbyArray);
model.addAttribute("hobbyList", hobbyList);
return "read04";
}
@RequestMapping(value = "/read05", method = RequestMethod.GET)
public String read05(Model model) {
logger.info("read05");
Member member = new Member();
Address address = new Address();
address.setPostCode("080908");
address.setLocation("seoul");
member.setAddress(address);
List<Card> cardList = new ArrayList<Card>();
Card card1 = new Card();
card1.setNo("123456");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2020);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DAY_OF_MONTH, 8);
card1.setValidMonth(cal.getTime());
cardList.add(card1);
Card card2 = new Card();
card2.setNo("456789");
cal.set(Calendar.YEAR, 2022);
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DAY_OF_MONTH, 7);
card2.setValidMonth(cal.getTime());
cardList.add(card2);
member.setCardList(cardList);
model.addAttribute("user", member);
return "read05";
}
@RequestMapping(value = "/read06", method = RequestMethod.GET)
public String read06(Model model) {
logger.info("read06");
Member member = new Member();
member.setUserId("hongkd");
member.setPassword("<PASSWORD>");
member.setEmail("<EMAIL>");
member.setUserName("홍길동");
member.setBirthDay("1989-09-07");
member.setGender("female");
member.setDeveloper("Y");
member.setForeigner(true);
member.setNationality("Austraila");
//user.setCars("saab, audi");
member.setCars("saab");
String[] carArray = {"saab", "audi"};
member.setCarArray(carArray);
List<String> carList = new ArrayList<String>();
carList.add("saab");
carList.add("audi");
member.setCarList(carList);
member.setHobby("Movie");
String[] hobbyArray = {"Music", "Movie"};
member.setHobbyArray(hobbyArray);
List<String> hobbyList = new ArrayList<String>();
hobbyList.add("Music");
hobbyList.add("Movie");
member.setHobbyList(hobbyList);
Address address = new Address();
address.setPostCode("080908");
address.setLocation("seoul");
member.setAddress(address);
List<Card> cardList = new ArrayList<Card>();
Card card1 = new Card();
card1.setNo("123456");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2020);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DAY_OF_MONTH, 8);
card1.setValidMonth(cal.getTime());
cardList.add(card1);
Card card2 = new Card();
card2.setNo("456789");
cal.set(Calendar.YEAR, 2022);
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DAY_OF_MONTH, 7);
card2.setValidMonth(cal.getTime());
cardList.add(card2);
member.setCardList(cardList);
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DAY_OF_MONTH, 7);
member.setDateOfBirth(cal.getTime());
String introduction = "안녕하세요.\n반갑습니다.";
member.setIntroduction(introduction);
model.addAttribute("user", member);
return "read06";
}
*/
//@ModelAttribute 애너테이션
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/register01", method = RequestMethod.POST)
public String register01(String userId) {
logger.info("register01");
logger.info("userId = " + userId);
// > userId = hongkd
return "result01";
}
@RequestMapping(value = "/register02", method = RequestMethod.POST)
public String register02(@ModelAttribute("userId") String userId) {
logger.info("register02");
logger.info("userId = " + userId);
// > userId = hongkd
return "result02";
}
@RequestMapping(value = "/register03", method = RequestMethod.POST)
public String register03(@ModelAttribute("userId") String userId, @ModelAttribute("password") String password) {
logger.info("register03");
logger.info("userId = " + userId);
// > userId = hongkd
logger.info("password = " + password);
// > password = <PASSWORD>
return "result03";
}
@RequestMapping(value = "/register04", method = RequestMethod.POST)
public String register04(Member member) {
logger.info("register04");
logger.info("userId = " + member.getUserId());
// > userId = hongkd
logger.info("password = " + member.getPassword());
// > password = <PASSWORD>
return "result04";
}
*/
//RedirectAttributes 타입
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm() {
logger.info("registerForm");
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member, RedirectAttributes rttr) throws Exception {
logger.info("register");
rttr.addFlashAttribute("msg", "success");
return "registerForm";
}
@RequestMapping(value = "/result", method = RequestMethod.GET)
public String result() {
logger.info("result");
return "result";
}
*/
//8. 스프링 폼
//폼 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01() {
logger.info("registerForm01");
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
//화면에 전달할 데이터를 위해 모델을 매개변수로 지정한다.
public String registerForm02(Model model) {
logger.info("registerForm02");
//속성명에 'member'를 지정하고 폼 객체를 모델에 추가한다.
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm03", method = RequestMethod.GET)
//화면에 전달할 데이터를 위해 모델을 매개변수로 지정한다.
public String registerForm03(Model model) {
logger.info("registerForm03");
//속성명에 'user'를 지정하고 폼 객체를 모델에 추가한다.
model.addAttribute("user", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm04", method = RequestMethod.GET)
//화면에 전달할 데이터를 위해 모델을 매개변수로 지정한다.
public String registerForm04(Model model) {
logger.info("registerForm04");
//속성명에 'user'를 지정하고 폼 객체를 모델에 추가한다.
model.addAttribute("user", new Member());
return "registerForm2";
}
@RequestMapping(value = "/registerForm05", method = RequestMethod.GET)
//컨트롤러는 기본적으로 자바빈즈 규칙에 맞는 객체는 다시 화면으로 폼 객체를 전달한다.
public String registerForm05(Member member) {
logger.info("registerForm05");
return "registerForm";
}
@RequestMapping(value = "/registerForm06", method = RequestMethod.GET)
//폼 객체의 속성명은 매개변수로 전달된 자바빈즈 클래스의 타입명을 이용하여 만든다.
public String registerForm06(Member user) {
logger.info("registerForm06");
return "registerForm";
}
@RequestMapping(value = "/registerForm07", method = RequestMethod.GET)
//폼 객체의 속성명은 매개변수로 전달된 자바빈즈 클래스의 타입명을 이용하여 만든다.
public String registerForm07(@ModelAttribute("user") Member member) {
logger.info("registerForm07");
return "registerForm";
}
@RequestMapping(value = "/registerForm08", method = RequestMethod.GET)
//폼 객체의 속성명은 매개변수로 전달된 자바빈즈 클래스의 타입명을 이용하여 만든다.
public String registerForm08(@ModelAttribute("user") Member member) {
logger.info("registerForm08");
return "registerForm2";
}
@RequestMapping(value = "/registerForm09", method = RequestMethod.GET)
//화면에 전달할 데이터를 위해 모델을 매개변수로 지정한다.
public String registerForm09(Model model) {
logger.info("registerForm09");
Member member = new Member();
//폼 객체의 프로퍼티에 값을 지정한다.
member.setUserId("hongkd");
member.setUserName("홍길동");
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getUserName() = " + member.getUserName());
return "result";
}
*/
//텍스트 필드 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
Member member = new Member();
member.setEmail("<EMAIL>");
member.setUserName("홍길동");
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getUserName() = " + member.getUserName());
logger.info("member.getEmail() = " + member.getEmail());
return "result";
}
*/
//패스워드 필드 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
Member member = new Member();
member.setPassword("<PASSWORD>");
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getPassword() = " + member.getPassword());
return "result";
}
*/
//텍스트 영역 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
Member member = new Member();
String introduction = "안녕하세요.\n반갑습니다.";
member.setIntroduction(introduction);
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getIntroduction() = " + member.getIntroduction());
return "result";
}
*/
//여러 개의 체크박스 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
Map<String, String> hobbyMap = new HashMap<String, String>();
hobbyMap.put("01", "Sports");
hobbyMap.put("02", "Music");
hobbyMap.put("03", "Movie");
model.addAttribute("hobbyMap", hobbyMap);
model.addAttribute("member", new Member());
return "registerForm01";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
List<CodeLabelValue> hobbyCodeList = new ArrayList<CodeLabelValue>();
hobbyCodeList.add(new CodeLabelValue("01", "Sports"));
hobbyCodeList.add(new CodeLabelValue("02", "Music"));
hobbyCodeList.add(new CodeLabelValue("03", "Movie"));
model.addAttribute("hobbyCodeList", hobbyCodeList);
model.addAttribute("member", new Member());
return "registerForm02";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
List<String> hobbyList = member.getHobbyList();
if(hobbyList != null) {
logger.info("hobbyList != null = " + hobbyList.size());
for(int i = 0; i< hobbyList.size(); i++) {
logger.info("hobbyList(" + i + ") = " + hobbyList.get(i));
}
}
else {
logger.info("hobbyList == null");
}
return "result";
}
*/
//체크박스 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
Member member = new Member();
member.setDeveloper("Y");
member.setForeigner(true);
member.setHobby("Movie");
String[] hobbyArray = {"Music", "Movie"};
member.setHobbyArray(hobbyArray);
List<String> hobbyList = new ArrayList<String>();
hobbyList.add("Music");
hobbyList.add("Movie");
member.setHobbyList(hobbyList);
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.isForeigner() = " + member.isForeigner());
logger.info("member.getDeveloper() = " + member.getDeveloper());
logger.info("member.getHobby() = " + member.getHobby());
String[] hobbyArray = member.getHobbyArray();
if(hobbyArray != null) {
logger.info("hobbyArray != null = " + hobbyArray.length);
for(int i = 0; i< hobbyArray.length; i++) {
logger.info("hobbyArray[" + i + "] = " + hobbyArray[i]);
}
}
else {
logger.info("hobbyArray == null");
}
List<String> hobbyList = member.getHobbyList();
if(hobbyList != null) {
logger.info("hobbyList != null = " + hobbyList.size());
for(int i = 0; i< hobbyList.size(); i++) {
logger.info("hobbyList(" + i + ") = " + hobbyList.get(i));
}
}
else {
logger.info("hobbyList == null");
}
return "result";
}
*/
//여러 개의 라디오 버튼 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
Map<String, String> genderCodeMap = new HashMap<String, String>();
genderCodeMap.put("01", "Male");
genderCodeMap.put("02", "Female");
genderCodeMap.put("03", "Other");
model.addAttribute("genderCodeMap", genderCodeMap);
model.addAttribute("member", new Member());
return "registerForm01";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
List<CodeLabelValue> genderCodeList = new ArrayList<CodeLabelValue>();
genderCodeList.add(new CodeLabelValue("01", "Male"));
genderCodeList.add(new CodeLabelValue("02", "Female"));
genderCodeList.add(new CodeLabelValue("03", "Other"));
model.addAttribute("genderCodeList", genderCodeList);
model.addAttribute("member", new Member());
return "registerForm02";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member, Model model) {
logger.info("register");
logger.info("member.getGender() = " + member.getGender());
model.addAttribute("gender", member.getGender());
return "result";
}
*/
//라디오 버튼 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
Member member = new Member();
member.setGender("female");
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member, Model model) {
logger.info("register");
logger.info("member.getGender() = " + member.getGender());
model.addAttribute("member", member);
return "result";
}
*/
//셀렉트 박스 요소
/*
@RequestMapping(value = "/registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
Map<String, String> nationalityCodeMap = new HashMap<String, String>();
nationalityCodeMap.put("01", "Korea");
nationalityCodeMap.put("02", "Germany");
nationalityCodeMap.put("03", "Australia");
model.addAttribute("nationalityCodeMap", nationalityCodeMap);
model.addAttribute("member", new Member());
return "registerForm01";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
List<CodeLabelValue> nationalityCodeList = new ArrayList<CodeLabelValue>();
nationalityCodeList.add(new CodeLabelValue("01", "Korea"));
nationalityCodeList.add(new CodeLabelValue("02", "Germany"));
nationalityCodeList.add(new CodeLabelValue("03", "Australia"));
model.addAttribute("nationalityCodeList", nationalityCodeList);
model.addAttribute("member", new Member());
return "registerForm02";
}
@RequestMapping(value = "/registerForm03", method = RequestMethod.GET)
public String registerForm03(Model model) {
logger.info("registerForm01");
Map<String, String> carCodeMap = new HashMap<String, String>();
carCodeMap.put("01", "Volvo");
carCodeMap.put("02", "Saab");
carCodeMap.put("03", "Opel");
model.addAttribute("carCodeMap", carCodeMap);
model.addAttribute("member", new Member());
return "registerForm03";
}
@RequestMapping(value = "/registerForm04", method = RequestMethod.GET)
public String registerForm04(Model model) {
logger.info("registerForm04");
List<CodeLabelValue> carCodeList = new ArrayList<CodeLabelValue>();
carCodeList.add(new CodeLabelValue("01", "Volvo"));
carCodeList.add(new CodeLabelValue("02", "Saab"));
carCodeList.add(new CodeLabelValue("03", "Opel"));
model.addAttribute("carCodeList", carCodeList);
model.addAttribute("member", new Member());
return "registerForm04";
}
@RequestMapping(value = "/registerForm05", method = RequestMethod.GET)
public String registerForm05(Model model) {
logger.info("registerForm05");
List<CodeLabelValue> carCodeList = new ArrayList<CodeLabelValue>();
carCodeList.add(new CodeLabelValue("01", "Volvo"));
carCodeList.add(new CodeLabelValue("02", "Saab"));
carCodeList.add(new CodeLabelValue("03", "Opel"));
model.addAttribute("carCodeList", carCodeList);
model.addAttribute("member", new Member());
return "registerForm05";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member, Model model) {
logger.info("register");
logger.info("member.getNationality() = " + member.getNationality());
model.addAttribute("nationality", member.getNationality());
return "result";
}
*/
//숨겨진 필드 요소
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm(Model model) {
logger.info("registerForm");
Member member = new Member();
member.setUserId("hongkd");
member.setUserName("홍길동");
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getUserName() = " + member.getUserName());
return "result";
}
*/
//입력값 검증 에러
/*
@RequestMapping(value = "/registerForm", method = RequestMethod.GET)
public String registerForm(Model model) {
logger.info("registerForm");
Member member = new Member();
member.setEmail("<EMAIL>");
member.setUserName("홍길동");
model.addAttribute("member", member);
return "registerForm";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Member member) {
logger.info("register");
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getUserName() = " + member.getUserName());
logger.info("member.getEmail() = " + member.getEmail());
return "result";
}
*/
//9. 입력 유효성 검증
//입력값 검증
//입력값 검증 결과
/*
@RequestMapping(value = "/register", method = RequestMethod.POST)
//입력값 검증을 할 도메인 클래스에 @Validated를 지정한다.
public String register(@Validated Member member, BindingResult result) {
logger.info("register");
//입력값 검증 에러가 발생한 경우 true를 반환한다.
logger.info("result.hasErrors() = " + result.hasErrors());
//입력갑 검증 후 BindingResult가 제공하는 메서드를 이용하여 검사 결과를 확인
if(result.hasErrors()) {
List<ObjectError> allErrors = result.getAllErrors();
List<ObjectError> globalErrors = result.getGlobalErrors();
List<FieldError> fieldErrors = result.getFieldErrors();
logger.info("allError.size() = " + allErrors.size());
logger.info("allError.size() = " + globalErrors.size());
logger.info("allError.size() = " + fieldErrors.size());
for(int i = 0; i < allErrors.size(); i++) {
ObjectError objectError = allErrors.get(i);
logger.info("allError = " + objectError);
}
for(int i = 0; i < allErrors.size(); i++) {
ObjectError objectError = allErrors.get(i);
logger.info("allError = " + objectError);
}
for(int i = 0; i < globalErrors.size(); i++) {
ObjectError objectError = globalErrors.get(i);
logger.info("globalErrors = " + globalErrors);
}
for(int i = 0; i < fieldErrors.size(); i++) {
FieldError fieldError = fieldErrors.get(i);
logger.info("fieldErrors = " + fieldErrors);
logger.info("fieldError.getDefaultMessage() = " + fieldError.getDefaultMessage());
}
return "registerForm";
}
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getGender() = #" + member.getGender() + "#");
return "success";
}
*/
//입력값 검증 규픽
/*
@RequestMapping(value = "/register", method = RequestMethod.POST)
//입력값 검증을 할 도메인 클래스에 @Validated를 지정한다.
public String register(@Validated Member member, BindingResult result) {
logger.info("register");
//입력값 검증 에러가 발생한 경우 true를 반환한다.
logger.info("result.hasErrors() = " + result.hasErrors());
//입력갑 검증 후 BindingResult가 제공하는 메서드를 이용하여 검사 결과를 확인
if(result.hasErrors()) {
List<ObjectError> allErrors = result.getAllErrors();
List<ObjectError> globalErrors = result.getGlobalErrors();
List<FieldError> fieldErrors = result.getFieldErrors();
logger.info("allError.size() = " + allErrors.size());
logger.info("allError.size() = " + globalErrors.size());
logger.info("allError.size() = " + fieldErrors.size());
for(int i = 0; i < allErrors.size(); i++) {
ObjectError objectError = allErrors.get(i);
logger.info("allError = " + objectError);
}
for(int i = 0; i < allErrors.size(); i++) {
ObjectError objectError = allErrors.get(i);
logger.info("allError = " + objectError);
}
for(int i = 0; i < globalErrors.size(); i++) {
ObjectError objectError = globalErrors.get(i);
logger.info("globalErrors = " + globalErrors);
}
for(int i = 0; i < fieldErrors.size(); i++) {
FieldError fieldError = fieldErrors.get(i);
logger.info("fieldErrors = " + fieldErrors);
logger.info("fieldError.getDefaultMessage() = " + fieldError.getDefaultMessage());
}
return "registerForm";
}
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getGender() = #" + member.getGender() + "#");
return "success";
}
@RequestMapping(value = "registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
Member member = new Member();
member.setPassword("<PASSWORD>");
member.setEmail("<EMAIL>");
member.setUserName("홍길동");
member.setGender("female");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DAY_OF_MONTH, 7);
member.setDateOfBirth(cal.getTime());
model.addAttribute("member", member);
return "registerForm";
}
*/
//중첩된 자바빈즈 입력값 검증
/*
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Validated Member member, BindingResult result) {
logger.info("register");
if(result.hasErrors()) {
return "registerForm";
}
logger.info("member.getUserId() = " + member.getUserId());
logger.info("member.getDateOfBirth() = " + member.getDateOfBirth());
Address address = member.getAddress();
if(address != null) {
logger.info("address != null address.getPostCode() = " + address.getPostCode());
logger.info("address != null address.getLocation() = " + address.getLocation());
}
else {
logger.info("address == null");
}
List<Card> cardList = member.getCardList();
if(cardList != null) {
logger.info("cardList != null = " + cardList.size());
for(int i = 0; i <cardList.size(); i++) {
Card card = cardList.get(i);
logger.info("card.getNo() = " + card.getNo());
logger.info("card.getValidMonth() = " + card.getValidMonth());
}
}
return "success";
}
@RequestMapping(value = "registerForm01", method = RequestMethod.GET)
public String registerForm01(Model model) {
logger.info("registerForm01");
model.addAttribute("member", new Member());
return "registerForm";
}
@RequestMapping(value = "/registerForm02", method = RequestMethod.GET)
public String registerForm02(Model model) {
logger.info("registerForm02");
Member member = new Member();
member.setPassword("<PASSWORD>");
member.setEmail("<EMAIL>");
member.setUserName("홍길동");
Address address = new Address();
address.setPostCode("080908");
address.setLocation("seoul");
member.setAddress(address);
List<Card> cardList = new ArrayList<Card>();
Card card1 = new Card();
card1.setNo("123456");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2020);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DAY_OF_MONTH, 8);
card1.setValidMonth(cal.getTime());
cardList.add(card1);
Card card2 = new Card();
card2.setNo("456789");
cal.set(Calendar.YEAR, 2022);
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DAY_OF_MONTH, 7);
card2.setValidMonth(cal.getTime());
cardList.add(card2);
member.setCardList(cardList);
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DAY_OF_MONTH, 7);
member.setDateOfBirth(cal.getTime());
model.addAttribute("member", member);
return "registerForm";
}
*/
//12. Mybatis
//기본키 취득
@Autowired
private MemberService service;
@RequestMapping(value = "/register", method = RequestMethod.GET)
public void registerForm(Member member, Model model) throws Exception {
logger.info("registerForm");
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Member member, Model model) throws Exception {
logger.info("register");
service.register(member);
model.addAttribute("msg", "등록이 완료되었습니다.");
return "user/success";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public void list(Model model) throws Exception {
logger.info("list");
model.addAttribute("list", service.list());
}
@RequestMapping(value = "read", method = RequestMethod.GET)
public void read(int userNo, Model model) throws Exception{
logger.info("read");
model.addAttribute(service.read(userNo));
}
@RequestMapping(value = "remove", method = RequestMethod.POST)
public String remove(int userNo, Model model) throws Exception {
logger.info("remove");
service.remove(userNo);
model.addAttribute("msg", "삭제가 완료되었습니다.");
return "user/success";
}
@RequestMapping(value = "/modify", method = RequestMethod.GET)
public void modifyForm(int userNo, Model model) throws Exception {
logger.info("modifyForm");
model.addAttribute(service.read(userNo));
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modify(Member member, Model model) throws Exception {
logger.info("modify");
service.modify(member);
model.addAttribute("msg", "수정이 완료되었습니다.");
return "user/success";
}
}
<file_sep>/Project/src/main/java/org/hdcd/controller/ProvinceClassController.java
package org.hdcd.controller;
import org.hdcd.domain.ProvinceClass;
import org.hdcd.service.ProvinceClassService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/province")
public class ProvinceClassController {
private static final Logger logger = LoggerFactory.getLogger(ProvinceClassController.class);
@Autowired
private ProvinceClassService service;
@RequestMapping(value = "/register", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void registerForm(Model model) throws Exception {
logger.info("ProvinceClass RegisterForm");
ProvinceClass provinceClass = new ProvinceClass();
model.addAttribute(provinceClass);
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String register(ProvinceClass provinceClass, RedirectAttributes rttr) throws Exception {
logger.info("ProvinceClass Register");
service.register(provinceClass);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/province/list";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void list(Model model) throws Exception {
logger.info("ProvinceClass List");
model.addAttribute("list", service.list());
}
@RequestMapping(value = "/read", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void read(int provinceNo, Model model) throws Exception {
logger.info("ProvinceClass Read");
ProvinceClass provinceClass = service.read(provinceNo);
model.addAttribute(provinceClass);
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String remove(int provinceNo, RedirectAttributes rttr) throws Exception {
logger.info("ProvinceClass Remove");
service.remove(provinceNo);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/province/list";
}
@RequestMapping(value = "/modify", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void modifyForm(int provinceNo, Model model) throws Exception {
logger.info("ProvinceClass ModifyForm");
ProvinceClass provinceClass = service.read(provinceNo);
model.addAttribute(provinceClass);
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String modify(ProvinceClass provinceClass, RedirectAttributes rttr) throws Exception {
logger.info("ProvinceClass Modify");
service.modify(provinceClass);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/province/list";
}
}
<file_sep>/DevProject/src/main/java/org/hdcd/domain/Member.java
package org.hdcd.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
public class Member implements Serializable {
/*
//private String userName = "hongkd";
private String userId = "hongkd";
private String password = "<PASSWORD>";
private int coin = 100;
//Date 타입 프로퍼티 변환 처리
@DateTimeFormat(pattern="yyyyMMdd")
private Date dateOfBirth;
*/
/*
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
*/
/*
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCoin() {
return coin;
}
public void setCoin(int coin) {
this.coin = coin;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
*/
//폼 방식 요청 처리
private static final long serialVersionUID = 338471121541985467L;
/*
private String userId;
private String password;
private String userName;
private String email;
private String gender;
private String hobby;
private String[] hobbyArray;
private List<String> hobbyList;
private boolean foreigner;
private String developer;
private String nationality;
private Address address;
private List<Card> cardList;
private String cars;
private String[] carArray;
private List<String> carList;
private String introduction;
//Date 타입 프로퍼티 변환 처리
@DateTimeFormat(pattern="yyyyMM")
private Date dateOfBirth;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String[] getHobbyArray() {
return hobbyArray;
}
public void setHobbyArray(String[] hobbyArray) {
this.hobbyArray = hobbyArray;
}
public List<String> getHobbyList() {
return hobbyList;
}
public void setHobbyList(List<String> hobbyList) {
this.hobbyList = hobbyList;
}
public boolean getForeigner() {
return foreigner;
}
public void setForeigner(boolean foreigner) {
this.foreigner = foreigner;
}
public String getDeveloper() {
return developer;
}
public void setDeveloper(String developer) {
this.developer = developer;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Card> getCardList() {
return cardList;
}
public void setCardList(List<Card> cardList) {
this.cardList = cardList;
}
public String getCars() {
return cars;
}
public void setCars(String cars) {
this.cars = cars;
}
public String[] getCarArray() {
return carArray;
}
public void setCarArray(String[] carArray) {
this.carArray = carArray;
}
public List<String> getCarList() {
return carList;
}
public void setCarList(List<String> carList) {
this.carList = carList;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
*/
//파일업로드 폼 방식 요청 처리
/*
private String userId;
private String password;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
*/
//Ajax 방식 요청 처리
/*
private String userId = "hongkd";
private String password = "<PASSWORD>";
private Address address;
private List<Card> cardList;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Card> getCardList() {
return cardList;
}
public void setCardList(List<Card> cardList) {
this.cardList = cardList;
}
*/
//6. 데이터 전달자 모델
//모델을 통한 데이터 전달
//@ModelAttribute 애너테이션
//RedirectAttributes 타입
/*
private String userId;
private String password;
private String userName;
private String email;
private String birthDay;
private String gender;
private String hobby;
private String[] hobbyArray;
private List<String> hobbyList;
private boolean foreigner;
private String developer;
private String nationality;
private Address address;
private List<Card> cardList;
private String cars;
private String[] carArray;
private List<String> carList;
private String introduction;
//Date 타입 프로퍼티 변환 처리
@DateTimeFormat(pattern="yyyyMM")
private Date dateOfBirth;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthDay() {
return birthDay;
}
public void setBirthDay(String birthDay) {
this.birthDay = birthDay;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String[] getHobbyArray() {
return hobbyArray;
}
public void setHobbyArray(String[] hobbyArray) {
this.hobbyArray = hobbyArray;
}
public List<String> getHobbyList() {
return hobbyList;
}
public void setHobbyList(List<String> hobbyList) {
this.hobbyList = hobbyList;
}
public boolean isForeigner() {
return foreigner;
}
public void setForeigner(boolean foreigner) {
this.foreigner = foreigner;
}
public String getDeveloper() {
return developer;
}
public void setDeveloper(String developer) {
this.developer = developer;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Card> getCardList() {
return cardList;
}
public void setCardList(List<Card> cardList) {
this.cardList = cardList;
}
public String getCars() {
return cars;
}
public void setCars(String cars) {
this.cars = cars;
}
public String[] getCarArray() {
return carArray;
}
public void setCarArray(String[] carArray) {
this.carArray = carArray;
}
public List<String> getCarList() {
return carList;
}
public void setCarList(List<String> carList) {
this.carList = carList;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
*/
//9. 입력 유효성 검증
//입력값 검증
//입력값 검증 결과
/*
//입력값 검증 규칙을 지정한다.
@NotBlank
private String userId;
private String password;
//여러 개의 입력값 검증 규칙을 지정할 수 있다.
@NotBlank
@Size(max = 3)
private String userName;
private String email;
private String birthDay;
private String gender;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthDay() {
return birthDay;
}
public void setBirthDay(String birthDay) {
this.birthDay = birthDay;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
*/
//입력값 검증 규픽
/*
//문자열이 null이 아니고 trim한 길이가 0보다 크다는 것을 검사함다.
@NotBlank
private String userId;
//문자열이 null이 아니고 trim한 길이가 0보다 크다는 것을 검사함다.
@NotBlank
private String password;
//문자열이 null이 아니고 trim한 길이가 3보다 작은 것을 검사함다.
@NotBlank
@Size(max = 3)
private String userName;
//이메일 주소 형식인지를 검사한다.
@Email
private String email;
private String gender;
//과거 날짜인지를 검사한다.
@Past
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateOfBirth;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
*/
//중첩된 자바빈즈 입력값 검증
/*
private String userId;
private String password;
@NotBlank
@Size(max = 3)
private String userName;
private String email;
//중첩된 자바빈즈의 입력값 검증을 지정한다.
@Valid
private Address address;
//자바빈즈 컬렉션의 입력값 검증을 지정한다.
@Valid
private List<Card> cardList;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateOfBirth;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Card> getCardList() {
return cardList;
}
public void setCardList(List<Card> cardList) {
this.cardList = cardList;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
*/
//12. Mybatis
//기본키 취득
private int userNo;
private String userId;
private String userPw;
private String email;
private String userName;
private Date regDate;
private Date updDate;
private List<MemberAuth> authList;
public int getUserNo() {
return userNo;
}
public void setUserNo(int userNo) {
this.userNo = userNo;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserPw() {
return userPw;
}
public void setUserPw(String userPw) {
this.userPw = userPw;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getRegDate() {
return regDate;
}
public void setRegDate(Date regDate) {
this.regDate = regDate;
}
public Date getUpdDate() {
return updDate;
}
public void setUpdDate(Date updDate) {
this.updDate = updDate;
}
public List<MemberAuth> getAuthList() {
return authList;
}
public void setAuthList(List<MemberAuth> authList) {
this.authList = authList;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
<file_sep>/Project/src/main/java/org/hdcd/mapper/ReservationMapper.java
package org.hdcd.mapper;
import java.util.List;
import org.hdcd.domain.Reservation;
import org.hdcd.domain.Seat;
public interface ReservationMapper {
public void create(Reservation reservation) throws Exception;
public Reservation read(Integer movieReserveNo) throws Exception;
public List<Reservation> listAll() throws Exception;
public List<Reservation> list(String userId) throws Exception;
public List<Seat> getSeatList(String showTime, String showDate, String city, String title) throws Exception;
public List<Reservation> getSeat(String showTime, String showDate, String city, String title) throws Exception;
}
<file_sep>/Project/src/main/java/org/hdcd/controller/ProvinceDetailController.java
package org.hdcd.controller;
import java.util.List;
import org.hdcd.common.domain.CodeLabelValue;
import org.hdcd.domain.ProvinceDetail;
import org.hdcd.service.ProvinceDetailService;
import org.hdcd.service.ProvinceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/city")
public class ProvinceDetailController {
private static final Logger logger = LoggerFactory.getLogger(ProvinceDetailController.class);
@Autowired
private ProvinceDetailService service;
@Autowired
private ProvinceService provinceService;
@RequestMapping(value = "/register", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void registerForm(Model model) throws Exception {
logger.info("ProvinceDetail RegisterForm");
ProvinceDetail provinceDetail = new ProvinceDetail();
model.addAttribute(provinceDetail);
List<CodeLabelValue> provinceNameList = provinceService.getProvinceClassList();
model.addAttribute("provinceNameList", provinceNameList);
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String register(ProvinceDetail provinceDetail, RedirectAttributes rttr) throws Exception {
logger.info("ProvinceDetail Register");
service.register(provinceDetail);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/city/list";
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public void list(Model model) throws Exception {
logger.info("ProvinceDetail List");
model.addAttribute("list", service.list());
}
@RequestMapping(value = "/read", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void read(int cityNo, Model model) throws Exception {
logger.info("ProvinceDetail Read");
ProvinceDetail provinceDetail = service.read(cityNo);
model.addAttribute(provinceDetail);
List<CodeLabelValue> provinceNameList = provinceService.getProvinceClassList();
model.addAttribute("provinceNameList", provinceNameList);
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String remove(int cityNo, RedirectAttributes rttr) throws Exception {
logger.info("ProvinceDetail Remove");
service.remove(cityNo);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/city/list";
}
@RequestMapping(value = "/modify", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void modifyForm(int cityNo, Model model) throws Exception {
logger.info("ProvinceDetail ModifyForm");
ProvinceDetail provinceDetail = service.read(cityNo);
model.addAttribute(provinceDetail);
List<CodeLabelValue> provinceNameList = provinceService.getProvinceClassList();
model.addAttribute("provinceNameList", provinceNameList);
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String modify(ProvinceDetail provinceDetail, RedirectAttributes rttr) throws Exception {
logger.info("ProvinceDetail Modify");
service.modify(provinceDetail);
rttr.addFlashAttribute("msg", "SUCCESS");
return "redirect:/city/list";
}
}
<file_sep>/DevProject/src/main/resources/message.properties
<!-- welcome.message = {0}\uB2D8, \uD658\uC601\uD569\uB2C8\uB2E4.! -->
welcome.message = hello, {0}
<file_sep>/Project/src/main/java/org/hdcd/service/ProvinceDetailServiceImpl.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.ProvinceDetail;
import org.hdcd.mapper.ProvinceDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProvinceDetailServiceImpl implements ProvinceDetailService {
@Autowired
private ProvinceDetailMapper mapper;
@Override
public void register(ProvinceDetail provinceDetail) throws Exception {
mapper.create(provinceDetail);
}
@Override
public ProvinceDetail read(Integer cityNo) throws Exception {
return mapper.read(cityNo);
}
@Override
public void modify(ProvinceDetail provinceClass) throws Exception {
mapper.update(provinceClass);
}
@Override
public void remove(Integer cityNo) throws Exception {
mapper.delete(cityNo);
}
@Override
public List<ProvinceDetail> list() throws Exception {
return mapper.list();
}
}
<file_sep>/Project/src/main/java/org/hdcd/service/ProvinceClassServiceImpl.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.ProvinceClass;
import org.hdcd.mapper.ProvinceClassMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProvinceClassServiceImpl implements ProvinceClassService {
@Autowired
private ProvinceClassMapper mapper;
@Override
public void register(ProvinceClass provinceClass) throws Exception {
mapper.create(provinceClass);
}
@Override
public ProvinceClass read(Integer provinceNo) throws Exception {
return mapper.read(provinceNo);
}
@Override
public void modify(ProvinceClass provinceClass) throws Exception {
mapper.update(provinceClass);
}
@Override
public void remove(Integer provinceNo) throws Exception {
mapper.delete(provinceNo);
}
@Override
public List<ProvinceClass> list() throws Exception {
return mapper.list();
}
}
<file_sep>/Project/src/main/java/org/hdcd/domain/Reservation.java
package org.hdcd.domain;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
import org.springframework.format.annotation.DateTimeFormat;
public class Reservation implements Serializable {
private static final long serialVersionUID = -2351700127905787118L;
private int movieReserveNo; /*예약 번호*/
private String userId;
private String title; /*영화 제목*/
private String provinceName; /*도시 이름*/
private String city; /*영화관*/
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate showDate;
@DateTimeFormat(pattern = "HH:mm:ss")
private LocalTime showTime;
private String screenName; /*영화 상영관 이름*/
private int seatNo;
private String seatId; /*좌석 이름*/
private int price;
public int getMovieReserveNo() {
return movieReserveNo;
}
public void setMovieReserveNo(int movieReserveNo) {
this.movieReserveNo = movieReserveNo;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public LocalDate getShowDate() {
return showDate;
}
public void setShowDate(LocalDate showDate) {
this.showDate = showDate;
}
public LocalTime getShowTime() {
return showTime;
}
public void setShowTime(LocalTime showTime) {
this.showTime = showTime;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public String getSeatId() {
return seatId;
}
public void setSeatId(String seatId) {
this.seatId = seatId;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
<file_sep>/Project/src/main/java/org/hdcd/mapper/ScreenMapper.java
package org.hdcd.mapper;
import java.util.List;
import org.hdcd.domain.Screen;
import org.hdcd.domain.Seat;
public interface ScreenMapper {
public void create(Screen screen) throws Exception;
public void createSeat(Seat seat) throws Exception;
public Screen read(String city, String screenName) throws Exception;
public void update(Screen screen) throws Exception;
public void delete(String city, String screenName) throws Exception;
public List<Screen> list() throws Exception;
}
<file_sep>/Project/src/main/java/org/hdcd/domain/ProvinceClass.java
package org.hdcd.domain;
import java.io.Serializable;
public class ProvinceClass implements Serializable {
private static final long serialVersionUID = 4943281794819208944L;
private int provinceNo;
private String provinceName;
public int getProvinceNo() {
return provinceNo;
}
public void setProvinceNo(int provinceNo) {
this.provinceNo = provinceNo;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
}
<file_sep>/Project/src/main/java/org/hdcd/domain/Theater.java
package org.hdcd.domain;
import java.io.Serializable;
public class Theater implements Serializable {
private static final long serialVersionUID = 1713906936947141859L;
private String province;
private String city;
private int theaterNo;
private String theater;
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getTheaterNo() {
return theaterNo;
}
public void setTheaterNo(int theaterNo) {
this.theaterNo = theaterNo;
}
public String getTheater() {
return theater;
}
public void setTheater(String theater) {
this.theater = theater;
}
}
<file_sep>/Project/src/main/java/org/hdcd/domain/Banner.java
package org.hdcd.domain;
import java.io.Serializable;
import org.springframework.web.multipart.MultipartFile;
public class Banner implements Serializable {
private static final long serialVersionUID = -658212877339310217L;
private int bannerNo;
private int movieNo;
private String bannerName;
private MultipartFile bannerPicture;
private String bannerPictureUrl;
public int getBannerNo() {
return bannerNo;
}
public void setBannerNo(int bannerNo) {
this.bannerNo = bannerNo;
}
public int getMovieNo() {
return movieNo;
}
public void setMovieNo(int movieNo) {
this.movieNo = movieNo;
}
public String getBannerName() {
return bannerName;
}
public void setBannerName(String bannerName) {
this.bannerName = bannerName;
}
public MultipartFile getBannerPicture() {
return bannerPicture;
}
public void setBannerPicture(MultipartFile bannerPicture) {
this.bannerPicture = bannerPicture;
}
public String getBannerPictureUrl() {
return bannerPictureUrl;
}
public void setBannerPictureUrl(String bannerPictureUrl) {
this.bannerPictureUrl = bannerPictureUrl;
}
}
<file_sep>/movie.sql
/*회원 테이블과 권한 테이블*/
CREATE TABLE member (
user_id VARCHAR(50) NOT NULL, /*아이디*/
user_pw VARCHAR(100) NOT NULL, /*비밀번호*/
user_name VARCHAR(10) NOT NULL DEFAULT '00', /*닉네임*/
point INT(10) DEFAULT 0, /*예약 페이지 화폐*/
email VARCHAR(50) NOT NULL, /*이메일 주소*/
phone VARCHAR(50) NOT NULL, /*휴대폰 번호*/
reg_Date TIMESTAMP DEFAULT now(), /*등록 일자*/
upd_date TIMESTAMP DEFAULT now(), /*수정 일자*/
enabled CHAR(1) DEFAULT '1', /*enabled : 계정의 활성화, 비활성화의 여부를 알려준다. */
PRIMARY KEY (user_id)
);
CREATE TABLE member_auth (
user_id VARCHAR(50) NOT NULL, /*아이디*/
auth VARCHAR(50) NOT NULL /*권한*/
);
ALTER TABLE member_auth ADD CONSTRAINT fk_member_auth_user_id FOREIGN KEY (user_id) REFERENCES member(user_id) ON DELETE CASCADE;
/*로그인 상태 유지 테이블*/
CREATE TABLE persistent_logins (
username VARCHAR(64) NOT NULL, /*아이디*/
series VARCHAR(64) NOT NULL, /*시리즈*/
token VARCHAR(64) NOT NULL, /*토큰*/
last_used TIMESTAMP NOT NULL, /*마지막 사용*/
PRIMARY KEY (series)
);
/*회원 게시판 테이블*/
CREATE TABLE board (
board_no INT NOT NULL AUTO_INCREMENT, /*게시판 번호*/
title VARCHAR(200) NOT NULL, /*게시판 제목*/
content TEXT, /*게시판 내용*/
writer VARCHAR(50) NOT NULL, /*게시판 작성자*/
reg_date TIMESTAMP NOT NULL DEFAULT now(), /*등록일자*/
PRIMARY KEY (board_no)
);
/*댓글 테이블*/
CREATE TABLE reply (
reply_no INT(5) NOT NULL AUTO_INCREMENT, /*댓글 번호*/
board_no INT NOT NULL, /*게시판 번호*/
reply_content VARCHAR(150) NOT NULL, /*댓글 내용*/
reply_writer VARCHAR(50) NOT NULL, /*댓글 작성자*/
reg_date TIMESTAMP DEFAULT now(), /*등록일자*/
PRIMARY KEY (reply_no, board_no)
);
ALTER TABLE reply ADD CONSTRAINT fk_reply_board_no FOREIGN KEY (board_no) REFERENCES board(board_no) ON DELETE CASCADE;
/*공지사항 테이블*/
CREATE TABLE notice (
notice_no INT NOT NULL AUTO_INCREMENT, /*공지사항 번호*/
title VARCHAR(200) NOT NULL, /*공지사항 제목*/
content TEXT, /*공지사항 내용*/
reg_date TIMESTAMP NOT NULL DEFAULT now(), /*등록 일자*/
PRIMARY KEY (notice_no)
);
/*1:1문의 테이블*/
CREATE TABLE inquiry (
inquiry_no INT NOT NULL AUTO_INCREMENT, /*1:1문의 번호*/
origin_no INT(10), /*문의하는 번호*/
group_ord INT(10) DEFAULT 0, /*순서 번호*/
group_layer INT(10) DEFAULT 0, /*깊이*/
title VARCHAR(200) NOT NULL, /*문의 제목*/
content TEXT, /*문의 내용*/
writer VARCHAR(50) NOT NULL, /*문의 작성자*/
reg_date TIMESTAMP NOT NULL DEFAULT now(), /*문의 등록일자*/
PRIMARY KEY (inquiry_no)
);
/*충전 내역 테이블*/
CREATE TABLE charge_point_history (
history_no INT AUTO_INCREMENT, /*충전 내역 번호*/
user_id VARCHAR(50) NOT NULL, /*아이디*/
amount INT(5) NOT NULL, /*금액*/
reg_date TIMESTAMP DEFAULT now(), /*충전 일자*/
PRIMARY KEY (history_no)
);
/*홍보 배너 테이블*/
CREATE TABLE banner (
banner_no INT(5) AUTO_INCREMENT, /*배너 번호*/
movie_no INT(5) NOT NULL, /*영화 번호*/
banner_name VARCHAR(30) NOT NULL, /*배너 이름*/
banner_picture_url varchar(200), /*배너 사진*/
PRIMARY KEY (banner_no)
);
ALTER TABLE banner ADD CONSTRAINT fk_banner_movie_no FOREIGN KEY (movie_no) REFERENCES movie(movie_no) ON DELETE CASCADE;
/*영화 테이블*/
CREATE TABLE movie (
movie_no INT NOT NULL AUTO_INCREMENT, /*영화 번호*/
title VARCHAR(100) NOT NULL, /*영화 제목*/
genre VARCHAR(50) NOT NULL, /*영화 장르*/
nation VARCHAR(50) NOT NULL, /*영화 국가*/
running_time INT(5) NOT NULL, /*영화 상영 시간*/
openning_days DATE, /*영화 개봉일*/
director VARCHAR(50) NOT NULL, /*영화 감독*/
actors VARCHAR(200) NOT NULL, /*영화 출연 배우*/
ratings VARCHAR(5), /*영화 심의 등급*/
scores FLOAT, /*영화 평점*/
summary TEXT, /*영화 소개*/
poster_url VARCHAR(200), /*영화 포스터*/
still1_url VARCHAR(200), /*영화 스틸컷1*/
still2_url VARCHAR(200), /*영화 스틸컷2*/
still3_url VARCHAR(200), /*영화 스틸컷3*/
still4_url VARCHAR(200), /*영화 스틸컷4*/
reg_date TIMESTAMP DEFAULT now(), /*등록 일자*/
enabled CHAR(1) DEFAULT '1', /*영화 상영 상태*/
PRIMARY KEY (movie_no)
);
/*영화 후기 테이블*/
CREATE TABLE review (
review_no INT(5) NOT NULL AUTO_INCREMENT, /*후기 번호*/
movie_no INT(5) NOT NULL, /*영화 번호*/
scores FLOAT, /*후기 점수*/
review_content VARCHAR(150) NOT NULL, /*후기 내용*/
review_writer VARCHAR(50) NOT NULL, /*후기 작성자*/
reg_date TIMESTAMP DEFAULT now(), /*등록 일자*/
PRIMARY KEY (review_no, movie_no)
);
ALTER TABLE review ADD CONSTRAINT fk_review_movie_no FOREIGN KEY (movie_no) REFERENCES movie(movie_no) ON DELETE CASCADE;
/*도시 그룹 테이블*/
CREATE TABLE province_class (
province_no INT NOT NULL AUTO_INCREMENT, /*도시 번호*/
province_name VARCHAR(20) NOT NULL, /*도시 이름*/
PRIMARY KEY (province_no)
);
/*도시 상세 테이블*/
CREATE TABLE province_detail (
province_name VARCHAR(20) NOT NULL, /*도시 이름*/
city_no INT NOT NULL AUTO_INCREMENT, /*영화관 번호*/
city VARCHAR(20) NOT NULL, /*영화관*/
PRIMARY KEY (city_no)
);
/*영화 상영관 테이블*/
CREATE TABLE movie_screen (
province_name VARCHAR(20) NOT NULL, /*도시 이름*/
city VARCHAR(20) NOT NULL, /*영화관*/
screen_name VARCHAR(5) NOT NULL, /*영화 상영관 이름*/
screen_col INT(3) NOT NULL, /*영화 상영관 행*/
screen_row INT(3) NOT NULL, /*영화 상영관 열*/
PRIMARY KEY (city, screen_name)
);
/*영화 좌석 테이블*/
CREATE TABLE movie_seat (
city VARCHAR(20) NOT NULL, /*영화관*/
screen_name VARCHAR(5) NOT NULL, /*영화 상영관 이름*/
seat_no INT NOT NULL AUTO_INCREMENT, /*좌석 번호*/
seat_id VARCHAR(10), /*영화 좌석 이름*/
price INT(6) DEFAULT 10000, /*영화 가격*/
PRIMARY KEY (seat_no)
);
CREATE TABLE movie_time (
time_no INT NOT NULL AUTO_INCREMENT,
province_name VARCHAR(20) NOT NULL, /*도시 이름*/
city VARCHAR(20) NOT NULL, /*영화관*/
screen_name VARCHAR(5) NOT NULL, /*영화 상영관 이름*/
title VARCHAR(100) NOT NULL, /*영화 제목*/
show_date DATE NOT NULL, /*상영일*/
show_time TIME NOT NULL, /*상영 시간*/
PRIMARY KEY (time_no, city, screen_name, show_date, show_time)
);
/*영화 예약 테이블*/
CREATE TABLE movie_reservation (
movie_reserve_no INT NOT NULL AUTO_INCREMENT, /*예약 번호*/
user_id VARCHAR(50) NOT NULL, /*회원 아이디*/
title VARCHAR(100) NOT NULL, /*영화 제목*/
province_name VARCHAR(20) NOT NULL, /*도시 이름*/
city VARCHAR(20) NOT NULL, /*영화관*/
show_date DATE NOT NULL, /*상영일*/
show_time TIME NOT NULL, /*상영 시간*/
screen_name VARCHAR(5) NOT NULL, /*영화 상영관 이름*/
seat_no INT(6), /*좌석 번호*/
seat_id VARCHAR(10), /*좌석 번호*/
price INT(6), /*가격*/
enable CHAR(1) DEFAULT '0', /*좌석 활성화*/
PRIMARY KEY (movie_reserve_no)
);
/*구매 내역 테이블*/
CREATE TABLE pay_point_history (
history_no INT AUTO_INCREMENT, /*구매 번호*/
user_id VARCHAR(50) NOT NULL, /*아이디*/
amount INT(5) NOT NULL, /*금액*/
reg_date TIMESTAMP DEFAULT now(), /*구매 일자*/
PRIMARY KEY (history_no)
);
<file_sep>/DevProject/src/main/resources/templates/home0301.html
<html xmlns:th="http://www.thymeleaf/org">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!-- 표현식 -->
<!--
<table border="1" th:object="${member}">
<tr>
<td>*{userId}</td>
<td th:text="*{userId}">userId</td>
</tr>
<tr>
<td>*{password}</td>
<td th:text="*{password}">password</td>
</tr>
<tr>
<td>*{userName}</td>
<td th:text="*{userName}">userName</td>
</tr>
<tr>
<td>*{email}</td>
<td th:text="*{email}">email</td>
</tr>
<tr>
<td>*{dateOfBirth}</td>
<td th:text="*{dateOfBirth}">dateOfBirth</td>
</tr>
</table>
-->
<!-- 속성 값 설정 -->
<!--
<h1>Home0301</h1>
<img src="../static/images/player.png" th:src="@{/images/player.png}" />
-->
<!-- 제어 속성 -->
<!--
<th:block th:each="hobby : ${member.hobbyArray}">
<p th:text="${hobby}">hobby</p>
</th:block>
-->
<!-- 인라인 -->
<!--
<p th:text="|Hello, ${username}!|">greeting</p>
<p>Hello, <span th:text="${username}">name</span>!</p>
<p>Hello, [[${username}]]!</p>
-->
<!-- 유틸리티 객체 -->
<table border="1">
<tr>
<td>${str}</td>
<td th:text=${str}"></td>
</tr>
<tr>
<td>${#strings.contains(str, 'Hello')}</td>
<td th:text="${#strings.contains(str, 'Hello')}"></td>
</tr>
<tr>
<td>${#strings.containsIgnoreCase(str, 'Hello')}</td>
<td th:text="${#strings.containsIgnoreCase(str, 'Hello')}"></td>
</tr>
<tr>
<td>${#strings.startsWith(str, 'Hello')}</td>
<td th:text="${#strings.startsWith(str, 'Hello')}"></td>
</tr>
<tr>
<td>${#strings.endsWith(str, 'World!')}</td>
<td th:text="${#strings.endsWith(str, 'World!')}"></td>
</tr>
<tr>
<td>${#strings.indexOf(str, 'World!')}</td>
<td th:text="${#strings.indexOf(str, 'World!')}"></td>
</tr>
<tr>
<td>${#strings.length(str)}</td>
<td th:text="${#strings.length(str)}"></td>
</tr>
<tr>
<td>${#strings.excapeXml(str)}</td>
<td th:text="${#strings.excapeXml(str)}"></td>
</tr>
<tr>
<td>${#strings.replace(str, 'Hello', 'Hi')}</td>
<td th:text="${#strings.replace(str, 'Hello', 'Hi)}"></td>
</tr>
<tr>
<td>${#strings.toLowerCase(str)}</td>
<td th:text="${#strings.toLowerCase(str)}"></td>
</tr>
<tr>
<td>${#strings.toUpperCase(str)}</td>
<td th:text="${#strings.toUpperCase(str)}"></td>
</tr>
<tr>
<td>${#strings.trim(str)}</td>
<td th:text="${#strings.trim(str)}"></td>
</tr>
<tr>
<td>${#strings.substring(str, 7, 12)}</td>
<td th:text="${#strings.substring(str, 7, 12)}"></td>
</tr>
<tr>
<td>${#strings.substringAfter(str, 'World!')}</td>
<td th:text="${#strings.substringAfter(str, 'World!')}"></td>
</tr>
<tr>
<td>${#strings.substringBefore(str, 'World!')}</td>
<td th:text="${#strings.substringBefore(str, 'World!')}"></td>
</tr>
<tr>
<td>tokenStr:${#strings.listSplit(str, '')}</td>
<td>
<ul>
<li th:each="tokenStr:${#strings.listSplit(str, '')}">[[${tokenStr]]</li>
</ul>
</td>
</tr>
<tr>
<td>tokenStr:${#strings.listSplit(str, ' ')}</td>
<td>
<ul>
<li th:each="tokenStr:${#strings.listSplit(str, ' ')}">[[${tokenStr]]</li>
</ul>
</td>
</tr>
<tr>
<td>
<div>
strArray:${#strings.listSplit(str, '')}
</div>
<div>
strArray:${#strings.arrayJoin(strArray, '-')}
</div>
</td>
<td>
<div th:with="strArray:${#strings.listSplit(str, '')}">
<p th:text="${#strings.arrayJoin(strArray, '-')}">
join : ${#strings.arrayJoin(strArray, '-')}
</p>
</div>
</td>
</tr>
</table>
</body>
</html><file_sep>/Project/src/main/java/org/hdcd/service/ProvinceClassService.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.domain.ProvinceClass;
public interface ProvinceClassService {
public void register(ProvinceClass provinceClass) throws Exception;
public ProvinceClass read(Integer provinceNo) throws Exception;
public void modify(ProvinceClass provinceClass) throws Exception;
public void remove(Integer provinceNo) throws Exception;
public List<ProvinceClass> list() throws Exception;
}
<file_sep>/Project/src/main/java/org/hdcd/mapper/InquiryMapper.java
package org.hdcd.mapper;
import java.util.List;
import org.hdcd.common.domain.PageRequest;
import org.hdcd.domain.Inquiry;
public interface InquiryMapper {
public void create(Inquiry inquiry) throws Exception;
public void admincreate(Inquiry inquiry) throws Exception;
public void updgroupOrd(Inquiry inquiry) throws Exception;
public Inquiry read(Integer inquiryNo) throws Exception;
public void update(Inquiry inquiry) throws Exception;
public void delete(Integer inquiryNo) throws Exception;
public List<Inquiry> list(PageRequest pageRequest) throws Exception;
public int count(PageRequest pageRequest) throws Exception;
}
<file_sep>/DevProject/src/main/java/org/hdcd/domain/MultiFileMember.java
package org.hdcd.domain;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class MultiFileMember {
private String userId;
private String password;
//MultipartFile 리스트 타입의 멤버변수를 선언한다.
private List<MultipartFile> pictureList;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<MultipartFile> getPictureList() {
return pictureList;
}
public void setPictureList(List<MultipartFile> pictureList) {
this.pictureList = pictureList;
}
}
<file_sep>/Project/src/main/java/org/hdcd/config/SecurityConfig.java
package org.hdcd.config;
import javax.sql.DataSource;
import org.hdcd.common.security.CustomAccessDeniedHandler;
import org.hdcd.common.security.CustomLoginSuccessHandler;
import org.hdcd.common.security.CustomUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled=true) //시큐리티 애너테이션 활성화
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
@Autowired
DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
logger.info("security config ...");
http.formLogin()
.loginPage("/auth/login")
.loginProcessingUrl("/login")
.successHandler(createAuthenticationSuccessHandler());
http.logout()
.logoutUrl("/auth/logout")
.invalidateHttpSession(true)
.deleteCookies("remember-me", "JSESSION_ID");
http.exceptionHandling()
.accessDeniedHandler(createAccessDeniedHandler());
http.rememberMe()
.key("hdcd")
.tokenRepository(createJDBCRepository())
.tokenValiditySeconds(60*60*24);
}
@Bean
public UserDetailsService createUserDetailsService() {
return new CustomUserDetailsService();
}
@Bean
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationSuccessHandler createAuthenticationSuccessHandler() {
return new CustomLoginSuccessHandler();
}
@Bean
public AccessDeniedHandler createAccessDeniedHandler() {
return new CustomAccessDeniedHandler();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(createUserDetailsService())
.passwordEncoder(createPasswordEncoder());
}
private PersistentTokenRepository createJDBCRepository() {
JdbcTokenRepositoryImpl repo = new JdbcTokenRepositoryImpl();
repo.setDataSource(dataSource);
return repo;
}
}
<file_sep>/Project/src/main/java/org/hdcd/service/ProvinceServiceImpl.java
package org.hdcd.service;
import java.util.List;
import org.hdcd.common.domain.CodeLabelValue;
import org.hdcd.mapper.ProvinceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProvinceServiceImpl implements ProvinceService {
@Autowired
private ProvinceMapper mapper;
@Override
public List<CodeLabelValue> getProvinceClassList() throws Exception {
return mapper.getProvinceClassList();
}
@Override
public List<CodeLabelValue> getProvinceList(String provinceName) throws Exception {
return mapper.getProvinceList(provinceName);
}
@Override
public List<CodeLabelValue> getcityList(String provinceName, String title) throws Exception {
return mapper.getcityList(provinceName, title);
}
@Override
public List<CodeLabelValue> getdayList(String city, String title) throws Exception {
return mapper.getdayList(city, title);
}
@Override
public List<CodeLabelValue> gettimeList(String showDate, String city, String title) throws Exception {
return mapper.gettimeList(showDate, city, title);
}
}
| 8999c7d90d1d5e13b4bfc6cb373ccbd74457e0d8 | [
"SQL",
"HTML",
"Markdown",
"INI",
"Java"
] | 42 | Java | ggxz88/Springboot | f8dc27e5ebddd8fd1a2c48c6c659423ad0e36692 | 3ae318f57c63999996bd950571f5c3ff10847475 |
refs/heads/master | <repo_name>deRvyn/Assignment4_DevynSmith_Section3<file_sep>/Controllers/HomeController.cs
using Assignment4_DevynSmith_Section3.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace Assignment4_DevynSmith_Section3.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
//Home page view
public IActionResult Index()
{
List<string> restaurantList = new List<string>();
foreach(Restaurant r in Restaurant.GetRestaurants())
{
if (r.FavoriteDish == null | r.FavoriteDish == "")
{
r.FavoriteDish = "It's all tasty!";
}
if (r.Link == null | r.Link == "")
{
r.Link = "Coming Soon";
}
restaurantList.Add($"<b>Rank {r.Rank}</b> <br> Restaurant: {r.RestaurantName} <br> Favorite Dish: {r.FavoriteDish} <br> Address: {r.Address} <br> Phone: {r.RestaurantPhone} <br> Website: <a href=\"{r.Link}\">{r.Link}</a> <br>");
}
return View(restaurantList);
}
//addsuggestion get view
[HttpGet]
public IActionResult AddSuggestion()
{
return View();
}
//addsuggestion post view
[HttpPost]
public IActionResult AddSuggestion(AddSuggestionResponse suggestionResponse)
{
if (ModelState.IsValid)
{
TempStorage.AddSuggestion(suggestionResponse);
return View("Confirmation", suggestionResponse);
}
else
{
return View();
}
}
//view restaurants view
public IActionResult RestaurantList()
{
foreach (AddSuggestionResponse s in TempStorage.Suggestions)
{
if (s.FavoriteDish == null | s.FavoriteDish == "")
{
s.FavoriteDish = "It's all tasty!";
}
}
return View(TempStorage.Suggestions);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/Models/Restaurant.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Assignment4_DevynSmith_Section3.Models
{
public class Restaurant
{
public Restaurant(int rank)
{
Rank = rank;
}
[Required]
public int Rank { get; }
[Required]
public string RestaurantName { get; set; }
public string? FavoriteDish { get; set; } = "It's all tasty!";
[Required]
public string Address { get; set; }
[RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Phone number entered incorrectly, please use this format: 000-000-0000")]
public string? RestaurantPhone { get; set; }
public string? Link { get; set; } = "Coming soon";
public static Restaurant[] GetRestaurants()
{
Restaurant r1 = new Restaurant(1)
{
RestaurantName = "<NAME>",
Address = "278 W Center St Provo, UT 84601",
RestaurantPhone = "(801)373-9540",
Link = "https://silverdishthaicuisine.com/"
};
Restaurant r2 = new Restaurant(2)
{
RestaurantName = "WINGERS",
FavoriteDish = "Sticky Fingers",
Address = "1200 Towne Centre Boulevard #1096 Provo, UT 84601",
RestaurantPhone = "(801) 812-2141",
Link = "https://wingerbros.com/locations/goto/wingers-grill-bar-provo"
};
Restaurant r3 = new Restaurant(3)
{
RestaurantName = "Chick-fil-A",
FavoriteDish = "Spicy Chicken Sandwich",
Address = "484 W Bulldog Blvd, Provo, UT 84604",
RestaurantPhone = "(801) 374-2697",
Link = "https://www.chick-fil-a.com/locations/ut/cougar-state"
};
Restaurant r4 = new Restaurant(4)
{
RestaurantName = "Panda Express",
FavoriteDish = "Honey Sesame Chicken",
Address = "1240 N University Ave Provo, UT 84604",
RestaurantPhone = "801-818-0111",
Link = "https://www.pandaexpress.com/userlocation/724/ut/provo/1240-n-university-ave"
};
Restaurant r5 = new Restaurant(5)
{
RestaurantName = "Cafe Rio",
FavoriteDish = "Sweet Pork Salad",
Address = "2244 N University Pkway Provo, UT 84604",
RestaurantPhone = "(801) 375-5133",
Link = "https://www.caferio.com/order/provo"
};
return new Restaurant[] { r1, r2, r3, r4, r5 };
}
}
}
<file_sep>/Models/AddSuggestion.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
//developing the model for the data, and requiring the data that is needed every time
namespace Assignment4_DevynSmith_Section3.Models
{
public class AddSuggestionResponse
{
[Required]
public string Name { get; set; }
[Required]
public string RestaurantName { get; set; }
public string? FavoriteDish { get; set; }
[RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Phone number entered incorrectly, please use this format: 000-000-0000")]
public string? Phone { get; set; }
}
}
<file_sep>/Models/TempStorage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Assignment4_DevynSmith_Section3.Models
{
public static class TempStorage
{
private static List<AddSuggestionResponse> suggestions = new List<AddSuggestionResponse>();
public static IEnumerable<AddSuggestionResponse> Suggestions => suggestions;
public static void AddSuggestion(AddSuggestionResponse suggestion)
{
suggestions.Add(suggestion);
}
}
}
| 130224e8f097ddfa0f22b583a158149ee02ca02c | [
"C#"
] | 4 | C# | deRvyn/Assignment4_DevynSmith_Section3 | c44ef1525dc1cc7b80914e2b5cc8b6552ae93aa1 | 45f90b3b940ceb90281d9711f7cd77ae7c463256 |
refs/heads/master | <file_sep>package com.qa.greenmarket.appHooks;
import com.qa.e.greenmarket.TestBase.TestBase;
import io.cucumber.java.After;
public class AppHooks extends TestBase {
@After("@Smoke")
public void afterEachTest()
{
System.out.println("Close driver");
driver.close();
}
}
<file_sep>package com.qa.greenmarket.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CartPage {
WebDriver driver;
public CartPage(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements(driver, this);
}
@FindBy(xpath="//button[contains(text(),'Place Order')]")
WebElement validateCartPage;
@FindBy(css="p.product-name")
WebElement getProductName;
public boolean validateCartPage()
{
System.out.println("Cart Page");
WebDriverWait wait=new WebDriverWait(driver,4000);
wait.until(ExpectedConditions.visibilityOf(validateCartPage));
boolean flag=false;
if(validateCartPage.isDisplayed())
{
System.out.println("Displayed");
flag=true;
}
return flag;
}
public String selectedItemValidation()
{
String checkoutPageText=getProductName.getText();
System.out.println(checkoutPageText);
return checkoutPageText;
}
}
<file_sep>package com.qa.greenmarker.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class TestData {
public static void getData(String testcase)
{
Workbook workbook;
Sheet sheet;
try {
FileInputStream fis=new FileInputStream("src/main/resources/TestData.xlsx");
workbook=WorkbookFactory.create(fis);
int sheets=workbook.getNumberOfSheets();
for(int i=0;i<sheets;i++)
{
String SheetName=workbook.getSheetName(i);
System.out.println(SheetName);
if(SheetName.equalsIgnoreCase("Sheet1"))
{
sheet=workbook.getSheetAt(i);
//Sheet is the collection of rows
}
}
} catch (IOException | EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String testCaseName="testcase";
getData(testCaseName);
}
}
| 29fadfe662dbdeaaa6586d54fa7dd636edafa78d | [
"Java"
] | 3 | Java | vasu446/CucumberTest1 | 07c0022be2ad080d3d1114cebcf06085bb77a7ee | 9e903346478622c203b30620654cae90b8a04734 |
refs/heads/master | <repo_name>Go-Shippit/Woo-Commerce<file_sep>/includes/class-shippit-data-mapper-order-v26.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Data_Mapper_Order_V26 extends Mamis_Shippit_Object
{
protected $helper;
protected $order;
public function __invoke($order)
{
$this->helper = new Mamis_Shippit_Helper();
$this->order = $order;
$this->mapRetailerReference()
->mapRetailerInvoice()
->mapUserAttributes()
->mapReceiverName()
->mapReceiverContactNumber()
->mapReceiverLanguageCode()
->mapCourierType()
->mapCourierAllocation()
->mapDeliveryDate()
->mapDeliveryWindow()
->mapDeliveryCompany()
->mapDeliveryAddress()
->mapDeliverySuburb()
->mapDeliveryState()
->mapDeliveryPostcode()
->mapDeliveryCountryCode()
->mapDeliveryInstructions()
->mapAuthorityToLeave()
->mapProductCurrency()
->mapParcelAttributes();
return $this;
}
public function mapRetailerReference()
{
$retailerReference = $this->order->id;
return $this->setRetailerReference($retailerReference);
}
public function mapRetailerInvoice()
{
$retailerInvoice = $this->order->get_order_number();
return $this->setRetailerInvoice($retailerInvoice);
}
public function mapReceiverName()
{
$receiverName = sprintf(
'%s %s',
$this->order->shipping_first_name,
$this->order->shipping_last_name
);
return $this->setReceiverName(trim($receiverName));
}
public function mapReceiverContactNumber()
{
$receiverContactNumber = $this->order->billing_phone;
return $this->setReceiverContactNumber($receiverContactNumber);
}
public function mapReceiverLanguageCode()
{
// WooCommerce does not provide order level
// language code, so we rely on store locale
$merchantLocale = get_locale();
if (empty($merchantLocale)) {
return $this;
}
$languageCode = explode('_', $merchantLocale);
return $this->setReceiverLanguageCode(reset($languageCode));
}
public function mapUserAttributes()
{
$userAttributes = array(
'email' => $this->order->billing_email,
'first_name' => $this->order->billing_first_name,
'last_name' => $this->order->billing_last_name,
);
return $this->setUserAttributes($userAttributes);
}
public function mapCourierType()
{
if ($this->helper->isShippitLiveQuote($this->order)) {
// If a shippit live quote is available, we'll set a courier allocation
// as such, return early
return $this;
}
$mappedShippingMethod = $this->helper->getMappedShippingMethod($this->order);
// Plain label services are assigned as a courier allocation
if ($mappedShippingMethod == 'plainlabel') {
return $this;
}
elseif ($mappedShippingMethod !== false) {
return $this->setCourierType($mappedShippingMethod);
}
return $this->setCourierType('standard');
}
public function mapCourierAllocation()
{
if ($this->helper->isShippitLiveQuote($this->order)) {
$courierAllocation = $this->helper->getShippitLiveQuoteDetail($this->order, 'courier_allocation');
return $this->setCourierAllocation($courierAllocation);
}
$mappedShippingMethod = $this->helper->getMappedShippingMethod($this->order);
if ($mappedShippingMethod == 'plainlabel') {
return $this->setCourierAllocation($mappedShippingMethod);
}
return $this;
}
public function mapDeliveryDate()
{
// Only provide a delivery date if the order has a shippit live quote
if (!$this->helper->isShippitLiveQuote($this->order)) {
return $this;
}
$deliveryDate = $this->helper->getShippitLiveQuoteDetail($this->order, 'delivery_date');
if (empty($deliveryDate)) {
return $this;
}
return $this->setDeliveryDate($deliveryDate);
}
public function mapDeliveryWindow()
{
// Only provide a delivery date if the order has a shippit live quote
if (!$this->helper->isShippitLiveQuote($this->order)) {
return $this;
}
$deliveryWindow = $this->helper->getShippitLiveQuoteDetail($this->order, 'delivery_window');
if (empty($deliveryWindow)) {
return $this;
}
return $this->setDeliveryWindow($deliveryWindow);
}
public function mapDeliveryCompany()
{
$deliveryCompany = $this->order->shipping_company;
return $this->setDeliveryCompany($deliveryCompany);
}
public function mapDeliveryAddress()
{
$deliveryAddress = sprintf(
'%s %s',
$this->order->shipping_address_1,
$this->order->shipping_address_2
);
return $this->setDeliveryAddress(trim($deliveryAddress));
}
public function mapDeliverySuburb()
{
$deliverySuburb = $this->order->shipping_city;
return $this->setDeliverySuburb($deliverySuburb);
}
public function mapDeliveryPostcode()
{
$deliveryPostcode = $this->order->shipping_postcode;
return $this->setDeliveryPostcode($deliveryPostcode);
}
public function mapDeliveryState()
{
$deliveryState = $this->order->shipping_state;
// If no state has been provided, use the suburb
if (empty($deliveryState)) {
$deliveryState = $this->order->shipping_state;
}
return $this->setDeliveryState($deliveryState);
}
public function mapDeliveryCountryCode()
{
$deliveryCountryCode = $this->order->shipping_country;
return $this->setDeliveryCountryCode(trim($deliveryCountryCode));
}
public function mapDeliveryInstructions()
{
$deliveryInstructions = $this->order->customer_message;
return $this->setDeliveryInstructions($deliveryInstructions);
}
public function mapAuthorityToLeave()
{
$authorityToLeaveData = get_post_meta($this->order->id, 'authority_to_leave', true);
if (in_array(strtolower($authorityToLeaveData), ['yes', 'y', 'true', 'atl'])) {
$this->setAuthorityToLeave('Yes');
}
elseif (in_array(strtolower($authorityToLeaveData), ['no', 'n', 'false'])) {
$this->setAuthorityToLeave('No');
}
return $this;
}
public function mapProductCurrency()
{
$orderCurrency = $this->order->get_order_currency();
if (empty($orderCurrency)) {
return $this;
}
return $this->setProductCurrency($orderCurrency);
}
public function mapParcelAttributes()
{
$itemsData = array();
$orderItems = $this->order->get_items();
// map to v2.6 order item data mapper
$orderItemDataMapper = new Mamis_Shippit_Data_Mapper_Order_Item_V26();
foreach ($orderItems as $orderItem) {
// If the order item does not have a linked product, skip it
if (empty($orderItem['product_id'])) {
continue;
}
$product = $this->order->get_product_from_item($orderItem);
// If the product is a virtual item, skip it
if ($product->is_virtual()) {
continue;
}
$itemsData[] = $orderItemDataMapper->__invoke(
$this->order,
$orderItem,
$product
)->toArray();
}
return $this->setParcelAttributes($itemsData);
}
protected function getLegacyShippingOptions($shippingMethodId)
{
if (stripos($shippingMethodId, 'priority') === FALSE) {
return;
}
return explode('_', $shippingMethodId);
}
}
<file_sep>/includes/class-shippit-data-mapper-order-item-v26.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Data_Mapper_Order_Item_V26 extends Mamis_Shippit_Object
{
const CUSTOM_OPTION_VALUE = '_custom';
protected $order;
protected $orderItem;
protected $product;
protected $helper;
public function __invoke($order, $orderItem, $product)
{
$this->order = $order;
$this->orderItem = $orderItem;
$this->product = $product;
$this->helper = new Mamis_Shippit_Helper();
$this->mapProductLineId()
->mapSku()
->mapTitle()
->mapQty()
->mapPrice()
->mapWeight()
->mapTariffCode()
->mapOriginCountryCode()
->mapDangerousGoodsCode()
->mapDangerousGoodsText();
if (!defined('SHIPPIT_IGNORE_ITEM_DIMENSIONS') || !SHIPPIT_IGNORE_ITEM_DIMENSIONS) {
$this->mapDepth()
->mapLength()
->mapWidth();
}
return $this;
}
public function mapProductLineId()
{
$productLineId = $this->product->get_id();
return $this->setProductLineId($productLineId);
}
public function mapSku()
{
if ($this->product->get_type() == 'variation') {
$sku = sprintf(
'%s|%s',
$this->product->get_sku(),
$this->product->get_variation_id()
);
}
else {
$sku = $this->product->get_sku();
}
return $this->setSku($sku);
}
public function mapTitle()
{
$title = $this->orderItem['name'];
return $this->setTitle($title);
}
public function mapQty()
{
$qty = $this->orderItem['qty'];
return $this->setQty($qty);
}
public function mapPrice()
{
$price = round(
(
($this->orderItem['line_total'] + $this->orderItem['line_total'])
/
$this->orderItem['qty']
),
2
);
return $this->setPrice($price);
}
public function mapWeight()
{
$itemWeight = $this->product->get_weight();
// Get the weight if available, otherwise stub weight to 0.2kg
$weight = (!empty($itemWeight) ? $this->helper->convertWeight($itemWeight) : 0.2);
return $this->setWeight($weight);
}
public function mapDepth()
{
$depth = $this->product->get_height();
if (empty($depth)) {
return $this;
}
$depth = $this->helper->convertDimension($depth);
return $this->setDepth($depth);
}
public function mapLength()
{
$length = $this->product->get_length();
if (empty($length)) {
return $this;
}
$length = $this->helper->convertDimension($length);
return $this->setLength($length);
}
public function mapWidth()
{
$width = $this->product->get_width();
if (empty($width)) {
return $this;
}
$width = $this->helper->convertDimension($width);
return $this->setWidth($width);
}
public function mapTariffCode()
{
$tariffCodeAttribute = get_option('wc_settings_shippit_tariff_code_attribute');
$tariffCodeCustomAttribute = get_option('wc_settings_shippit_tariff_code_custom_attribute');
$tariffCodeValue = $this->mapProductAttribute($tariffCodeAttribute, $tariffCodeCustomAttribute);
if (empty($tariffCodeValue)) {
return $this;
}
return $this->setTariffCode($tariffCodeValue);
}
public function mapOriginCountryCode()
{
$originCountryCodeAttribute = get_option('wc_settings_shippit_origin_country_code_attribute');
$originCountryCodeAttibuteCustomAttribute = get_option('wc_settings_shippit_origin_country_code_custom_attribute');
$originCountryCodeValue = $this->mapProductAttribute($originCountryCodeAttribute, $originCountryCodeAttibuteCustomAttribute);
if (empty($originCountryCodeValue)) {
return $this;
}
return $this->setOriginCountryCode($originCountryCodeValue);
}
public function mapDangerousGoodsCode()
{
$dangerousGoodsCodeAttribute = get_option('wc_settings_shippit_dangerous_goods_code_attribute');
$dangerousGoodsCodeCustomAttribute = get_option('wc_settings_shippit_dangerous_goods_code_custom_attribute');
$dangerousGoodsCodeValue = $this->mapProductAttribute($dangerousGoodsCodeAttribute, $dangerousGoodsCodeCustomAttribute);
if (empty($dangerousGoodsCodeValue)) {
return $this;
}
return $this->setDangerousGoodsCode($dangerousGoodsCodeValue);
}
public function mapDangerousGoodsText()
{
$dangerousGoodsTextAttribute = get_option('wc_settings_shippit_dangerous_goods_text_attribute');
$dangerousGoodsTextCustomAttribute = get_option('wc_settings_shippit_dangerous_goods_text_custom_attribute');
$dangerousGoodsTextValue = $this->mapProductAttribute($dangerousGoodsTextAttribute, $dangerousGoodsTextCustomAttribute);
if (empty($dangerousGoodsTextValue)) {
return $this;
}
return $this->setDangerousGoodsText($dangerousGoodsTextValue);
}
public function mapProductAttribute($attribute, $customAttribute)
{
$value = null;
// If we have a mapped DG custom value, and the custom value is not empty, use this value
if ($attribute == self::CUSTOM_OPTION_VALUE) {
$value = $this->product->get_attribute($customAttribute);
}
// Otherwise, if we have a mapped text attribute, use this value
else {
$value = $this->product->get_attribute($attribute);
}
return $value;
}
}
<file_sep>/woocommerce-shippit.php
<?php
/*
* Plugin Name: WooCommerce Shippit
* Description: WooCommerce Shippit
* Version: 1.9.0
* Author: Shippit Pty Ltd
* Author URL: http://www.shippit.com
* Text Domain: woocommerce-shippit
* WC requires at least: 2.6.0
* WC Tested Up To: 7.7.1
*/
define('MAMIS_SHIPPIT_VERSION', '1.9.0');
// import core classes
include_once('includes/class-shippit-helper.php');
include_once('includes/class-shippit-settings.php');
include_once('includes/class-shippit-settings-method.php');
include_once('includes/class-shippit-core.php');
function init_shippit_core()
{
include_once('includes/class-upgrade.php');
$upgrade = new Mamis_Shippit_Upgrade();
$upgrade->run();
// import helper classes
include_once('includes/class-shippit-log.php');
include_once('includes/class-shippit-api.php');
include_once('includes/class-shippit-order.php');
include_once('includes/class-shippit-object.php');
include_once('includes/class-shippit-data-mapper-order.php');
include_once('includes/class-shippit-data-mapper-order-v26.php');
include_once('includes/class-shippit-data-mapper-order-item.php');
include_once('includes/class-shippit-data-mapper-order-item-v26.php');
include_once('includes/class-shippit-shipment.php');
$shippit = Mamis_Shippit_Core::instance();
add_filter(
'woocommerce_settings_tabs_array',
array(
'Mamis_Shippit_Settings',
'addSettingsTab',
),
50
);
}
// add shippit core functionality
add_action('woocommerce_init', 'init_shippit_core', 99999);
// register shippit script
add_action('admin_enqueue_scripts', 'register_shippit_script');
function register_shippit_script()
{
wp_register_script(
'shippit-script',
plugin_dir_url(__FILE__) . 'assets/js/shippit.js',
array('jquery'),
MAMIS_SHIPPIT_VERSION,
true
);
}
function init_shippit_method()
{
include_once('includes/class-shippit-log.php');
include_once('includes/class-shippit-api.php');
include_once('includes/class-shippit-method.php');
include_once('includes/class-shippit-method-legacy.php');
// add shipping methods
add_filter('woocommerce_shipping_methods', array('Mamis_Shippit_Method', 'add_shipping_method'));
add_filter('woocommerce_shipping_methods', array('Mamis_Shippit_Method_Legacy', 'add_shipping_method'));
}
// add shipping method class
add_action('woocommerce_shipping_init', 'init_shippit_method');
// register the cron job hooks when activating / de-activating the module
register_activation_hook(__FILE__, array('Mamis_Shippit_Core', 'order_sync_schedule'));
register_deactivation_hook(__FILE__, array('Mamis_Shippit_Core', 'order_sync_deschedule'));
<file_sep>/assets/js/shippit.js
jQuery(document).ready(function () {
// Ensure the attributes are displayed based on the currently active options
registerOnchangeEvent('wc_settings_shippit_tariff_code');
registerOnchangeEvent('wc_settings_shippit_dangerous_goods_code');
registerOnchangeEvent('wc_settings_shippit_dangerous_goods_text');
registerOnchangeEvent('wc_settings_shippit_origin_country_code');
});
function registerOnchangeEvent(attributeId)
{
// Register the event handler
// Handle change event for select2 versions > 4.0.0 as well as older versions
jQuery('[name="' + attributeId + '_attribute"]').on('select2:select, change', function() {
visibilityCustomAttribute(attributeId);
});
// Update the current display
visibilityCustomAttribute(attributeId);
}
function visibilityCustomAttribute(attributeId)
{
var value = jQuery('[name="' + attributeId + '_attribute"]').val();
if (value == '_custom') {
jQuery('input[name="' + attributeId + '_custom_attribute"]').closest('tr').show();
}
else {
jQuery('input[name="' + attributeId + '_custom_attribute"]').closest('tr').hide();
}
}
<file_sep>/includes/class-upgrade.php
<?php
class Mamis_Shippit_Upgrade
{
const OPTIONS_PREFIX = 'wc_settings_shippit_';
public function run()
{
$dbVersion = get_option('wc_shippit_version', 0);
// If an upgrade is not required, stop here
if (version_compare(MAMIS_SHIPPIT_VERSION, $dbVersion, '<=')) {
return;
}
$this->upgrade_1_3_0($dbVersion);
$this->upgrade_1_4_0($dbVersion);
$this->upgrade_1_5_5($dbVersion);
// Mark the upgrade as complete
$this->upgrade_complete($dbVersion);
}
protected function upgrade_1_3_0($dbVersion)
{
// Avoid running this update if it's not required
if (version_compare('1.3.0', $dbVersion, '<=')) {
return;
}
// Migrate the core module settings to the new "Shippit Tab"
$oldOptions = get_option('woocommerce_mamis_shippit_settings');
$newOptions = array(
'enabled',
'api_key',
'debug',
'environment',
'send_all_orders',
'standard_shipping_methods',
'express_shipping_methods',
'international_shipping_methods'
);
if (!empty($oldOptions)) {
foreach ($oldOptions as $key => $value) {
if (in_array($key, $newOptions)) {
update_option(self::OPTIONS_PREFIX . $key, $value);
}
}
}
// Migrate the shipping method settings to "legacy"
update_option('woocommerce_mamis_shippit_legacy_settings', $oldOptions);
// Update version
update_option('wc_shippit_version', '1.3.0');
}
protected function upgrade_1_4_0($dbVersion)
{
// Avoid running this update if it's not required
if (version_compare('1.4.0', $dbVersion, '<=')) {
return;
}
// Migrate the core module settings to the new "Shippit Tab"
$shippingMethodsStandard = get_option(self::OPTIONS_PREFIX . 'standard_shipping_methods');
$shippingMethodsExpress = get_option(self::OPTIONS_PREFIX . 'express_shipping_methods');
$shippingMethodsStandardMigrate = (array) $shippingMethodsStandard;
$shippingMethodsExpressMigrate = (array) $shippingMethodsExpress;
$zones = WC_Shipping_Zones::get_zones();
foreach ($zones as $zone) {
$shippingMethods = $zone['shipping_methods'];
foreach ($shippingMethods as $shippingMethod) {
// If the standard shipping method is currently mapped,
// update the mapping to include zone mapped methods
if ($shippingMethodsStandard && in_array($shippingMethod->id, $shippingMethodsStandard)) {
// determine the mapping key
$shippingMethodKey = $shippingMethod->id . ':' . $shippingMethod->instance_id;
$shippingMethodsStandardMigrate[] = $shippingMethodKey;
}
// If the standard shipping method is currently mapped,
// update the mapping to include zone mapped methods
if ($shippingMethodsExpress && in_array($shippingMethod->id, $shippingMethodsExpress)) {
// determine the mapping key
$shippingMethodKey = $shippingMethod->id . ':' . $shippingMethod->instance_id;
$shippingMethodsExpressMigrate[] = $shippingMethodKey;
}
}
}
update_option(self::OPTIONS_PREFIX . 'standard_shipping_methods', $shippingMethodsStandardMigrate);
update_option(self::OPTIONS_PREFIX . 'express_shipping_methods', $shippingMethodsExpressMigrate);
// Update version
update_option('wc_shippit_version', '1.4.0');
}
protected function upgrade_1_5_5($dbVersion)
{
// Avoid running this update if it's not required
if (version_compare('1.5.5', $dbVersion, '<=')) {
return;
}
$sendAllOrders = get_option(self::OPTIONS_PREFIX . 'send_all_orders');
if ($sendAllOrders == 'yes') {
$value = 'all';
}
else {
$value = 'no';
}
update_option(self::OPTIONS_PREFIX . 'auto_sync_orders', $value);
// Update version
update_option('wc_shippit_version', '1.5.5');
}
protected function upgrade_complete($dbVersion)
{
// Update DB version to latest code release version
update_option('wc_shippit_version', MAMIS_SHIPPIT_VERSION);
}
}
<file_sep>/readme.txt
=== Shippit for WooCommerce ===
Contributors: matthewmuscat
Donate link: NA
Tags: shipping, australia post, couriers please, aramex
Requires at least: 3.0.0
Tested up to: 6.2.2
Stable tag: stable
Requires PHP: 5.4
License: Shippit Commercial Licence
License URI: https://www.shippit.com/terms-of-service
== Description ==
Shippit is a shipping platform that connects WooCommerce customers with a network of carriers. Retailers don't have time to waste on shipping stuff. Plug in to Shippit and forget all about negotiating rates, finding the best carriers or spending hours on the phone chasing couriers. Book, Print and Ship.
* Manage multiple delivery services easily with one account and bill
* Never leave your store again with daily pickup on all deliveries
* Keep customers happy with FREE email and SMS notifications
We've negotiated rates with the best carriers so you don't have to. No account keeping fees, no credit checks, no lock-in contracts
* National Satchels from $5.99 (ex. GST)
* National Same / Next Day from $7.99 (ex. GST)
* Metro 3-Hour Timeslot Delivery from $7.30 (ex.GST)
Automatic labelling and tracking is just the beginning. Shippit's focus on customer satisfaction will change the way you ship forever.
* Print labels, despatch and track deliveries in a jiffy with our expert-designed workflow system
* Plug in to quality delivery services with our Approved Carriers
* Keep customers happy with Shippit's unique Proactive Tracking and Notification System that is proven to reduce missed delivery rates by up to 50%!
Whether you ship from a warehouse, a store or both, we've got you covered.
* Ship from store using Shippit Send a Package with saved location support.
* Multiple user and location support enables simplified drop-shipping.
== Installation ==
You can install this plugin directly from your WordPress dashboard:
1. Navigate to Plugin section of WooCommerce admin
2. Click "Add New" next to the Plugins title
3. Upload `woocommerce-shippit.zip'
4. Navigate to WooCommerce > Settings > Shipping > Shippit
5. Select "Enable = Yes" from drop down
6. Enter API Key and saving settings
Get your API key at www.shippit.com
== Frequently Asked Questions ==
= How do I get an API key? =
Go to www.shippit.com and sign up for an account. We will email you an API key
== Screenshots ==
1. See all your orders and live courier pricing in real time as customers check out
2. You can send a package at any time with live quoting
3. You and your customers can track their deliveries simply, elegantly and easily
== Changelog ==
= 1.9.0 =
- Added
-- Added a depreciation notice for users using the "Shippit (Legacy)" shipping method, with details on using Shipping Zones
-- Add CI linter coverage for PHP 7.2, 7.3, 7.4, 8.0 and 8.1
- Changes
-- Removed the "filter by product" configuration option if this option is not already configured, resolving a performance issue for large stores
= 1.8.1 =
- Bugfixes
-- Resolved an issue where incorrect version metadata was set on the release
= 1.8.0 =
- Added
-- Updated tested upto tag to indicate support for WooCommerce 6.9.4
= 1.7.2 =
- Bugfixes
-- Resolved an issue where orders containing a partial refund would not be marked as completed when goods are shipped
= 1.7.1 =
- Bugfixes
-- Bumped internal version number in metadata to v1.7.1
= 1.7.0 =
- Added
-- Support for capturing the courier tracking number when creating a shipment
= 1.6.7 =
- Changes
-- Validated plugin is tested on Wordpress v6 and WooCommerce v6.8
= 1.6.6 =
- Bugfixes
-- Resolved an issue whereby DB upgrades may throw an error if the configuration is empty / not set
= 1.6.5 =
- Bugfixes
-- Resolved an issue whereby Bulk Sync actions may take a number of hours to run after they are scheduled
= 1.6.4 =
- Bugfixes
-- Remove calls to depreciated woocommerce methods
-- Re-add module resource assets to installation
= 1.6.3 =
- Changes
-- Improve handling on `api_key` or `webhook` setting updates
= 1.6.2 =
- Changes
-- Removed `state/region` as a required field for live quotes, ensuring live quotes are available in countries without states/regions.
= 1.6.1 =
- Changes
-- We have validated this release for WooCommerce version v5.4, and Wordpress v5.7.2
= 1.6.0 =
- Changes
-- We've updated the way we authenticate with the Shippit API - we'll now utilize header-based bearer authorization
= 1.5.6 =
- Bugfixes
-- Resolved an issue whereby multiple instances of the same "Shipping Method" in the "Default Zone" could not be mapped using Shipping Method Mapping
= 1.5.5 =
- New Features
-- Added the ability to only sync orders mapped to a Shippit Service
-- Added support for mapping shipping methods from the "Default Zone" in WooCommerce
- Changes
-- We have improved the display of shipping methods in our Shipping Method Mapping configuration area to make it easier to identify shipping methods across zones
-- We will now avoid making a Live Quote request to Shippit if required address details are missing
- Bugfixes
-- Resolved an issue whereby an item's price details was sent to Shippit without GST, item prices will now include any applicable taxes when sent to Shippit
-- Resolved an issue whereby manual orders may result the incorrect order may be marked as shipped in WooCommerce
= 1.5.4 =
- New Features
-- We have added the ability to capture the language and currency code of orders
-- We have added the ability to capture a products `Country of Origin`, `Tariff Code` and `Dangerous Goods` Details
-- We now capture the `Dutiable Amount` of an order during live quoting, this is based on the product's value in the cart, enabling Live Quotes to consider duties such as customs
= 1.5.3 =
- New Features
-- We now update your merchant account to indicate it's connected with a woocommerce store
- Changes
-- We've adjusted the way we trigger validation of your Shippit API key when updating it's value in the backend settings
= 1.5.2 =
- New Features
-- Added the street address to live quote requests, which can now be utilised by on-demand delivery services
-- Added dutiable amounts to live quote requests
= 1.5.1 =
- Bugfixes
-- We've resolved an issue with an item's weight not being sent to Shippit
= 1.5.0.1 =
- Changes
-- We've updated the range of Wordpress versions supported by this plugin
= 1.5.0 =
- New Features
-- We've improved the way we handle order data mappings
-- We've added support across WooCommerce v2.6 - WooCommerce v3.6
- Bugfixes
-- Resolved an issue whereby the incorrect shipping method may be selected when utilising live quotes
= 1.4.7 =
- New Features
-- We'll now include both the woocommerce order internal identifier, and the friendly order reference number when communicating orders and shipments
- Bugfixes
-- Resolved an issue whereby an incorrect order could be marked as shipped if the order id was not provided in an expected format
-- Improved support for earlier versions of WooCommerce when retrieving a order items product name
= 1.4.6 =
- New Features
-- Added support for WooCommerce v1.4.0
- Bugfixes
-- Resolved an issue with Shipping Method Mapping for orders created using WooCommerce v1.4.0
= 1.4.5 =
- New Features
-- Added a feature flag that could disable the product filtering functionality on quotes, enabling larger stores to avoid a potentially expensive query
- Bugfixes
-- Resolved an issue that could prevent shipments from being registered in php v7.0.x environments.
= 1.4.4 =
- New Features
-- Added a Shipments Meta box to the Orders Admin Area, with details as to the shipments completed by Shippit
= 1.4.3 =
- New Features
-- Added support for the WooCommerce table rates plugin with shipping method mapping functionality
= 1.4.2 =
- New Features
-- Added the ability to retrieve live quotes in the cart shipping estimator
= 1.4.1 =
- New Features
-- Added click and collect shipping method as an available shipping method mapping
- Updates
-- Updated shipping method quotes to utilise the service level name as the shipping method identifier
-- Removed references to international shipping method mapping services
—-- We now use service levels of standard, express and priority to indicate service levels for domestic + international services
—-- Removes the hard-allocation of all non-AU based orders to international, as we now use the service level names
-- Renamed “premium” services to “priority”
- Cleanup
-- Cleanup of the shipping method mapping logic to an abstracted function that processes the relevant details and returns the api data required for the order to be sent to Shippit
= 1.4.0 =
- New Features
-- Adds the ability to setup shipping method mapping based on the individual zone methods
-- Improved messaging if a sync failure occurs
- Bugfixes
-- Resolve an issue whereby the wrong order could be send in some environments
= 1.3.9 =
- New Features
-- Adds the ability to send orders manually, via the orders listing page or when editing an order directly
-- Adds a new configuration option for the "Authority To Leave" field in Checkout, allowing it to be disabled if required.
- Bugfixes
-- Resolve an issue whereby orders could be sent to Shippit without any items in the order
= 1.3.8 =
- Bugfixes
-- Resolved an issue whereby shipping method mapping may not map correctly when using Shipping Method Instances in WooCommerce v3
= 1.3.7 =
- New Features
-- Adds support for WooCommerce v3
—-- Ensures variation products are loaded via WC_Product_Variation on fulfillments
—-- resolves minor PHP_NOTICE errors messages due to WooCommerce v3 changes on accessing order properties
- Bugfixes
-- Resolves undefined index “default” message when loading shipping method settings
= 1.3.6 =
- Feature - Allow for shipments of orders without SKU details to be accepted and processed by the plugin
= 1.3.5 =
- Bugfix - Ensure live quotes take into account the WooCommerce Taxation preferences
= 1.3.4 =
- add plugin syntax support for PHP 5.2 and 5.3
= 1.3.3 =
- Feature - Add feature flag to enable merchants to ignore item dimensions in quotes / orders
-- To enable, add "define(`SHIPPIT_IGNORE_ITEM_DIMENSIONS`, true)" to wp-config.php
= 1.3.2 =
- Bugfix - Fixes a bug affecting unsupported version of PHP (< PHP 5.4)
= 1.3.1 =
- Change - Include the taxable amount for item prices sent to Shippit
= 1.3.0 =
- Feature - Add support for shipping zones - you can now use shipping live quotes within WooCommerce Shipping Zones - we've kept the old shipping method active, however we suggest updating your shipping method to utilise the new zones functionality, as this legacy method will be removed in a future release.
- Change - A new "Shippit" tab will now appear in WooCommerce for all Shippit core settings, shippit shipping method options will now only contain configuration options relating to live quoting functionality, with order sync and fulfillment sync options now shown in the "Shippit" tab
= 1.2.13 =
- Bugfix - Resolve an issue where if the jetpack module was present, but disabled, custom orders numbers logic was still being used - causing the fulfillment webhook to fail to locate the order for fulfillment.
= 1.2.12 =
- Feature - Add support for shipping orders that use custom order numbers in the WooCommerce Jetpack module
= 1.2.11 =
- Bugfix - Resolve an issue where an order may not be marked as shipped, due to differing order id and woocommerce order numbers
= 1.2.10 =
- Bugfix - Resolve an issue with the product height dimensions not being synced correctly via the api
= 1.2.9 =
- Change - API timeout updates
- Bugfix - Resolve an issue with product dimentions when syncing orders
= 1.2.8 =
* Bugfix - Resolve an issue retrieving the product width value
= 1.2.7 =
* Bugfix - Use the property "method_title" shipping method mappings, as used in new shipping methods as of WC 2.6.x
= 1.2.5 =
* Add functionality to enable merchants to add a margin to the quoted shipping prices (fixed or percentage).
* Ensure qty, price and weight details are sent to the api as floats
= 1.2.3 =
* Fix a bug in marking orders as shipped on some webhook requests
* Improve logging information on webhook activity
* Improve logging information on api response activity
= 1.2.2 =
* Update staging to use secure staging api endpoint
= 1.2.1 =
* Adds support for orders initially created in a processing state to be synced
= 1.2.0 =
* Enables international orders to be sent to Shippit
* Allow for shipping methods to be mapped to "international"
* Add item level details to the order sync data (name, qty, price, weight)
* Add item level receive logic to the webhook sync logic
** Includes support for partial shipping and product variations
= 1.1.13 =
* Fix an issue whereby the settings form fields logic would load whenever the page being loaded involved the shippit shipping method, settings are now loaded only on the settings page
* Avoid a php error when filter by products is enabled, but there are no products in the filter
= 1.1.12 =
* Fix an issue whereby shipping method mappings would fail to load on some version of PHP (< PHP v5.6)
* Avoid php errors when no apiResponse is recieved
= 1.1.10 =
* Fix a bug in the plugin activation due to the core files not being available early on in module init
= 1.1.9 =
* Fix a bug where if the webhook registration api request failed, no notification was shown to the user
= 1.1.8 =
* Update api endpoint url for production to use HTTPs
* Update api endpoint for staging to use the shippit domain
* Add the company name to the order sync request data
= 1.1.7 =
* Adds functionality to enable other shipping methods to be utilised and synced with Shippit
= 1.1.6 =
* Updates the quotes and order sync api calls to use the individual item weights, rather than the total weight
= 1.1.5 =
* Updates the label of a standard quote to use "Standard" instead of "Couriers Please"
= 1.1.4 =
* Adds some additional checks on the API methods before attempting to return the response
= 1.1.3 =
* Resolves an issue with the logging system containing an undefined variable
= 1.1.2 =
* Resolves an issue where shipping address line 2 was not being captured
= 1.0.0 =
* Live quoting for Standard and Scheduled deliveries
* Shippit can be enabled to accept orders not requiring live quoting
* Product filtering for live quoting on individual products or specified attributes
== Upgrade Notice ==
= 1.9.0 =
Resolves a performance issue affecting stores with large catalogs (over 1,000 products)
<file_sep>/includes/class-shippit-method.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Method extends WC_Shipping_Method
{
protected $api;
protected $helper;
/**
* Constructor.
*/
public function __construct($instance_id = 0)
{
$this->api = new Mamis_Shippit_Api();
$this->log = new Mamis_Shippit_Log();
$this->helper = new Mamis_Shippit_Helper();
$settings = new Mamis_Shippit_Settings_Method();
$this->id = 'mamis_shippit';
$this->instance_id = absint($instance_id);
$this->instance_form_fields = $settings->getFields();
$this->title = __('Shippit', 'woocommerce-shippit');
$this->method_title = __('Shippit', 'woocommerce-shippit');
$this->method_description = __('Have Shippit provide you with live quotes directly from the carriers. Simply enable live quoting and set your preferences to begin.');
$this->supports = array(
'shipping-zones',
'instance-settings',
// Disable instance modal settings due to array not saving correctly
// https://github.com/bobbingwide/woocommerce/commit/1e8d9d4c95f519df090e3ec94d8ea08eb8656c9f
// 'instance-settings-modal',
);
$this->init();
}
/**
* Initialize plugin parts.
*
* @since 1.0.0
*/
public function init()
{
// Initiate instance settings as class variables
// Use property "quote_enabled", as "enabled" is used by the parent method
$this->quote_enabled = $this->get_option('enabled');
$this->title = $this->get_option('title');
$this->allowed_methods = $this->get_option('allowed_methods');
$this->max_timeslots = $this->get_option('max_timeslots');
$this->filter_enabled = 'no'; // depreciated
$this->filter_enabled_products = array(); // depreciated
$this->filter_attribute = $this->get_option('filter_attribute');
$this->filter_attribute_code = $this->get_option('filter_attribute_code');
$this->filter_attribute_value = $this->get_option('filter_attribute_value');
$this->margin = $this->get_option('margin');
$this->margin_amount = $this->get_option('margin_amount');
// Add action hook to save the shipping method instance settings when they saved
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
}
/**
* Add shipping method.
*
* Add shipping method to WooCommerce.
*
*/
public static function add_shipping_method($methods)
{
if (class_exists('Mamis_Shippit_Method')) {
$methods['mamis_shippit'] = 'Mamis_Shippit_Method';
}
return $methods;
}
/**
* Calculate shipping.
*
* @param mixed $package
* @return void
*/
public function calculate_shipping($package = array())
{
// Check if the module is enabled and used for shipping quotes
if (get_option('wc_settings_shippit_enabled') != 'yes'
|| $this->quote_enabled != 'yes') {
return;
}
// Ensure we have a shipping method available for use
if (empty($this->allowed_methods)) {
return;
}
$quoteDestination = $package['destination'];
$quoteCart = $package['contents'];
// Check if we can ship the products by enabled filtering
if (!$this->_canShipEnabledProducts($package)) {
return;
}
// Check if we can ship the products by attribute filtering
if (!$this->_canShipEnabledAttributes($package)) {
return;
}
$this->_processShippingQuotes($quoteDestination, $quoteCart);
}
private function getParcelAttributes($items)
{
$itemDetails = array();
foreach ($items as $cartItemId => $item) {
$itemDetail = array();
// If product is variation, load variation ID
if ($item['variation_id']) {
$cartItem = wc_get_product($item['variation_id']);
}
else {
$cartItem = wc_get_product($item['product_id']);
}
$itemWeight = $cartItem->get_weight();
$itemHeight = $cartItem->get_height();
$itemLength = $cartItem->get_length();
$itemWidth = $cartItem->get_width();
$itemDetail['qty'] = $item['quantity'];
if (!empty($itemWeight)) {
$itemDetail['weight'] = $this->helper->convertWeight($itemWeight);
}
else {
// stub weight to 0.2kg
$itemDetail['weight'] = 0.2;
}
if (!defined('SHIPPIT_IGNORE_ITEM_DIMENSIONS')
|| !SHIPPIT_IGNORE_ITEM_DIMENSIONS) {
if (!empty($itemHeight)) {
$itemDetail['depth'] = $this->helper->convertDimension($itemHeight);
}
if (!empty($itemLength)) {
$itemDetail['length'] = $this->helper->convertDimension($itemLength);
}
if (!empty($itemWidth)) {
$itemDetail['width'] = $this->helper->convertDimension($itemWidth);
}
}
$itemDetails[] = $itemDetail;
}
return $itemDetails;
}
private function _processShippingQuotes($quoteDestination, $quoteCart)
{
$isPriorityAvailable = in_array('priority', $this->allowed_methods);
$isExpressAvailable = in_array('express', $this->allowed_methods);
$isStandardAvailable = in_array('standard', $this->allowed_methods);
$dropoffSuburb = $quoteDestination['city'];
$dropoffPostcode = $quoteDestination['postcode'];
$dropoffState = $quoteDestination['state'];
$dropoffCountryCode = $quoteDestination['country'];
$items = WC()->cart->get_cart();
// Only make a live quote request if required fields are present
if (empty($dropoffSuburb)) {
$this->log->add(
'Quote Request',
'A suburb is required for a live quote'
);
return;
}
elseif (empty($dropoffPostcode)) {
$this->log->add(
'Quote Request',
'A postcode is required for a live quote'
);
return;
}
elseif (empty($dropoffCountryCode)) {
$this->log->add(
'Quote Request',
'A country is required for a live quote'
);
return;
}
$quoteData = array(
'order_date' => '', // get all available dates
'dropoff_address' => $this->getDropoffAddress($quoteDestination),
'dropoff_suburb' => $dropoffSuburb,
'dropoff_postcode' => $dropoffPostcode,
'dropoff_state' => $dropoffState,
'dropoff_country_code' => $dropoffCountryCode,
'parcel_attributes' => $this->getParcelAttributes($items)
);
// @Workaround
// - Only add the dutiable_amount for domestic orders
// - The Shippit Quotes API does not currently support the dutiable_amount
// field being present for domestic (AU) deliveries — declaring a dutiable
// amount value for these quotes may result in some carrier quotes not
// being available.
if ($dropoffCountryCode != 'AU') {
$quoteData['dutiable_amount'] = WC()->cart->get_cart_contents_total();
}
$shippingQuotes = $this->api->getQuote($quoteData);
if ($shippingQuotes) {
foreach ($shippingQuotes as $shippingQuote) {
if ($shippingQuote->success) {
switch ($shippingQuote->service_level) {
case 'priority':
if ($isPriorityAvailable) {
$this->_addPriorityQuote($shippingQuote);
}
break;
case 'express':
if ($isExpressAvailable) {
$this->_addExpressQuote($shippingQuote);
}
break;
case 'standard':
if ($isStandardAvailable) {
$this->_addStandardQuote($shippingQuote);
}
break;
}
}
}
}
else {
return false;
}
}
/**
* Get the dropoff address value for a quote
*
* @param array $quoteDestination
* @return string|null
*/
private function getDropoffAddress($quoteDestination)
{
$addresses = [
$quoteDestination['address'],
$quoteDestination['address_2'],
];
$addresses = array_filter($addresses, function ($address) {
$address = trim($address);
return !empty($address);
});
if (empty($addresses)) {
return null;
}
return implode(', ', $addresses);
}
private function _addStandardQuote($shippingQuote)
{
foreach ($shippingQuote->quotes as $quote) {
$quotePrice = $this->_getQuotePrice($quote->price);
$rate = array(
// unique id for each rate
'id' => 'Mamis_Shippit_' . $shippingQuote->service_level,
'label' => ucwords($shippingQuote->service_level),
'cost' => $quotePrice,
'meta_data' => array(
'service_level' => $shippingQuote->service_level,
'courier_allocation' => $shippingQuote->courier_type,
),
);
$this->add_rate($rate);
}
}
private function _addExpressQuote($shippingQuote)
{
foreach ($shippingQuote->quotes as $quote) {
$quotePrice = $this->_getQuotePrice($quote->price);
$rate = array(
'id' => 'Mamis_Shippit_' . $shippingQuote->service_level,
'label' => ucwords($shippingQuote->service_level),
'cost' => $quotePrice,
'meta_data' => array(
'service_level' => $shippingQuote->service_level,
'courier_allocation' => $shippingQuote->courier_type,
),
);
$this->add_rate($rate);
}
}
private function _addPriorityQuote($shippingQuote)
{
$timeSlotCount = 0;
foreach ($shippingQuote->quotes as $priorityQuote) {
if (!empty($this->max_timeslots) && $this->max_timeslots <= $timeSlotCount) {
break;
}
// Increase the timeslot count
$timeSlotCount++;
$quotePrice = $this->_getQuotePrice($priorityQuote->price);
$rate = array(
'id' => sprintf(
'Mamis_Shippit_%s_%s_%s',
$shippingQuote->service_level,
$priorityQuote->delivery_date,
$priorityQuote->delivery_window
),
'label' => sprintf(
'Scheduled - Delivered %s between %s',
date('d/m/Y', strtotime($priorityQuote->delivery_date)),
$priorityQuote->delivery_window_desc
),
'cost' => $quotePrice,
'meta_data' => array(
'service_level' => $shippingQuote->service_level,
'courier_allocation' => $priorityQuote->courier_type,
'delivery_date' => $priorityQuote->delivery_date,
'delivery_window' => $priorityQuote->delivery_window
),
);
$this->add_rate($rate);
}
}
/**
* Get the quote price, including the margin amount
* @param float $quotePrice The quote amount
* @return float The quote amount, with margin
* if applicable
*/
private function _getQuotePrice($quotePrice)
{
switch ($this->margin) {
case 'yes-fixed':
$quotePrice += (float) $this->margin_amount;
break;
case 'yes-percentage':
$quotePrice *= (1 + ( (float) $this->margin_amount / 100));
}
// ensure we get the lowest price, but not below 0.
$quotePrice = max(0, $quotePrice);
return $quotePrice;
}
/**
* Checks if we can ship the products in the cart
*
* @depreciated - this functionality is only available on
* the legacy shipping method - it will be removed in Q1 2018
*/
private function _canShipEnabledProducts($package)
{
if ($this->filter_enabled == 'no') {
return true;
}
if ($this->filter_enabled_products == null) {
return false;
}
$allowedProducts = $this->filter_enabled_products;
$products = $package['contents'];
$productIds = array();
foreach ($products as $itemKey => $product) {
$productIds[] = $product['product_id'];
}
if (!empty($allowedProducts)) {
// If item is not enabled return false
if ($productIds != array_intersect($productIds, $allowedProducts)) {
$this->log->add(
'Can Ship Enabled Products',
'Returning false'
);
return false;
}
}
$this->log->add(
'Can Ship Enabled Products',
'Returning true'
);
return true;
}
private function _canShipEnabledAttributes($package)
{
if ($this->filter_attribute == 'no') {
return true;
}
$attributeCode = $this->filter_attribute_code;
// Check if there is an attribute code set
if (empty($attributeCode)) {
return true;
}
$attributeValue = $this->filter_attribute_value;
// Check if there is an attribute value set
if (empty($attributeValue)) {
return true;
}
$products = $package['contents'];
foreach ($products as $itemKey => $product) {
$productObject = new WC_Product($product['product_id']);
$productAttributeValue = $productObject->get_attribute($attributeCode);
if (strpos($productAttributeValue, $attributeValue) === false) {
$this->log->add(
'Can Ship Enabled Attributes',
'Returning false'
);
return false;
}
}
$this->log->add(
'Can Ship Enabled Attributes',
'Returning true'
);
return true;
}
}
<file_sep>/includes/class-shippit-log.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Log
{
public function add($errorType, $message = null, $metaData = null, $severity = 'info')
{
// If debug mode is active, log all info serverities, otherwise log only errors
if (get_option('wc_settings_shippit_debug') == 'yes' || $severity == 'error') {
error_log('-- ' . $errorType . ' --');
if (!is_null($message)) {
error_log($message);
}
if (!is_null($metaData)) {
error_log(json_encode($metaData));
}
}
}
/**
* add function.
*
* Uses the build in logging method in WooCommerce.
* Logs are available inside the System status tab
*
* @access public
* @param string|array|object
* @return void
*/
public function exception($exception)
{
error_log($exception->getMessage());
}
}<file_sep>/includes/class-shippit-method-legacy.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Method_Legacy extends Mamis_Shippit_Method
{
protected $api;
protected $helper;
/**
* Constructor.
*/
public function __construct()
{
$this->api = new Mamis_Shippit_Api();
$this->log = new Mamis_Shippit_Log();
$this->helper = new Mamis_Shippit_Helper();
$this->id = 'mamis_shippit_legacy';
$this->title = __('Shippit (Legacy)', 'woocommerce-shippit');
$this->method_title = __('Shippit (Legacy)', 'woocommerce-shippit');
$this->method_description = __(
'<p>
Have Shippit provide you with live quotes directly from the carriers.
Simply enable live quoting and set your preferences to begin.
</p>'
);
$this->init();
}
/**
* Initialize plugin parts.
*
* @since 1.0.0
*/
public function init()
{
// Initiate instance settings as class variables
$this->quote_enabled = $this->get_option('enabled');
$this->title = $this->get_option('title');
$this->allowed_methods = $this->get_option('allowed_methods');
$this->max_timeslots = $this->get_option('max_timeslots');
$this->filter_enabled = $this->get_option('filter_enabled'); // depreciated
$this->filter_enabled_products = $this->get_option('filter_enabled_products'); // depreciated
$this->filter_attribute = $this->get_option('filter_attribute');
$this->filter_attribute_code = $this->get_option('filter_attribute_code');
$this->filter_attribute_value = $this->get_option('filter_attribute_value');
$this->margin = $this->get_option('margin');
$this->margin_amount = $this->get_option('margin_amount');
$this->init_form_fields();
$this->init_settings();
// Add action hook to save the shipping method instance settings when they saved
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
}
public function init_form_fields()
{
// Filter by Products should only be available when...
// - The merchant has it actively enabled in the current settings; and
// - The named constant `SHIPPIT_DISABLE_PRODUCT_FILTER` is not present
$isFilterByProductsEnabled = (
$this->get_option('filter_enabled') === 'yes'
&& defined('SHIPPIT_DISABLE_PRODUCT_FILTER') === false
);
$settings = new Mamis_Shippit_Settings_Method();
$this->form_fields = $settings->getFields($isFilterByProductsEnabled);
return $this->form_fields;
}
/**
* Add shipping method.
*
* Add shipping method to WooCommerce.
*
*/
public static function add_shipping_method($methods)
{
if (class_exists('Mamis_Shippit_Method_Legacy')) {
$methods['mamis_shippit_legacy'] = 'Mamis_Shippit_Method_Legacy';
}
return $methods;
}
}
<file_sep>/includes/class-shippit-helper.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Helper
{
/**
* Convert the dimension to a different unit size
*
* based on https://gist.github.com/mbrennan-afa/1812521
*
* @param float $dimension The dimension to be converted
* @param string $unit The unit to be converted to
* @return float The converted dimension
*/
public function convertDimension($dimension, $unit = 'm')
{
$dimensionCurrentUnit = get_option('woocommerce_dimension_unit');
$dimensionCurrentUnit = strtolower($dimensionCurrentUnit);
$unit = strtolower($unit);
if ($dimensionCurrentUnit !== $unit) {
// Unify all units to cm first
switch ($dimensionCurrentUnit) {
case 'inch':
$dimension *= 2.54;
break;
case 'm':
$dimension *= 100;
break;
case 'mm':
$dimension *= 0.1;
break;
}
// Output desired unit
switch ($unit) {
case 'inch':
$dimension *= 0.3937;
break;
case 'm':
$dimension *= 0.01;
break;
case 'mm':
$dimension *= 10;
break;
}
}
return $dimension;
}
/**
* Convert the weight to a different unit size
*
* based on https://gist.github.com/mbrennan-afa/1812521
*
* @param float $weight The weight to be converted
* @param string $unit The unit to be converted to
* @return float The converted weight
*/
public function convertWeight($weight, $unit = 'kg')
{
$weightCurrentUnit = get_option('woocommerce_weight_unit');
$weightCurrentUnit = strtolower($weightCurrentUnit);
$unit = strtolower($unit);
if ($weightCurrentUnit !== $unit) {
// Unify all units to kg first
switch ($weightCurrentUnit) {
case 'g':
$weight *= 0.001;
break;
case 'lbs':
$weight *= 0.4535;
break;
case 'oz':
$weight *= 0.0279798545;
break;
}
// Output desired unit
switch ($unit) {
case 'g':
$weight *= 1000;
break;
case 'lbs':
$weight *= 2.204;
break;
case 'oz':
$weight *= 35.274;
break;
}
}
return $weight;
}
public function isShippitLiveQuote($order)
{
$shippingMethods = $order->get_shipping_methods();
foreach ($shippingMethods as $shippingMethod) {
// @TODO: use get_method_id() check if still works on v3.6
// If the method is a shippit live quote, return the title of the method
if (stripos($shippingMethod['method_id'], 'mamis_shippit') !== FALSE) {
return true;
}
}
return false;
}
public function getShippitLiveQuoteDetail($order, $detail)
{
$shippingMethods = $order->get_shipping_methods();
foreach ($shippingMethods as $shippingMethod) {
// If the method is a shippit live quote, return the title of the method
if (stripos($shippingMethod['method_id'], 'mamis_shippit') !== FALSE) {
// @TODO: use get_method_id() and get_meta() when support for 2.6 deprecated
//$metaDataItem = $shippingMethod->get_meta($detail);
$metaDataItem = $shippingMethod[$detail];
return $metaDataItem;
}
}
}
public function getMappedShippingMethod($order)
{
$shippingMethods = $order->get_shipping_methods();
$mappingsStandard = get_option('wc_settings_shippit_standard_shipping_methods', array());
$mappingsExpress = get_option('wc_settings_shippit_express_shipping_methods', array());
$mappingsClickAndCollect = get_option('wc_settings_shippit_clickandcollect_shipping_methods', array());
$mappingsPlainLabel = get_option('wc_settings_shippit_plainlabel_shipping_methods', array());
foreach ($shippingMethods as $shippingMethod) {
$shippingMethodId = $this->getShippingMethodId($shippingMethod);
// If the method is a shippit live quote, return the title of the method
// @TODO: use get_method_id() and get_meta() when support for 2.6 deprecated
if ($shippingMethod['method_id'] == 'mamis_shippit') {
// $serviceLevel = $shippingMethod->get_meta('service_level');
$serviceLevel = $shippingMethod['service_level'];
if (!empty($serviceLevel)) {
return $serviceLevel;
}
}
// Otherwise, attempt to locate a suitable method based on shipping method mappings
if (in_array($shippingMethodId, $mappingsStandard)) {
return 'standard';
}
elseif (in_array($shippingMethodId, $mappingsExpress)) {
return 'express';
}
elseif (in_array($shippingMethodId, $mappingsClickAndCollect)) {
return 'click_and_collect';
}
elseif (in_array($shippingMethodId, $mappingsPlainLabel)) {
return 'plainlabel';
}
}
return false;
}
protected function getShippingMethodId($shippingMethod)
{
// Since Woocommerce v3.4.0, the instance_id is saved in a seperate property of the shipping method
// To add support for v3.4.0, we'll append the instance_id, as this is how we store a mapping in Shippit
if (!empty($shippingMethod['instance_id'])) {
$shippingMethodId = sprintf(
'%s:%s',
$shippingMethod['method_id'],
$shippingMethod['instance_id']
);
}
else {
$shippingMethodId = $shippingMethod['method_id'];
}
// If the shipping method id has more than 1 ":" occarance,
// we only want the {method_id}:{instance_id}
// — stripping all other data
if (substr_count($shippingMethodId, ':') > 1) {
$shippingMethodId = sprintf(
'%s:%s',
strtok($shippingMethodId, ':'),
strtok(':')
);
}
return $shippingMethodId;
}
}
<file_sep>/includes/class-shippit-settings-method.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Settings_Method
{
/**
* Init fields.
*
* Add fields to the Shippit settings page.
*
*/
public function getFields($isFilterByProductsAvailable = false)
{
$fields['enabled'] = array(
'id' => 'wc_settings_shippit_enabled',
'title' => __('Enabled', 'woocommerce-shippit'),
'desc' => 'Utilise this shipping method for live quoting.',
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'no',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
),
);
$fields['title'] = array(
'title' => __('Title', 'woocommerce-shippit'),
'type' => 'text',
'default' => 'Shippit',
);
$fields['allowed_methods'] = array(
'title' => __('Allowed Methods', 'woocommerce-shippit'),
'id' => 'allowed_methods',
'class' => 'wc-enhanced-select',
'type' => 'multiselect',
'default' => array(
'standard',
'express',
'priority'
),
'options' => array(
'standard' => __('Standard', 'woocommerce-shippit'),
'express' => __('Express', 'woocommerce-shippit'),
'priority' => __('Priority', 'woocommerce-shippit'),
)
);
$fields['max_timeslots'] = array(
'title' => __('Maximum Timeslots', 'woocommerce-shippit'),
'description' => __('The maximum amount of timeslots to display', 'woocommerce-shippit'),
'desc_tip' => true,
'id' => 'max_timeslots',
'class' => 'wc-enhanced-select',
'default' => '',
'type' => 'select',
'options' => array(
'' => __('-- No Max Timeslots --', 'woocommerce-shippit'),
'1' => __('1 Timeslots', 'woocommerce-shippit'),
'2' => __('2 Timeslots', 'woocommerce-shippit'),
'3' => __('3 Timeslots', 'woocommerce-shippit'),
'4' => __('4 Timeslots', 'woocommerce-shippit'),
'5' => __('5 Timeslots', 'woocommerce-shippit'),
'6' => __('6 Timeslots', 'woocommerce-shippit'),
'7' => __('7 Timeslots', 'woocommerce-shippit'),
'8' => __('8 Timeslots', 'woocommerce-shippit'),
'9' => __('9 Timeslots', 'woocommerce-shippit'),
'10' => __('10 Timeslots', 'woocommerce-shippit'),
'11' => __('11 Timeslots', 'woocommerce-shippit'),
'12' => __('12 Timeslots', 'woocommerce-shippit'),
'13' => __('13 Timeslots', 'woocommerce-shippit'),
'14' => __('14 Timeslots', 'woocommerce-shippit'),
'15' => __('15 Timeslots', 'woocommerce-shippit'),
'16' => __('16 Timeslots', 'woocommerce-shippit'),
'17' => __('17 Timeslots', 'woocommerce-shippit'),
'18' => __('18 Timeslots', 'woocommerce-shippit'),
'19' => __('19 Timeslots', 'woocommerce-shippit'),
'20' => __('20 Timeslots', 'woocommerce-shippit'),
),
);
// Only show "filter enabled" and "filter_enabled_products"
// on the legacy shipping method class
//
// Also enables merchants to avoid this functionality if they have
// larger stores by setting the "SHIPPIT_DISABLE_PRODUCT_FILTER" constant
// to false
//
// @Depreciated: this functionality is due to be removed in 2018 Q1;
if ($isFilterByProductsAvailable) {
$fields['filter_enabled'] = array(
'title' => __('Filter by enabled products', 'woocommerce-shippit'),
'description' => __('Filter products that are enabled for quoting by shippit', 'woocommerce-shippit'),
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'no',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
),
);
$fields['filter_enabled_products'] = array(
'title' => __('Enabled Products', 'woocommerce-shippit'),
'description' => __('The products enabled for quoting by Shippit', 'woocommerce-shippit'),
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => '',
'type' => 'multiselect',
'options' => $this->_getProducts(),
);
}
$fields['filter_attribute'] = array(
'title' => __('Filter by product attributes', 'woocommerce-shippit'),
'description' => __('Filter products that are enabled for quoting by shippit via their attributes', 'woocommerce-shippit'),
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'no',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
),
);
$fields['filter_attribute_code'] = array(
'title' => __('Filter by attribute code', 'woocommerce-shippit'),
'description' => __('The product attribute code', 'woocommerce-shippit'),
'desc_tip' => true,
'type' => 'select',
'class' => 'wc-enhanced-select',
'default' => '',
'options' => $this->_getAttributes(),
);
$fields['filter_attribute_value'] = array(
'title' => __('Filter by attribute value', 'woocommerce-shippit'),
'description' => __('The product attribute value', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'text',
);
$fields['margin'] = array(
'title' => __('Margin'),
'class' => 'wc-enhanced-select',
'default' => 'no',
'description' => __('Add a margin to the quoted shipping amounts', 'woocommerce-shippit'),
'desc_tip' => true,
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes-percentage' => __('Yes - Percentage', 'woocommerce-shippit'),
'yes-fixed' => __('Yes - Fixed Dollar Amount', 'woocommerce-shippit'),
),
);
$fields['margin_amount'] = array(
'title' => __('Margin Amount', 'woocommerce-shippit'),
'description' => __('Please enter a margin amount, in either a whole dollar amount (ie: 5.50) or a percentage amount (ie: 5)', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'text',
);
return $fields;
}
/**
* Get products with id/name for a multiselect
*
* @return array An associative array of product ids and name
*/
private function _getProducts()
{
$productArgs = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$products = get_posts($productArgs);
$productOptions = array();
foreach ($products as $product) {
$productOptions[$product->ID] = __($product->post_title, 'woocommerce-shippit');
}
return $productOptions;
}
public function _getAttributes()
{
$productAttributes = array();
$attributeTaxonomies = wc_get_attribute_taxonomies();
foreach ($attributeTaxonomies as $tax) {
$productAttributes[$tax->attribute_name] = __($tax->attribute_name, 'woocommerce-shippit');
}
return $productAttributes;
}
}<file_sep>/includes/class-shippit-core.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Core
{
public $id = 'mamis_shippit';
/**
* Webhook Error Messages.
*/
const ERROR_API_KEY_MISSING = 'An API Key is required';
const ERROR_API_KEY_MISMATCH = 'The API Key provided does not match the configured API Key';
const ERROR_BAD_REQUEST = 'An invalid request was recieved';
const ERROR_ORDER_MISSING = 'The order id requested was not found or has a status that is not available for shipping';
const NOTICE_SHIPMENT_STATUS = 'Ignoring the order status update, as we only respond to ready_for_pickup state';
const ERROR_SHIPMENT_FAILED = 'The shipment record was not able to be created at this time, please try again.';
const SUCCESS_SHIPMENT_CREATED = 'The shipment record was created successfully.';
/**
* Instace of Mamis Shippit
*/
private static $instance;
/**
* Constructor.
*/
public function __construct()
{
if (!function_exists('is_plugin_active_for_network')) {
require_once(ABSPATH . '/wp-admin/includes/plugin.php');
}
// Check if WooCommerce is active
if (!class_exists('woocommerce')) {
return;
}
$this->s = new Mamis_Shippit_Settings();
$this->log = new Mamis_Shippit_Log();
$this->init();
}
/**
* Instance.
*
* An global instance of the class. Used to retrieve the instance
* to use on other files/plugins/themes.
*
* @since 1.0.0
*
* @return object Instance of the class.
*/
public static function instance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Initialize plugin parts.
*
* @since 1.0.0
*/
public function init()
{
add_action('syncOrders', array($this, 'syncOrders'));
// *****************
// Order Sync
// *****************
$order = new Mamis_Shippit_Order;
// If a new order is recieved, add pending sync
add_action('woocommerce_checkout_update_order_meta', array($order, 'addPendingSync'));
// If a order transitions into "processing", add pending sync
add_action('woocommerce_order_status_processing', array($order, 'addPendingSync'));
// If the order transition into "on-hold", remove pending sync
add_action('woocommerce_order_status_on-hold', array($order, 'removePendingSync'));
// *****************
// Authority To Leave
// *****************
// Add authority to leave field to checkout
add_action('woocommerce_after_order_notes', array($this, 'add_authority_to_leave'));
// Update the order meta with authority to leave value
add_action('woocommerce_checkout_update_order_meta', array($this, 'update_authority_to_leave_order_meta'));
// Display the authority to leave on the orders edit page
add_action('woocommerce_admin_order_data_after_shipping_address', 'authority_to_leave_display_admin_order_meta', 10, 1);
function authority_to_leave_display_admin_order_meta($order)
{
if (version_compare(WC()->version, '3.0.0') >= 0) {
$orderId = $order->get_id();
}
else {
$orderId = $order->id;
}
echo '<p><strong>'.__('Authority to leave').':</strong> ' . get_post_meta( $orderId, 'authority_to_leave', true ) . '</p>';
}
// Add the shippit settings tab functionality
add_action('woocommerce_settings_tabs_shippit_settings_tab', 'Mamis_Shippit_Settings::addFields');
add_action('woocommerce_update_options_shippit_settings_tab', 'Mamis_Shippit_Settings::updateSettings');
// Validate the api key when the setting is changed
add_action('update_option_wc_settings_shippit_api_key', array($this, 'after_api_key_update'), 10, 2);
add_action('update_option_wc_settings_shippit_fulfillment_enabled', array($this, 'after_fulfillment_enabled_update'), 10, 2);
//**********************/
// Webhook functionality
//**********************/
// create filter to get $_GET['shippit_api_key']
add_filter('query_vars', array($this, 'add_query_vars'), 0);
// handle API request if 'shippit_api_key' is set
add_action('parse_request', array($this, 'handle_webhook_request'), 0);
// create 'shippit/shipment_create' endpoint
add_action('init', array($this, 'add_webhook_endpoint'), 0);
// Add Send to Shippit order action
add_action('woocommerce_order_actions', array($this, 'shippit_add_order_meta_box_action') );
// Process Shippit send order action
add_action('woocommerce_order_action_shippit_order_action', array($order, 'sendOrder') );
// Add Bulk Send to Shippit orders action
add_action('bulk_actions-edit-shop_order', array($this, 'shippit_send_bulk_orders_action'), 20, 1);
// Process Shippit bulk orders send action
add_action('handle_bulk_actions-edit-shop_order', array($order, 'sendBulkOrders'), 10, 3 );
add_action('admin_notices', array($this, 'order_sync_notice') );
if (get_option('wc_settings_shippit_shippingcalculator_city_enabled') == 'yes') {
// Enable suburb/city field for Shipping calculator
add_filter('woocommerce_shipping_calculator_enable_city', '__return_true');
}
// Add the shipment meta boxes when viewing an order.
add_action('add_meta_boxes_shop_order', array($this, 'mamis_add_shipment_meta_box'));
// Add notification if the merchant has this shipping method still enabled
add_action('admin_notices', array($this, 'add_depreciation_notice'));
add_action('network_admin_notices', array($this, 'add_depreciation_notice'));
}
/**
* Add the Shippit Shipment Meta Box
*/
function mamis_add_shipment_meta_box()
{
$orderId = get_the_ID();
$shipmentData = get_post_meta($orderId, '_mamis_shippit_shipment', true);
if (empty($shipmentData)) {
return;
}
add_meta_box(
'mamis_shipment_fields',
__('Shipments - Powered by Shippit', 'woocommerce-shippit'),
array(
$this,
'mamis_add_shipment_meta_box_content'
),
'shop_order',
'side',
'high'
);
}
/**
* Render the Shippit Shipment Meta Box Content
*/
function mamis_add_shipment_meta_box_content($order)
{
$shipmentData = get_post_meta($order->ID, '_mamis_shippit_shipment', true);
$count = count($shipmentData);
$shipmentDetails = '';
$i = 1;
foreach ($shipmentData as $shipment) {
// Render the Courier Name
if (!empty($shipment['courier_name'])) {
$shipmentDetails .= '<strong>Courier:</strong> ';
$shipmentDetails .= '<span>' .$shipment['courier_name']. '</span>';
$shipmentDetails .= '<br/>';
}
// Render the Courier Job ID
if (!empty($shipment['booked_at'])) {
$shipmentDetails .= '<strong>Booked At:</strong> ';
$shipmentDetails .= '<span>' .$shipment['booked_at']. '</span>';
$shipmentDetails .= '<br/>';
}
// Render the Shippit Tracking Link
if (!empty($shipment['tracking_number'])) {
$shipmentDetails .= '<strong>Shippit Track #:</strong> ';
$shipmentDetails .= '<a target="_blank" href="'. $shipment['tracking_url']. '">';
$shipmentDetails .= $shipment['tracking_number'];
$shipmentDetails .= '</a><br/>';
}
if (!empty($shipment['courier_tracking_number'])) {
$shipmentDetails .= '<strong>Courier Track #:</strong> ';
$shipmentDetails .= $shipment['courier_tracking_number'];
$shipmentDetails .= '</a><br/>';
}
if ($i < $count) {
$shipmentDetails .= '<hr/>';
}
$i++;
}
echo $shipmentDetails;
}
/**
* Add a custom action to order actions select box
*
* @param array $actions order actions array to display
* @return array updated actions
*/
public function shippit_add_order_meta_box_action($actions)
{
// add "Send to Shippit" custom order action
$actions['shippit_order_action'] = __('Send to Shippit');
return $actions;
}
/**
* Add a custom bulk order action to order actions select box on orders list page
*
* @param array $actions order actions array to display
* @return array updated actions
*/
public function shippit_send_bulk_orders_action($actions)
{
// add "Send to Shippit" bulk action on the orders listing page
$actions['shippit_bulk_orders_action'] = __('Send to Shippit');
return $actions;
}
public function order_sync_notice()
{
if (!isset($_GET['shippit_sync'])) {
return;
}
echo '<div class="updated notice is-dismissable">'
. '<p>Orders have been scheduled to sync with Shippit - they will be synced shortly.</p>'
. '</div>';
}
public function add_webhook_endpoint()
{
add_rewrite_rule('^shippit/shipment_create/?([0-9]+)?/?', 'index.php?shippit_api_key=$matches[1],', 'top');
}
public function add_query_vars($vars)
{
$vars[] = 'shippit_api_key';
return $vars;
}
public function handle_webhook_request()
{
global $wp;
if (isset($wp->query_vars['shippit_api_key'])) {
$shipment = new Mamis_Shippit_Shipment();
$shipment->handle();
exit;
}
}
public function after_api_key_update($oldApiKey, $newApiKey)
{
$GLOBALS['SHIPPIT_API_KEY_UPDATED'] = true;
// Retrieve the environment setting from the POST request,
// as this may not yet be saved if it was changed in the same request
$environment = $_POST['wc_settings_shippit_environment'];
$isFulfillmentEnabled = $_POST['wc_settings_shippit_fulfillment_enabled'];
$isValidApiKey = $this->validate_apikey($newApiKey, $environment);
$this->show_api_notice($isValidApiKey);
if (!$isValidApiKey) {
return;
}
$this->register_shopping_cart_name($newApiKey, $environment);
$registerWebhookResult = $this->update_webhook($isFulfillmentEnabled, $newApiKey, $environment);
$this->show_webhook_notice($registerWebhookResult);
}
public function after_fulfillment_enabled_update($oldFulfillmentEnabled, $newFulfillmentEnabled)
{
// If the api key was updated in this request, return early
// as we don't need to update the webhook again
if (isset($GLOBALS['SHIPPIT_API_KEY_UPDATED'])) {
return;
}
// Retrieve the environment setting from the POST request,
// as this may not yet be saved if it was changed in the same request
$apiKey = $_POST['wc_settings_shippit_api_key'];
$environment = $_POST['wc_settings_shippit_environment'];
$isFulfillmentEnabled = $_POST['wc_settings_shippit_fulfillment_enabled'];
$isValidApiKey = $this->validate_apikey($apiKey, $environment);
if (!$isValidApiKey) {
// Trigger a failied webhook notice
$this->show_webhook_notice(false);
return;
}
$this->register_shopping_cart_name($apiKey, $environment);
$registerWebhookResult = $this->update_webhook($isFulfillmentEnabled, $apiKey, $environment);
$this->show_webhook_notice($registerWebhookResult);
}
/**
* Update the webhook url with Shippit
*
* @param string $apiKey The api key to be validated
* @param string $environment The enviornment in which the api key is validated against
* @return bool
*/
private function update_webhook($isEnabled, $apiKey = null, $environment = null)
{
$this->api = new Mamis_Shippit_Api($apiKey, $environment);
if ($isEnabled) {
$webhookUrl = sprintf(
'%s/shippit/shipment_create?shippit_api_key=%s',
get_site_url(),
$apiKey
);
}
else {
$webhookUrl = null;
}
$requestData = array(
'webhook_url' => $webhookUrl
);
$this->log->add(
'Webhook',
'Registering Webhook Url'
);
try {
$apiResponse = $this->api->putMerchant($requestData);
if ($apiResponse
&& !property_exists($apiResponse, 'error')
&& property_exists($apiResponse, 'response')) {
$this->log->add(
'Webhook',
'Webhook Registration Successful'
);
return true;
}
else {
$this->log->add(
'Webhook',
'An error occurred while attempting to register the webhook'
);
return false;
}
}
catch (Exception $e) {
$this->log->exception($e);
}
return false;
}
/**
* Registers the webhook url with Shippit
*
* @param string $apiKey The api key to be validated
* @param string $environment The enviornment in which the api key is validated against
* @return bool
*/
private function register_shopping_cart_name($apiKey = null, $environment = null)
{
$this->api = new Mamis_Shippit_Api($apiKey, $environment);
$requestData = array(
'shipping_cart_method_name' => 'woocommerce'
);
$this->log->add('Registering shopping cart name', '', $requestData);
try {
$apiResponse = $this->api->putMerchant($requestData);
if (empty($apiResponse)
|| property_exists($apiResponse, 'error')) {
$this->show_cart_registration_notice();
}
}
catch (Exception $e) {
$this->log->exception($e);
$this->show_cart_registration_notice();
}
}
/**
* Determines if the api key is valid
*
* @param string $apiKey The api key to be validated
* @param string $environment The enviornment in which the api key is validated against
* @return bool
*/
private function validate_apikey($apiKey = null, $environment = null)
{
$this->api = new Mamis_Shippit_Api($apiKey, $environment);
try {
$apiResponse = $this->api->getMerchant();
if (property_exists($apiResponse, 'error')) {
$this->log->add(
'Validating API Key Result',
'API Key is INVALID'
);
return false;
}
if (property_exists($apiResponse, 'response')) {
$this->log->add(
'Validating API Key Result',
'API Key is VALID'
);
return true;
}
}
catch (Exception $e) {
$this->log->exception($e);
}
return false;
}
public function show_api_notice($isValid)
{
if (!$isValid) {
echo '<div class="error notice">'
. '<p>An invalid Shippit API key has been detected, please check the api key and environment and try again.</p>'
. '</div>';
}
else {
echo '<div class="updated notice">'
. '<p>Your Shippit API Key has been validated and is correct</p>'
. '</div>';
}
}
public function show_webhook_notice($isValid)
{
if (!$isValid) {
echo '<div class="error notice">'
. '<p>Shippit Webhook could not be updated</p>'
. '</div>';
}
else {
echo '<div class="updated notice">'
. '<p>Shippit Webhook has now been updated</p>'
. '</div>';
}
}
public function show_cart_registration_notice()
{
echo '<div class="error notice">'
. '<p>The request to update the shopping cart integration name failed - please try again.</p>'
. '</div>';
}
/**
* Add the shippit order sync to the cron scheduler
*/
public static function order_sync_schedule()
{
if (!wp_next_scheduled('syncOrders')) {
wp_schedule_event(
current_time('timestamp', true),
'hourly',
'syncOrders'
);
}
}
/**
* Remove the shippit order sync to the cron scheduler
*/
public static function order_sync_deschedule()
{
wp_clear_scheduled_hook('syncOrders');
}
public function syncOrders()
{
if (class_exists('WC_Order')) {
$orders = new Mamis_Shippit_Order();
$orders->syncOrders();
}
}
public function add_authority_to_leave($checkout)
{
if (get_option('wc_settings_shippit_atl_enabled') != 'yes') {
return;
}
echo '<div id="authority_to_leave"><h2>' . __('Authority to leave') . '</h2>';
woocommerce_form_field( 'authority_to_leave', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'options' => array(
'No' => 'No',
'Yes' => 'Yes'
),
),
$checkout->get_value( 'authority_to_leave' ));
echo '</div>';
}
public function update_authority_to_leave_order_meta($order_id)
{
if (!empty($_POST['authority_to_leave'])) {
update_post_meta(
$order_id,
'authority_to_leave',
sanitize_text_field($_POST['authority_to_leave'])
);
}
}
/**
* Add a depreciation notice for merchants that have the legacy shipping method active and in use
*
* @return void
*/
public function add_depreciation_notice()
{
$legacyOptions = get_option('woocommerce_mamis_shippit_legacy_settings');
// If there are no options present, we don't require the depreciation notice
if (empty($legacyOptions)) {
return;
}
// If the `enabled` configuration option is not present, or not yes, we don't require the depreciation notice
if (!isset($legacyOptions['enabled']) || $legacyOptions['enabled'] !== 'yes') {
return;
}
// Render the depreciation notice
include_once __DIR__ . '/../views/notices/shippit-legacy-depreciation.php';
}
}
<file_sep>/includes/class-shippit-api.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Api
{
const API_ENDPOINT_LIVE = 'https://www.shippit.com/api/3';
const API_ENDPOINT_STAGING = 'https://staging.shippit.com/api/3';
const API_TIMEOUT = 30;
private $apiKey = null;
public $debug = false;
/**
* Create a Shippit API Client
*
* @param string $apiKey (Optional) The API key to be used for requests
* @param string $environment (Optional) The environment to be used for requests
* @param bool $debug (Optional) The debug mode of the client
*/
public function __construct($apiKey = null, $environment = null, $debug = null)
{
$this->settings = new Mamis_Shippit_Settings();
$this->log = new Mamis_Shippit_Log();
$this->apiKey = (empty($apiKey) ? get_option('wc_settings_shippit_api_key') : $apiKey);
$this->environment = (empty($environment) ? get_option('wc_settings_shippit_environment') : $environment);
$this->debug = (empty($debug) ? get_option('wc_settings_shippit_debug') : $debug);
}
private function getApiKey()
{
return $this->apiKey;
}
public function setApiKey($apiKey)
{
return $this->apiKey = $apiKey;
}
public function setEnvironment($environment)
{
return $this->environment = $environment;
}
public function getApiUrl($path)
{
if ( $this->environment == 'sandbox' ) {
return self::API_ENDPOINT_STAGING . '/' . $path;
}
else {
return self::API_ENDPOINT_LIVE . '/' . $path;
}
}
public function getApiArgs($requestData, $requestMethod)
{
$apiArgs = array(
'blocking' => true,
'method' => $requestMethod,
'timeout' => self::API_TIMEOUT,
'user-agent' => $this->getUserAgent(),
'headers' => array(
'content-type' => 'application/json',
'Authorization' => sprintf(
'Bearer %s',
$this->getApiKey()
),
),
);
if (!empty($requestData)) {
$apiArgs['body'] = json_encode($requestData);
}
return $apiArgs;
}
public function call($uri, $requestData, $requestMethod = 'POST', $exceptionOnResponseError = true)
{
$url = $this->getApiUrl($uri);
$args = $this->getApiArgs($requestData, $requestMethod);
$this->log->add(
'SHIPPIT - API REQUEST',
$uri,
array(
'url' => $url,
'requestData' => $requestData
)
);
try {
$response = wp_remote_request(
$url,
$args
);
$responseCode = wp_remote_retrieve_response_code($response);
if ($exceptionOnResponseError) {
if ($responseCode < 200 ||
$responseCode > 300) {
throw new Exception('An API Request Error Occured');
}
}
}
catch (Exception $e) {
$metaData = array(
'url' => $url,
'requestData' => $requestData,
'responseData' => wp_remote_retrieve_body($response)
);
$this->log->exception($e, $metaData);
$this->log->add(
'SHIPPIT - API REQUEST ERROR',
$uri,
$metaData,
'error'
);
return false;
}
$jsonResponseData = wp_remote_retrieve_body($response);
$responseData = json_decode($jsonResponseData);
$this->log->add(
'SHIPPIT - API RESPONSE',
$uri,
array(
'url' => $url,
'requestData' => $requestData,
'responseData' => $responseData
)
);
return $responseData;
}
/**
* Retrieves the user agent for outbound API calls
*/
public function getUserAgent()
{
return sprintf(
'Shippit_WooCommerce/%s WooCommerce/%s PHP/%s',
MAMIS_SHIPPIT_VERSION,
WC()->version,
phpversion()
);
}
public function getQuote($quoteData)
{
$requestData = array(
'quote' => $quoteData
);
$quote = $this->call('quotes', $requestData);
if (!$quote) {
return false;
}
return $quote->response;
}
public function sendOrder($orderData)
{
$requestData = array(
'order' => $orderData
);
$order = $this->call('orders', $requestData, 'POST', false);
if (!$order) {
return false;
}
return $order->response;
}
public function getMerchant()
{
return $this->call('merchant', null, 'GET', false);
}
public function putMerchant($merchantData)
{
$requestData = array(
'merchant' => $merchantData
);
return $this->call('merchant', $requestData, 'PUT');
}
}<file_sep>/includes/class-shippit-settings.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Settings
{
/**
* Add a new settings tab to the WooCommerce settings tabs array.
*
* @param array $settingsTab Array of WooCommerce setting tabs & their labels, excluding the Subscription tab.
* @return array $settingsTab Array of WooCommerce setting tabs & their labels, including the Subscription tab.
*/
public static function addSettingsTab($settingsTab)
{
$settingsTab['shippit_settings_tab'] = __('Shippit', 'woocommerce-shippit');
return $settingsTab;
}
/**
* Uses the WooCommerce admin fields API to output settings via the @see woocommerce_admin_fields() function.
*
* @uses woocommerce_admin_fields()
*/
public static function addFields()
{
woocommerce_admin_fields(self::getFields());
// include custom script on shippit settings page
wp_enqueue_script('shippit-script');
}
/**
* Uses the WooCommerce options API to save settings via the @see woocommerce_update_options() function.
*
* @uses woocommerce_update_options()
*/
public static function updateSettings()
{
woocommerce_update_options(self::getFields());
}
/**
* Get all the settings for this plugin for @see woocommerce_admin_fields() function.
*
* @return array Array of settings for @see woocommerce_admin_fields() function.
*/
public static function getFields()
{
$shippingMethodOptions = self::getShippingMethodOptions();
$settings = array(
'title_general' => array(
'id' => 'shippit-settings-general-title',
'name' => __( 'General Settings', 'woocommerce-shippit' ),
'type' => 'title',
'desc' => 'General Settings allow you to connect your WooCommerce store with Shippit.',
'desc_tip' => true,
),
'enabled' => array(
'id' => 'wc_settings_shippit_enabled',
'title' => __('Enabled', 'woocommerce-shippit'),
'desc' => 'Determines whether live quoting, order sync and fulfillment sync are enabled and active.',
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'no',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
),
),
'api_key' => array(
'id' => 'wc_settings_shippit_api_key',
'title' => __('API Key', 'woocommerce-shippit'),
'desc' => 'Your Shippit API Key',
'desc_tip' => true,
'default' => '',
'name' => 'api_key',
'type' => 'text',
'css' => 'min-width: 350px; border-radius: 3px;',
),
'debug' => array(
'id' => 'wc_settings_shippit_debug',
'title' => __('Debug Mode', 'woocommerce-shippit'),
'desc' => __('If debug mode is enabled, all events and requests are logged to the debug log file', 'woocommerce-shippit'),
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'no',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
),
),
'environment' => array(
'id' => 'wc_settings_shippit_environment',
'title' => __('Environment', 'woocommerce-shippit'),
'desc' => __('The environment to connect to for all quotes and order sync operations', 'woocommerce-shippit'),
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'live',
'type' => 'select',
'options' => array(
'sandbox' => __('Sandbox', 'woocommerce-shippit'),
'live' => __('Live', 'woocommerce-shippit'),
),
),
'section_general_end' => array(
'id' => 'shippit-settings-general-end',
'type' => 'sectionend',
),
'title_cart_checkout' => array(
'id' => 'shippit-settings-checkout-title',
'name' => __( 'Cart & Checkout Options', 'woocommerce-shippit' ),
'type' => 'title',
'desc' => 'Show/hide additional fields in the cart & checkout areas.',
'desc_tip' => true,
),
'shippingcalculator_city_enabled' => array(
'id' => 'wc_settings_shippit_shippingcalculator_city_enabled',
'title' => __('Display City Field in Shipping Estimator', 'woocommerce-shippit'),
'desc' => 'Using Shippit Live Quotes? Ensure this is enabled so that we can retrieve quotes for shipping estimations from the Shipping Calculator.',
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'yes',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
),
),
'atl_enabled' => array(
'id' => 'wc_settings_shippit_atl_enabled',
'title' => __('Display Authority to Leave', 'woocommerce-shippit'),
'desc' => 'Determines whether to show Auhtority to Leave field in the checkout or not.',
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'yes',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
),
),
'section_cart_checkout_end' => array(
'id' => 'shippit-settings-cart-checkout-end',
'type' => 'sectionend',
),
'title_order' => array(
'id' => 'shippit-settings-orders-title',
'name' => __( 'Order Sync Settings', 'woocommerce-shippit' ),
'type' => 'title',
'desc' => 'Order Sync Settings refers to your preferences for when an order should be sent to Shippit and the type of Shipping Service to utilise.',
),
'auto_sync_orders' => array(
'id' => 'wc_settings_shippit_auto_sync_orders',
'title' => __('Auto-Sync New Orders', 'woocommerce-shippit'),
'desc' => __('Determines whether to automatically sync all orders, or only Shippit Quoted or Mapped orders to Shippit', 'woocommerce-shippit'),
'desc_tip' => true,
'class' => 'wc-enhanced-select',
'default' => 'no',
'type' => 'select',
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'all' => __('Yes - Auto-sync all new orders', 'woocommerce-shippit'),
'all_shippit' => __('Yes - Auto-sync only orders with Shippit Shipping Methods', 'woocommerce-shippit'),
),
),
'standard_shipping_methods' => array(
'id' => 'wc_settings_shippit_standard_shipping_methods',
'title' => __('Standard Shipping Methods', 'woocommerce-shippit'),
'desc' => __('The third party shipping methods that should be allocated to a "Standard" Shippit Service', 'woocommerce-shippit', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'multiselect',
'options' => $shippingMethodOptions,
'class' => 'wc-enhanced-select',
),
'express_shipping_methods' => array(
'id' => 'wc_settings_shippit_express_shipping_methods',
'title' => __('Express Shipping Methods', 'woocommerce-shippit'),
'desc' => __('The third party shipping methods that should be allocated to a "Express" Shippit Service', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'multiselect',
'options' => $shippingMethodOptions,
'class' => 'wc-enhanced-select',
),
'clickandcollect_shipping_methods' => array(
'id' => 'wc_settings_shippit_clickandcollect_shipping_methods',
'title' => __('Click & Collect Shipping Methods', 'woocommerce-shippit'),
'desc' => __('The third party shipping methods that should be allocated to a "Click and Collect" Shippit service level', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'multiselect',
'options' => $shippingMethodOptions,
'class' => 'wc-enhanced-select',
),
'plainlabel_shipping_methods' => array(
'id' => 'wc_settings_shippit_plainlabel_shipping_methods',
'title' => __('Plain Label Shipping Methods', 'woocommerce-shippit'),
'desc' => __('The third party shipping methods that should be allocated to the "Plain Label" Shippit Service', 'woocommerce-shippit', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'multiselect',
'options' => $shippingMethodOptions,
'class' => 'wc-enhanced-select',
),
'section_order_end' => array(
'id' => 'shippit-settings-order-end',
'type' => 'sectionend',
),
'title_order_items' => array(
'id' => 'shippit-settings-items-title',
'name' => __( 'Item Sync Settings', 'woocommerce-shippit' ),
'type' => 'title',
),
'tariff_code_attribute' => array(
'id' => 'wc_settings_shippit_tariff_code_attribute',
'title' => __('Tariff Code Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Attribute to be used for Tariff Code information sent to Shippit.', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'select',
'options' => self::getProductAttributes(),
'class' => 'wc-enhanced-select',
),
'tariff_code_custom_attribute' => array(
'id' => 'wc_settings_shippit_tariff_code_custom_attribute',
'title' => __('Tariff Code Custom Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Custom Attribute to be used for Tariff Code information sent to Shippit', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'name' => 'tariff_code_custom_attribute',
'type' => 'text',
),
'origin_country_code_attribute' => array(
'id' => 'wc_settings_shippit_origin_country_code_attribute',
'title' => __('Origin Country Code Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Attribute to be used for Origin Country Code information sent to Shippit.', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'select',
'options' => self::getProductAttributes(),
'class' => 'wc-enhanced-select',
),
'origin_country_code_custom_attribute' => array(
'id' => 'wc_settings_shippit_origin_country_code_custom_attribute',
'title' => __('Origin Country Code Custom Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Custom Attribute to be used for Origin Country Code information sent to Shippit.', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'name' => 'origin_country_code_custom_attribute',
'type' => 'text',
),
'dangerous_goods_code_attribute' => array(
'id' => 'wc_settings_shippit_dangerous_goods_code_attribute',
'title' => __('Dangerous Goods Code Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Attribute to be used for Dangerous Goods Code information sent to Shippit.', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'select',
'options' => self::getProductAttributes(),
'class' => 'wc-enhanced-select',
),
'dangerous_goods_code_custom_attribute' => array(
'id' => 'wc_settings_shippit_dangerous_goods_code_custom_attribute',
'title' => __('Dangerous Goods Code Custom Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Custom Attribute to be used for Dangerous Goods Code information sent to Shippit.', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'name' => 'dangerous_goods_code_custom_attribute',
'type' => 'text',
),
'dangerous_goods_text_attribute' => array(
'id' => 'wc_settings_shippit_dangerous_goods_text_attribute',
'title' => __('Dangerous Goods Text Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Attribute to be used for Dangerous Goods Text information sent to Shippit.', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'type' => 'select',
'options' => self::getProductAttributes(),
'class' => 'wc-enhanced-select',
),
'dangerous_goods_text_custom_attribute' => array(
'id' => 'wc_settings_shippit_dangerous_goods_text_custom_attribute',
'title' => __('Dangerous Goods Text Custom Attribute', 'woocommerce-shippit'),
'desc' => __('The Product Custom Attribute to be used for Dangerous Goods Text information sent to Shippit.', 'woocommerce-shippit'),
'desc_tip' => true,
'default' => '',
'name' => 'dangerous_goods_text_custom_attribute',
'type' => 'text',
),
'section_order_items_end' => array(
'id' => 'shippit-settings-order-items-end',
'type' => 'sectionend',
),
'title_fulfillment' => array(
'id' => 'shippit-settings-fulfillment-title',
'name' => __( 'Fulfillment Settings', 'woocommerce-shippit' ),
'type' => 'title',
),
'fulfillment_enabled' => array(
'id' => 'wc_settings_shippit_fulfillment_enabled',
'title' => __('Enabled', 'woocommerce-shippit'),
'class' => 'wc-enhanced-select',
'default' => 'yes',
'type' => 'select',
'desc' => 'Enable this setting to mark orders as fulfilled in WooCommerce. With this setting enabled, Shippit will update all tracking information against the order as it is fulfilled.',
'desc_tip' => true,
'options' => array(
'no' => __('No', 'woocommerce-shippit'),
'yes' => __('Yes', 'woocommerce-shippit'),
)
),
'fulfillment_tracking_reference' => array(
'id' => 'wc_settings_shippit_fulfillment_tracking_reference',
'title' => __('Tracking Reference', 'woocommerce-shippit'),
'class' => 'wc-enhanced-select',
'default' => 'shippit_tracking_reference',
'type' => 'select',
'desc' => 'The tracking reference that you wish to capture from Shippit and communicate with customers.',
'desc_tip' => true,
'options' => array(
'shippit_tracking_reference' => __('Shippit Tracking Reference', 'woocommerce-shippit'),
'courier_tracking_reference' => __('Courier Tracking Reference', 'woocommerce-shippit'),
)
),
'section_end' => array(
'id' => 'shippit-settings-fulfillment-end',
'type' => 'sectionend',
),
);
return apply_filters('wc_settings_shippit_settings', $settings);
}
/**
* Get WooCommerce Product Attributes
*
* @return array
*/
public static function getProductAttributes()
{
$productAttributes = array();
$placeHolder = array('' => '-- Please Select --');
$attributeTaxonomies = wc_get_attribute_taxonomies();
if (empty($attributeTaxonomies)) {
return $placeHolder;
}
foreach ($attributeTaxonomies as $tax) {
$productAttributes[$tax->attribute_name] = __($tax->attribute_label, 'woocommerce-shippit');
}
// Add custom attribute as option
$productAttributes['_custom'] = 'Use custom product attribute';
return array_merge($placeHolder, $productAttributes);
}
/**
* Get the shipping method options that should
* be available for shipping method mapping
*
* @return array
*/
public static function getShippingMethodOptions()
{
// If we have a WooCommerce installation
// with Shipping Zones Support
if (class_exists('WC_Shipping_Zones')) {
$shippingMethodsWithZones = self::getShippingMethodsWithZones();
$shippingMethodsWithoutZones = self::getShippingMethodsWithoutZones();
$shippingMethodsOptions = array_merge($shippingMethodsWithZones, $shippingMethodsWithoutZones);
}
// Otherwise, fallback to legacy methods only display
else {
$shippingMethodsOptions = self::getShippingMethodsLegacy();
}
return $shippingMethodsOptions;
}
/**
* Get the shipping method options with zone details
*
* @return array
*/
protected static function getShippingMethodsWithZones()
{
$shippingMethodOptions = array();
$zones = WC_Shipping_Zones::get_zones();
foreach ($zones as $zone) {
$shippingMethods = $zone['shipping_methods'];
foreach ($shippingMethods as $shippingMethod) {
if ($shippingMethod->id == 'mamis_shippit') {
continue;
}
$shippingMethodKey = $shippingMethod->id . ':' . $shippingMethod->instance_id;
$shippingMethodLabel = (property_exists($shippingMethod, 'title') ? $shippingMethod->title : $shippingMethod->method_title);
$shippingMethodOptions[$shippingMethodKey] = sprintf(
'%s Zone — %s',
$zone['zone_name'],
$shippingMethodLabel
);
}
}
return $shippingMethodOptions;
}
/**
* Get the shipping method options without zone details
* - used to support legacy methods used in a zone-supported environment
*
* @return array
*/
protected static function getShippingMethodsWithoutZones()
{
$shippingMethodOptions = array();
$shippingMethods = WC_Shipping_Zones::get_zone_by()->get_shipping_methods();
foreach ($shippingMethods as $shippingMethod) {
if ($shippingMethod->id == 'mamis_shippit' || $shippingMethod->id == 'mamis_shippit_legacy') {
continue;
}
$shippingMethodKey = $shippingMethod->id. ':' . $shippingMethod->instance_id;
$shippingMethodLabel = (property_exists($shippingMethod, 'title') ? $shippingMethod->title : $shippingMethod->method_title);
$shippingMethodOptions[$shippingMethodKey] = sprintf(
'Default Zone - %s',
$shippingMethodLabel
);
}
return $shippingMethodOptions;
}
/**
* Get the shipping method options using the legacy functionality
*
* @return array
*/
protected static function getShippingMethodsLegacy()
{
$shippingMethodOptions = array();
$shippingMethods = WC()->shipping()->get_shipping_methods();
foreach ($shippingMethods as $shippingMethod) {
if ($shippingMethod->id == 'mamis_shippit' || $shippingMethod->id == 'mamis_shippit_legacy') {
continue;
}
$shippingMethodKey = $shippingMethod->id;
$shippingMethodLabel = (property_exists($shippingMethod, 'method_title') ? $shippingMethod->method_title : $shippingMethod->title);
$shippingMethodOptions[$shippingMethodKey] = sprintf(
'%s',
$shippingMethodLabel
);
}
return $shippingMethodOptions;
}
}
<file_sep>/includes/class-shippit-order.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2016 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
class Mamis_Shippit_Order
{
private $api;
private $s;
private $helper;
private $woocommerce;
const CARRIER_CODE = 'mamis_shippit';
/**
* Constructor.
*/
public function __construct()
{
$this->api = new Mamis_Shippit_Api();
$this->s = new Mamis_Shippit_Settings();
$this->helper = new Mamis_Shippit_Helper();
$this->woocommerce = $GLOBALS['woocommerce'];
}
/**
* Remove a pending sync
*
* Called when an order moves out from "processing"
* status to a hold status
*
* @param int $order_id The Order Id
* @return boolean True or false
*/
public function removePendingSync($orderId)
{
$order = new WC_Order($orderId);
if (get_post_meta($orderId, '_mamis_shippit_sync', true) == 'false') {
delete_post_meta($orderId, '_mamis_shippit_sync');
}
}
/**
* Add a pending sync
*
* @param int $orderId The Order Id
* @return boolean True or false
*/
public function addPendingSync($orderId)
{
$isEnabled = get_option('wc_settings_shippit_enabled');
$autoSyncOrders = get_option('wc_settings_shippit_auto_sync_orders');
if ($isEnabled != 'yes' || $autoSyncOrders == 'no') {
return;
}
if (get_post_meta($orderId, '_mamis_shippit_sync', true) == 'true') {
return;
}
// Get the orders_item_id meta with key shipping
$order = new WC_Order($orderId);
// Only add the order as pending when it's in a "processing" status
if (!$order->has_status('processing')) {
return;
}
// If we are only syncing shippit quoted orders, ensure it's a shippit quoted order
if ($autoSyncOrders == 'all_shippit' && !$this->isShippitShippingMethod($order)) {
return;
}
add_post_meta($orderId, '_mamis_shippit_sync', 'false', true);
// attempt to sync the order now
$this->syncOrder($orderId);
}
protected function isShippitShippingMethod($order)
{
$shippingMethods = $order->get_shipping_methods();
$standardShippingMethods = get_option('wc_settings_shippit_standard_shipping_methods');
$expressShippingMethods = get_option('wc_settings_shippit_express_shipping_methods');
$clickandcollectShippingMethods = get_option('wc_settings_shippit_clickandcollect_shipping_methods');
$plainlabelShippingMethods = get_option('wc_settings_shippit_plainlabel_shipping_methods');
foreach ($shippingMethods as $shippingMethod) {
// Since Woocommerce v3.4.0, the instance_id is saved in a seperate property of the shipping method
// To add support for v3.4.0, we'll append the instance_id, as this is how we store a mapping in Shippit
if (isset($shippingMethod['instance_id']) && !empty($shippingMethod['instance_id'])) {
$shippingMethodId = sprintf(
'%s:%s',
$shippingMethod['method_id'],
$shippingMethod['instance_id']
);
}
else {
$shippingMethodId = $shippingMethod['method_id'];
}
if (!empty($standardShippingMethods)
&& in_array($shippingMethodId, $standardShippingMethods)) {
return true;
}
if (!empty($expressShippingMethods)
&& in_array($shippingMethodId, $expressShippingMethods)) {
return true;
}
if (!empty($clickandcollectShippingMethods)
&& in_array($shippingMethodId, $clickandcollectShippingMethods)) {
return true;
}
if (!empty($plainlabelShippingMethods)
&& in_array($shippingMethodId, $plainlabelShippingMethods)) {
return true;
}
// Check if the shipping method chosen is a shippit method
if (stripos($shippingMethod['method_id'], 'Mamis_Shippit') !== FALSE) {
return true;
}
}
return false;
}
protected function getShippingMethodId($order)
{
$shippingMethods = $order->get_shipping_methods();
$standardShippingMethods = get_option('wc_settings_shippit_standard_shipping_methods');
$expressShippingMethods = get_option('wc_settings_shippit_express_shipping_methods');
$clickandcollectShippingMethods = get_option('wc_settings_shippit_clickandcollect_shipping_methods');
$plainlabelShippingMethods = get_option('wc_settings_shippit_plainlabel_shipping_methods');
foreach ($shippingMethods as $shippingMethod) {
// Since Woocommerce v3.4.0, the instance_id is saved in a seperate property of the shipping method
// To add support for v3.4.0, we'll append the instance_id, as this is how we store a mapping in Shippit
if (isset($shippingMethod['instance_id']) && !empty($shippingMethod['instance_id'])) {
$shippingMethodId = sprintf(
'%s:%s',
$shippingMethod['method_id'],
$shippingMethod['instance_id']
);
}
else {
$shippingMethodId = $shippingMethod['method_id'];
}
// Check if the shipping method chosen is Mamis_Shippit
if (stripos($shippingMethodId, 'Mamis_Shippit') !== FALSE) {
return $shippingMethodId;
}
// If we have anything after shipping_method:instance_id
// then ignore it
if (substr_count($shippingMethodId, ':') > 1) {
$firstOccurence = strrpos($shippingMethodId, ':');
$secondOccurence = strpos($shippingMethodId, ':', $firstOccurence);
$shippingMethodId = substr($shippingMethodId, 0, $secondOccurence);
}
// Check if shipping method is mapped to standard
if (!empty($standardShippingMethods)
&& in_array($shippingMethodId, $standardShippingMethods)) {
return 'standard';
}
// Check if shipping method is mapped to express
if (!empty($expressShippingMethods)
&& in_array($shippingMethodId, $expressShippingMethods)) {
return 'express';
}
// Check if shipping method is mapped to click and collect
if (!empty($clickandcollectShippingMethods)
&& in_array($shippingMethodId, $clickandcollectShippingMethods)) {
return 'click_and_collect';
}
// Check if shipping method is mapped to plain label
if (!empty($plainlabelShippingMethods)
&& in_array($shippingMethodId, $plainlabelShippingMethods)) {
return 'plainlabel';
}
}
return false;
}
/**
* Sync all pending orders
*
* Adds _mamis_shippit_sync meta key value to all orders
* that have been scheduled for sync with shippit
* @return [type] [description]
*/
public function syncOrders()
{
global $woocommerce;
$orderPostArg = array(
'post_status' => 'wc-processing',
'post_type' => 'shop_order',
'meta_query' => array(
array(
'key' => '_mamis_shippit_sync',
'value' => 'false',
'compare' => '='
)
),
);
// Get all woocommerce orders that are processing
$orderPosts = get_posts($orderPostArg);
foreach ($orderPosts as $orderPost) {
$this->syncOrder($orderPost->ID);
}
}
/**
* Manual action - Send order to shippit
*
* @param object $order order to be send
*/
public function sendOrder($order)
{
if (version_compare($this->woocommerce->version, '2.6.0', '<=')) {
$orderId = $order->id;
}
else {
$orderId = $order->get_id();
}
update_post_meta($orderId, '_mamis_shippit_sync', 'false');
// attempt to sync the order now
$this->syncOrder($orderId);
}
/**
* Manual action - Send bulk orders to shippit
*
* @param string $redirectTo return url
* @param string $action selected bulk order action
*/
public function sendBulkOrders($redirectTo, $action, $orderIds)
{
// only process when the action is a shippit bulk-ordders action
if ($action != 'shippit_bulk_orders_action') {
return $redirectTo;
}
foreach ($orderIds as $orderId) {
// Mark Shippit sync as false as for this manual action
// we want to schedule orders for sync even if synced already
update_post_meta($orderId, '_mamis_shippit_sync', 'false');
}
// Create the schedule for the orders to sync
wp_schedule_single_event(
current_time('timestamp', true),
'syncOrders'
);
return add_query_arg(array('shippit_sync' => '2'), $redirectTo);
}
public function syncOrder($orderId)
{
// Get the orders_item_id meta with key shipping
$order = new WC_Order($orderId);
$orderItems = $order->get_items();
// $shippingMethodId = $this->getShippingMethodId($order);
// if WooCommerce version is equal or less than 2.6 then use
// different data mapper for it
if (version_compare($this->woocommerce->version, '2.6.0', '<=')) {
$orderData = (new Mamis_Shippit_Data_Mapper_Order_V26())->__invoke($order)->toArray();
}
else {
$orderData = (new Mamis_Shippit_Data_Mapper_Order())->__invoke($order)->toArray();
}
// If there are no order items, return early
if (count($orderItems) == 0) {
update_post_meta($orderId, '_mamis_shippit_sync', 'true', 'false');
return;
}
// Send the API request
$apiResponse = $this->api->sendOrder($orderData);
if ($apiResponse && $apiResponse->tracking_number) {
update_post_meta($orderId, '_mamis_shippit_sync', 'true', 'false');
$orderComment = 'Order Synced with Shippit. Tracking number: ' . $apiResponse->tracking_number . '.';
$order->add_order_note($orderComment, 0);
}
else {
$orderComment = 'Order Failed to sync with Shippit.';
if ($apiResponse && isset($apiResponse->messages)) {
$messages = $apiResponse->messages;
foreach ($messages as $field => $message) {
$orderComment .= sprintf(
'%c%s - %s',
10, // ASCII Code for NewLine
$field,
implode(', ', $message)
);
}
}
elseif ($apiResponse && isset($apiResponse->error) && isset($apiResponse->error_description)) {
$orderComment .= sprintf(
'%c%s - %s',
10, // ASCII Code for NewLine
$apiResponse->error,
$apiResponse->error_description
);
}
$order->add_order_note($orderComment, 0);
}
}
}
<file_sep>/includes/class-shippit-object.php
<?php
/**
* Mamis.IT
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is available through the world-wide-web at this URL:
* http://www.mamis.com.au/licencing
*
* @category Mamis
* @copyright Copyright (c) 2019 by Mamis.IT Pty Ltd (http://www.mamis.com.au)
* @author <NAME> <<EMAIL>>
* @license http://www.mamis.com.au/licencing
*/
// Contents of this class are based on string
// and array access implementations from the
// Laravel Framework
// @see https://github.com/laravel/framework
class Mamis_Shippit_Object implements ArrayAccess
{
/**
* Object attributes
*
* @var array
*/
protected $_data = array();
/**
* The cache of snake-cased words.
*
* @var array
*/
protected static $snakeCache = [];
/**
* The cache of studly-cased words.
*
* @var array
*/
protected static $studlyCache = [];
/**
* Attribute data handling wrapper
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
$methodType = substr($method, 0, 3);
$methodName = $methodType . 'Data';
// If the method does not exist locally, throw an exception
if (!method_exists($this, $methodName)) {
throw new Exception(
sprintf(
'Invalid method %s::%s (%s)',
get_class($this),
$method,
print_r($parameters, 1)
)
);
}
$attribute = substr($method, 3);
// Retrieve the data key for this attribute
$key = $this->snake($attribute);
if ($methodType == 'set') {
// Retrieve the data value for the attribute
$value = (isset($parameters[0]) ? $parameters[0]: null);
return $this->{$methodName}($key, $value);
}
else {
return $this->{$methodName}($key);
}
}
/**
* Convert object attributes to JSON
*
* @param array $attributes Array of required attributes
* @return string
*/
public function __toJson(array $attributes = array())
{
$arrayData = $this->toArray($attributes);
return json_encode($arrayData);
}
/**
* Public wrapper for __toJson
*
* @param array $attributes
* @return string
*/
public function toJson(array $attributes = array())
{
return $this->__toJson($attributes);
}
/**
* Convert object attributes to array
*
* @param array $arrAttributes array of required attributes
* @return array
*/
public function __toArray(array $attributes = array())
{
if (empty($attributes)) {
return $this->_data;
}
$arrayData = array();
foreach ($attributes as $attribute) {
if (isset($this->_data[$attribute])) {
$arrayData[$attribute] = $this->_data[$attribute];
}
else {
$arrayData[$attribute] = null;
}
}
return $arrayData;
}
/**
* Public wrapper for __toArray
*
* @param array $attributes
* @return array
*/
public function toArray(array $attributes = array())
{
return $this->__toArray($attributes);
}
/**
* Checks whether the object is empty
*
* @return boolean
*/
public function isEmpty()
{
if (empty($this->_data)) {
return true;
}
return false;
}
/**
* Retrieves data from the object
*
* If $key is empty will return all the data as an array
* Otherwise it will return value of the attribute specified by $key
*
* @param string $key
* @return mixed
*/
public function getData($key = null)
{
if (is_null($key)) {
return $this->_data;
}
if (!isset($this->_data[$key])) {
return;
}
return $this->_data[$key];
}
/**
* Overwrite data in the object.
*
* @param string $key
* @param mixed $value
* @return Mamis_Shippit_Object
*/
public function setData($key, $value = null)
{
$this->_data[$key] = $value;
return $this;
}
/**
* Unsets the data from the object
*
* @param string $key
* @return boolean
*/
public function unsData($key)
{
unset($this->_data[$key]);
return $this;
}
/**
* Determines if the data is set in the object
*
* @param string $key
* @return boolean
*/
public function hasData($key)
{
return isset($this->_data[$key]);
}
/**
* Convert a value to studly caps case.
*
* @param string $value
* @return string
*/
public static function studly($value)
{
$key = $value;
if (isset(static::$studlyCache[$key])) {
return static::$studlyCache[$key];
}
$value = ucwords(str_replace(['-', '_'], ' ', $value));
return static::$studlyCache[$key] = str_replace(' ', '', $value);
}
/**
* Convert a string to snake case.
*
* @param string $value
* @param string $delimiter
* @return string
*/
public static function snake($value, $delimiter = '_')
{
$key = $value;
if (isset(static::$snakeCache[$key][$delimiter])) {
return static::$snakeCache[$key][$delimiter];
}
if (!ctype_lower($value)) {
$value = preg_replace('/\s+/u', '', ucwords($value));
$value = static::lower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value));
}
return static::$snakeCache[$key][$delimiter] = $value;
}
/**
* Convert the given string to lower-case.
*
* @param string $value
* @return string
*/
public static function lower($value)
{
return mb_strtolower($value, 'UTF-8');
}
/**
* Implementation of ArrayAccess::offsetSet()
*
* @link http://www.php.net/manual/en/arrayaccess.offsetset.php
* @param string $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
$this->_data[$offset] = $value;
}
/**
* Implementation of ArrayAccess::offsetExists()
*
* @link http://www.php.net/manual/en/arrayaccess.offsetexists.php
* @param string $offset
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->_data[$offset]);
}
/**
* Implementation of ArrayAccess::offsetUnset()
*
* @link http://www.php.net/manual/en/arrayaccess.offsetunset.php
* @param string $offset
*/
public function offsetUnset($offset)
{
unset($this->_data[$offset]);
}
/**
* Implementation of ArrayAccess::offsetGet()
*
* @link http://www.php.net/manual/en/arrayaccess.offsetget.php
* @param string $offset
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->_data[$offset]) ? $this->_data[$offset] : null;
}
}
<file_sep>/includes/class-shippit-shipment.php
<?php
class Mamis_Shippit_Shipment
{
/**
* Response Messages
*/
const ERROR_API_KEY_MISSING = 'An API Key is required';
const ERROR_API_KEY_MISMATCH = 'The API Key provided does not match the configured API Key';
const ERROR_BAD_REQUEST = 'An invalid request was recieved';
const ERROR_ORDER_MISSING = 'The order requested was not found or has a status that is not available for shipping';
const NOTICE_SHIPMENT_STATUS = 'Ignoring the order status update, as we only respond to ready_for_pickup state';
const SUCCESS_SHIPMENT_CREATED = 'The shipment record was created successfully.';
protected $log;
/**
* Constructor.
*/
public function __construct()
{
$this->log = new Mamis_Shippit_Log();
}
/**
* Handle a Shippit Shipment Request
*
* @return void
*/
public function handle()
{
global $wp;
// Check the request API key is present and matches the configured API key
$this->checkApiKey();
// Get the JSON data posted
$requestData = json_decode(file_get_contents('php://input'));
// Validate the request is valid and in a state that can be used to update shipping details
$this->checkRequest($requestData);
$order = $this->getOrder($requestData);
// Ensure we have a valid order object
$this->checkOrder($order);
// Update the order with the shipment details
$this->updateOrder($order, $requestData);
// Return a response to the actions completed
wp_send_json_success(array(
'message' => self::SUCCESS_SHIPMENT_CREATED
));
}
public function getOrder($requestData)
{
$retailerOrderNumber = $this->getRequestRetailerOrderNumber($requestData);
$retailerReference = $this->getRequestRetailerReference($requestData);
// If a retailer_reference is available and numeric, do a direct lookup via the database identifier
// Note: Numeric check is required as WooCommerce will ignore queries filters for non-numeric identifiers
if (!empty($retailerReference) && is_numeric($retailerReference)) {
$order = wc_get_order($retailerReference);
}
// Otherwise, attempt to locate the order using the friendly reference number
else {
// If the WordPress JetPack module is installed + enabled, lookup using this module's order metadata
if (class_exists('WCJ_Order_Numbers') && get_option('wcj_order_numbers_enabled') == 'yes') {
$order = $this->getOrderByReferenceJetpack($retailerOrderNumber);
}
// Otherwise, attempt the lookup using the standard wordpress lookup methods
else {
$order = $this->getOrderByReference($retailerOrderNumber);
}
}
if (empty($order)) {
wp_send_json_error(array(
'message' => self::ERROR_ORDER_MISSING
));
}
return $order;
}
/**
* Get the order object, querying for the order
* using it's reference number
*
* @param string $orderNumber
* @return WP_Post|void
*/
public function getOrderByReference($orderNumber)
{
if (empty($orderNumber)) {
return;
}
$queryArgs = array(
'post__in' => [$orderNumber],
'post_type' => 'shop_order',
'post_status' => 'wc-processing',
'posts_per_page' => 1,
);
$posts = get_posts($queryArgs);
$post = reset($posts);
// If no results are found, return early
if (empty($post)) {
return;
}
// Load the woocommerce order using the post id
return wc_get_order($post->ID);
}
/**
* Get the order object, querying for the order
* using JetPack Metadata and considering it's
* configuration options
*
* @param string $orderNumber
* @return WP_Post|void
*/
public function getOrderByReferenceJetpack($orderNumber)
{
if (empty($orderNumber)) {
return;
}
// Add support for Wordpress Jetpack - Order Numbers
$orderPrefix = get_option('wcj_order_number_prefix');
$wcjSequentialEnabled = get_option('wcj_order_number_sequential_enabled');
// If an order prefix is configured, remove it from the order number to be used for lookup
if (!empty($orderPrefix)) {
$orderNumber = str_replace($orderPrefix, '', $orderNumber);
}
if ($wcjSequentialEnabled == 'yes') {
$queryArgs = array(
'meta_key' => '_wcj_order_number',
'meta_value' => $orderNumber,
'post_type' => 'shop_order',
'post_status' => 'wc-processing',
'posts_per_page' => 1,
);
}
else {
$queryArgs = array(
'post__in' => [$orderNumber],
'post_type' => 'shop_order',
'post_status' => 'wc-processing',
'posts_per_page' => 1,
);
}
$posts = get_posts($queryArgs);
$post = reset($posts);
// If no results are found, return early
if (empty($post)) {
return;
}
// Load the woocommerce order using the post id
return wc_get_order($post->ID);
}
public function updateOrder($order, $requestData)
{
// Grab item details from order
$orderId = $order->get_id();
$orderItems = $order->get_items();
// Grab item details from request data
$requestItems = $requestData->products;
// Temproary storage of items shipped and shippable
$orderItemsData = array();
$totalItemsShippable = 0;
// Create new array that holds the products in the order with required data
foreach ($orderItems as $orderItem) {
// SKU not stored in get_items so need to create new WC_Product
// If item is a variation use variation_id in product call
if ($orderItem['variation_id']) {
$product = new WC_Product_Variation($orderItem['variation_id']);
}
else {
$product = new WC_Product($orderItem['product_id']);
}
$orderItemsData[] = array (
'name' => $orderItem['name'],
'sku' => $product->get_sku(),
'qty' => $orderItem['qty'],
'variation_id' => $orderItem['variation_id']
);
// Count how many total items have been ordered
$totalItemsShippable += $orderItem['qty'];
}
// Remove any refunded items from shippable count
$totalItemsShippable += $order->get_total_qty_refunded();
$this->log->add(
'SHIPPIT - WEBHOOK REQUEST',
'Order Contents',
array(
'orderItems' => $orderItemsData,
'totalItemsShippable' => $totalItemsShippable
)
);
// Check for count of items that have been shipped
if (get_post_meta($orderId, '_mamis_shippit_shipped_items', true)) {
$totalItemsShipped = get_post_meta($orderId, '_mamis_shippit_shipped_items', true);
}
// If no items have been shipped previously set count to 0
else {
add_post_meta($orderId, '_mamis_shippit_shipped_items', 0, true);
$totalItemsShipped = 0;
}
// Add order comment for when items are shipped
$orderComment = 'The following items have been marked as Shipped in Shippit..<br>';
$orderItemsShipped = array();
foreach ($requestItems as $requestItem) {
// skip requests for quantities not present or less than or equal to 0
if (!property_exists($requestItem, 'quantity') || $requestItem->quantity <= 0) {
continue;
}
$skuData = null;
$productSku = (isset($requestItem->sku) ? $requestItem->sku : null);
$productVariationId = null;
if (strpos($productSku, '|') !== false) {
$skuData = explode('|', $productSku);
$productVariationId = end($skuData);
// remove the variation id
array_pop($skuData);
$productSku = implode('|', $skuData);
}
// If we have product sku data, attempt to match based
// on the product sku + variation id, or product sku
if (!empty($productSku)) {
foreach ($orderItemsData as $orderItemData) {
if (
// If the product is a variation, match sku and variation_id
(!is_null($productVariationId)
&& $productSku == $orderItemData['sku']
&& $productVariationId == $orderItemData['variation_id'])
// Otherwise, match by the sku only
|| $productSku == $orderItemData['sku']
) {
$orderComment .= $requestItem->quantity . 'x of ' . $requestItem->title . '<br>';
$totalItemsShipped += $requestItem->quantity;
$orderItemsShipped[] = array(
'sku' => $requestItem->sku,
'quantity' => $requestItem->quantity,
'title' => $requestItem->title
);
}
}
}
// Otherwise, don't attempt matching to order items
// Use the requestItem qty to determine the
// number of items that were shipped
else {
$orderComment .= $requestItem->quantity . 'x of ' . (isset($requestItem->title) ? $requestItem->title : 'Unknown Item') . '<br>';
$totalItemsShipped += $requestItem->quantity;
$orderItemsShipped[] = array(
'quantity' => $requestItem->quantity
);
}
}
if ($totalItemsShipped == 0) {
wp_send_json_error(array(
'message' => self::ERROR_BAD_REQUEST
));
}
$this->log->add(
'SHIPPIT - WEBHOOK REQUEST',
'Items Shipped',
array(
'orderItems' => $orderItemsData,
'orderItemsShipped' => $orderItemsShipped,
'totalItemsShipped' => $totalItemsShipped
)
);
// Update Order Shipments Metadata
$this->updateShipmentMetadata($orderId, $requestData, $totalItemsShipped);
// Add order comment for shipped items
$order->add_order_note($orderComment, 0);
// If all items have been shipped, change the order status to completed
if ($totalItemsShipped >= $totalItemsShippable) {
$order->update_status('completed', 'Order has been shipped with Shippit');
add_action(
'woocommerce_order_status_completed_notification',
'action_woocommerce_order_status_completed_notification',
10,
2
);
}
// Update the total of all items shipped
update_post_meta($orderId, '_mamis_shippit_shipped_items', $totalItemsShipped);
}
/**
* Add shipment information for the order or update the
* shipment information if some data already exists
*
* @param string $orderId The order id
* @param object $requestData The webhook request data
* @param object $totalItemsShipped The webhook request data
* @return mixed The response from update_post_meta,
* or null if request data is empty
*/
public function updateShipmentMetadata($orderId, $requestData, $totalItemsShipped)
{
$statusHistory = $requestData->status_history;
$status = array_filter($statusHistory, function($statusItem) {
return ($statusItem->status == 'ready_for_pickup');
});
$readyForPickUp = reset($status);
$shipmentData['tracking_number'] = $requestData->tracking_number;
$shipmentData['tracking_url'] = $requestData->tracking_url;
$shipmentData['courier_name'] = $requestData->courier_name;
if (get_option('wc_settings_shippit_fulfillment_tracking_reference') == 'courier_tracking_reference') {
$shipmentData['courier_tracking_number'] = $requestData->courier_job_id;
}
if (!empty($readyForPickUp)) {
$shipmentData['booked_at'] = date("d-m-Y H:i:s", strtotime($readyForPickUp->time));
}
$shipments = array();
$existingShipment = get_post_meta($orderId, '_mamis_shippit_shipment', false);
// Retrieve the existing shipment data if it's available
if (!empty($existingShipment)) {
$shipments = reset($existingShipment);
}
// Append the new shipment data
$shipments[] = $shipmentData;
// Update the total of all items shipped
update_post_meta($orderId, '_mamis_shippit_shipped_items', $totalItemsShipped);
// Update the order shipment metadata
update_post_meta($orderId, '_mamis_shippit_shipment', $shipments);
}
public function checkApiKey()
{
global $wp;
// Get the configured api key
$apiKey = get_option('wc_settings_shippit_api_key');
// Grab the posted shippit API key
$requestApiKey = $wp->query_vars['shippit_api_key'];
// ensure an api key has been retrieved in the request
if (empty($requestApiKey)) {
wp_send_json_error(array(
'message' => self::ERROR_API_KEY_MISSING
));
}
// check that the request api key matches the stored api key
if ($apiKey != $requestApiKey) {
wp_send_json_error(array(
'message' => self::ERROR_API_KEY_MISMATCH
));
}
}
public function getRequestRetailerOrderNumber($requestData)
{
if (isset($requestData->retailer_order_number)) {
return $requestData->retailer_order_number;
}
}
public function getRequestRetailerReference($requestData)
{
if (isset($requestData->retailer_reference)) {
return $requestData->retailer_reference;
}
}
public function getRequestCurrentState($requestData)
{
if (isset($requestData->current_state)) {
return $requestData->current_state;
}
}
/**
* Checks the request data is valid and in a state that can be worked with
*
* @param [type] $requestData
* @return void
*/
public function checkRequest($requestData)
{
global $wp;
// Grab the posted shippit API key
$requestApiKey = $wp->query_vars['shippit_api_key'];
$this->log->add(
'SHIPPIT - WEBHOOK REQUEST',
'Webhook Request Received',
array(
'url' => get_site_url() . '/shippit/shipment_create?shippit_api_key=' . $requestApiKey,
'requestData' => $requestData
)
);
// Check if the request has a body of data
if (empty($requestData)) {
wp_send_json_error(array(
'message' => self::ERROR_BAD_REQUEST
));
}
$retailerOrderNumber = $this->getRequestRetailerOrderNumber($requestData);
$retailerReference = $this->getRequestRetailerReference($requestData);
$currentState = $this->getRequestCurrentState($requestData);
// Ensure the request had an order number / order id that we can update against
if (empty($retailerOrderNumber) && empty($retailerReference)) {
wp_send_json_error(array(
'message' => self::ERROR_ORDER_MISSING
));
}
// Ensure the order update notification is a state that we wish to update against
if (empty($currentState) || $currentState != 'ready_for_pickup') {
wp_send_json_success(array(
'message' => self::NOTICE_SHIPMENT_STATUS
));
}
}
public function checkOrder($order)
{
// Check if an order is returned
if (!$order) {
wp_send_json_error(array(
'message' => self::ERROR_ORDER_MISSING
));
}
}
}
| 2207318d7a0ffe97cbbf358e0a442b668a25af2c | [
"JavaScript",
"Text",
"PHP"
] | 17 | PHP | Go-Shippit/Woo-Commerce | 09aca8b586b794a46aa22649006ab08bc30059a5 | cd254470335168ef0d0affe26a67b19f01639190 |
refs/heads/master | <file_sep>Factory.define :legislator do |u|
u.sequence(:first_name) {|n| "Legislator #{n.to_s}"}
u.sequence(:last_name) {|n| "Coolio #{n.to_s}"}
u.sequence(:address1) {|n| "#{n.to_s} Oak Street"}
u.sequence(:address2) {|n| "Apt. #{n.to_s}"}
u.sequence(:town) {|n| "City #{n.to_s}"}
u.sequence(:state) {|n| "ME"}
u.sequence(:zip) {|n| "1234#{n.to_s}"}
u.sequence(:zip4) {|n| "123#{n.to_s}"}
end<file_sep>require File.dirname(__FILE__) + '/../spec_helper'
describe LegislatorsController, "Get index" do
it "assigns all legislators" do
legislators = []
Legislator.stub!(:all).and_return legislators
get :index
assigns[:legislators].should be(legislators)
end
end
# describe LegislatorsController, "Get show" do
# it "assigns a legislator" do
# @legislator = mock(Legislator)
# Legislator.stub!(:find).and_return @legislator
# get :show, :id => id
# assigns[:legislator].should be(@legislator)
# end
# end
describe LegislatorsController, "Get new" do
it "assigns a new legislator" do
legislator = mock(Legislator)
Legislator.stub!(:new).and_return legislator
get :new
assigns[:legislator].should be(legislator)
end
end
describe LegislatorsController, "POST create" do
before(:each) do
@legislator = mock_model(Legislator, :save => nil)
Legislator.stub!(:new).and_return(@legislator)
end
it "should build a new legislator" do
Legislator.should_receive(:new).with("first_name" => "Bob").and_return(@legislator)
post :create, :legislator => { "first_name" => "Bob"}
end
it "should save the legislator" do
@legislator.should_receive(:save)
post :create
end
context "when the legislator saves successfully" do
before(:each) do
@legislator.stub!(:save).and_return true
end
it "should set a flash[:notice] message" do
post :create
flash[:notice].should == "The legislator was saved successfully."
end
it "should redirect to the legislator's profile page" do
post :create
response.should redirect_to(legislator_path(@legislator))
end
end
context "when the legislator fails to save" do
before(:each) do
@legislator.stub!(:save).and_return false
end
it "should assign @legislator" do
post :create
assigns[:legislator].should == @legislator
end
it "should render the new template" do
post :create
response.should render_template("new")
end
end
end
describe LegislatorsController, "Get edit" do
before(:each) do
@legislator = mock(Legislator)
Legislator.stub!(:find).and_return @legislator
end
it "responds successfully" do
get :edit, :id => '1'
response.should be_success
end
it "finds the requested legislator" do
id = "1"
Legislator.should_receive(:find).with id
get :edit, :id => id
end
it "assigns the requested legislator" do
get :edit, :id => "1"
assigns[:legislator].should be(@legislator)
end
end
describe LegislatorsController, "Get show" do
before(:each) do
@legislator = mock(Legislator)
Legislator.stub!(:find).and_return @legislator
end
it "responds successfully" do
get :show, :id => '1'
response.should be_success
end
it "finds the requested legislator" do
id = "1"
Legislator.should_receive(:find).with id
get :show, :id => id
end
it "assigns the requested legislator" do
get :show, :id => "1"
assigns[:legislator].should be(@legislator)
end
end
describe LegislatorsController, "Get update" do
before(:each) do
@legislator = mock_model(Legislator)
Legislator.stub!(:find).and_return @legislator
@legislator.stub!(:update_attributes)
end
it "redirects to the index" do
put :update, :id => "1", :legislator => {}
response.should redirect_to(legislator_path(@legislator))
end
it "updates the legislator" do
attributes = {
"first_name" => 'cool',
"last_name" => '<NAME>',
"address1" => '21 Oak Street',
"address2" => 'Apt. 4',
"town" => 'Anytown',
"state" => 'ME',
"zip" => '04102',
"zip4" => '1234'
}
@legislator.should_receive(:update_attributes).with attributes
put :update, :id => "1", :legislator => attributes
end
end
<file_sep># Sets up the Rails environment for Cucumber
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/rails/world'
# Comment out the next line if you don't want Cucumber Unicode support
require 'cucumber/formatter/unicode'
# Comment out the next line if you don't want transactions to
# open/roll back around each scenario
Cucumber::Rails.use_transactional_fixtures
# Comment out the next line if you want Rails' own error handling
# (e.g. rescue_action_in_public / rescue_responses / rescue_from)
Cucumber::Rails.bypass_rescue
require 'webrat'
Webrat.configure do |config|
config.mode = :rails
end
require 'cucumber/rails/rspec'
require 'webrat/core/matchers'
require 'pickle/world'
Pickle.configure do |config|
config.adapters = [:factory_girl]
config.map 'I', 'myself', 'me', 'my', :to => 'user: "me"'
end
require 'pickle/path/world'
require 'pickle/email/world'
<file_sep>
Given /^no legislators$/ do
Legislator.destroy_all
end
Given /^the legislator$/ do |table|
data = table.hashes[0]
@legislator = Legislator.create!(data)
end
Given /^the legislators$/ do |table|
@legislators = table.hashes.map do |data|
Legislator.create!(data)
end
end
Given /^(\d*) legislators?$/ do |legislator_count|
@legislators = []
legislator_count.to_i.times do
@legislators << Factory(:legislator)
end
end
When /^I create a legislator$/ do |legislator|
When %{I fill in legislator information}, legislator
And %{I press "Create"}
end
When /^I fill in legislator information$/ do |table|
data = table.hashes[0]
first_name = data[:first_name]
last_name = data[:last_name]
address1 = data[:address1]
address2 = data[:address2]
town = data[:town]
state = data[:state]
zip = data[:zip]
zip4 = data[:zip4]
When %{I fill in "First Name" with "#{first_name}"}
And %{I fill in "Last Name" with "#{last_name}"}
And %{I fill in "Address" with "#{address1}"}
And %{I fill in "Address 2" with "#{address2}"}
And %{I fill in "Town" with "#{town}"}
And %{I fill in "State" with "#{state}"}
And %{I fill in "Zip" with "#{zip}"}
And %{I fill in "+4" with "#{zip4}"}
end
When /^I fill in legislator address$/ do |table|
data = table.hashes[0]
address1 = data[:address1]
address2 = data[:address2]
town = data[:town]
state = data[:state]
zip = data[:zip]
zip4 = data[:zip4]
When %{I fill in "Address" with "#{address1}"}
And %{I fill in "Address 2" with "#{address2}"}
And %{I fill in "Town" with "#{town}"}
And %{I fill in "State" with "#{state}"}
And %{I fill in "Zip" with "#{zip}"}
And %{I fill in "+4" with "#{zip4}"}
end
Then /^I should see the legislator$/ do
Then %{I should see "#{@legislator.first_name} #{@legislator.last_name}"}
end
Then /^I should see the legislators$/ do
@legislators.each do |legislator|
Then %{I should see "#{legislator.first_name} #{legislator.last_name}"}
end
end
<file_sep>class Legislator < CouchFoo::Base
property :first_name, String
property :last_name, String
property :address1, String
property :address2, String
property :town, String
property :state, String
property :zip, String
property :zip4, String
property :created_at, DateTime
property :updated_at, DateTime
validates_presence_of :first_name
validates_presence_of :last_name
end
<file_sep>require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Legislator do
before(:each) do
@legislator = Legislator.new(:first_name => "Bob",:last_name => "Dobbs")
end
describe "validations" do
it "should be valid with valid attributes" do
@legislator.should be_valid
end
it "should should not be valid without a first_name" do
@legislator.first_name = nil
@legislator.should_not be_valid
end
it "should not be valid without a last_name" do
@legislator.last_name = nil
@legislator.should_not be_valid
end
end
end
<file_sep>require "couch_foo"
CouchFoo::Base.set_database(:host => "http://localhost:5984", :database => "legiwatch-dev")
CouchFoo::Base.logger = Rails.logger
| a6564ee4fa270517c223aea61d8a2e7fbb2f3ef7 | [
"Ruby"
] | 7 | Ruby | jhenry/legiwatch | 315f60db95a8bb78078df1301f0b115f5df62c4a | 9f8f7e2f7a0eb62c30a70a599a318a20b45a5af8 |
refs/heads/master | <file_sep>#ifndef COLLISION_H
#define COLLISION_H
#include "Square.h"
#include "Circle.h"
/**
* Class which contains the logic for square/square, circle/circle &
* circle/square collison.
*/
class Collision {
public:
~Collision(void);
static bool isCollision(const Square &squareOne, const Square &squareTwo);
static bool isCollision(const Circle &circleOne, const Circle &circleTwo);
static bool isCollision(const Circle &circle, const Square &square);
private:
/**
* We declare the constructor as private as this is a static only use class to
* call collision detection on
*/
Collision(void);
};
#endif
<file_sep>#include "Square.h"
#include "Collision.h"
#include <iostream>
/** CONSTRUCTORS & DESTRUCTOR **/
/**
* Default constructor
*/
Square::Square(void)
: Shape() {
this->length = 0;
}
/**
* Constructor with explicit x, y, length values
*/
Square::Square(const float x, const float y, const float length)
: Shape(x, y, length, length) {
this->length = length;
}
/**
* Copy constructor
*/
Square::Square(const Square& copy) {
pos.left = copy.pos.left;
pos.top = copy.pos.top;
pos.right = copy.pos.right;
pos.bottom = copy.pos.bottom;
length = copy.length;
}
/**
* Destructor
*/
Square::~Square(void) {
}
/** MEMBER FUNCTIONS **/
/**
* As we cant make the << operator virtual in the base class this function
* gets an ostream passed in and just calls this classes own << overload so
* we can print out the square output.
*/
std::ostream& Square::print(std::ostream& o) const {
o << *this;
return o;
}
/**
* Checks the run time type ID for the shape being passed in and
* calls the correct collision method in the Collision class respectivly
*/
bool Square::isCollision(const Shape &shape) const {
try {
if(typeid(shape) == typeid(Square)) {
return Collision::isCollision(dynamic_cast<const Square&>(shape), *this);
} else if(typeid(shape) == typeid(Circle)) {
return Collision::isCollision(dynamic_cast<const Circle&>(shape), *this);
}else {
throw "Error: Cannot define derived shape type";
}
} catch (char const* &e) {
std::cout << e;
}
return false;
}
/** OPERATOR OVERLOADS **/
/**
* Overloads assignment operator
*/
Square& Square::operator=(const Square &square) {
if(this != &square) {
pos.left = square.pos.left;
pos.top = square.pos.top;
pos.right = square.pos.right;
pos.bottom = square.pos.bottom;
length = square.length;
}
return *this;
}
/**
* Overloads ostream operator
*/
std::ostream& operator<<(std::ostream& o, const Square& square) {
o << "SQUARE" << std::endl <<
"Position[Top: " << square.pos.top << " , Right: " << square.pos.right << " , Bottom: " << square.pos.bottom << " , Left: " << square.pos.left << "]" << std::endl <<
"Length[" << square.length << "]" << std::endl <<
"Origin[X: " << square.getOriginX() << " , Y: " << square.getOriginY() << "]" << std::endl;
return o;
}
<file_sep>#ifndef SHAPE_H
#define SHAPE_H
#include <string>
class Shape {
/** Position struct for all derived shapes **/
struct Position {
float top;
float bottom;
float left;
float right;
};
public:
/** CONSTRUCTORS & DESTRUCTOR **/
Shape(void);
Shape(const float x, const float y, const float width, const float height);
virtual ~Shape(void);
/** MEMBER FUNCTIONS **/
virtual std::ostream& print(std::ostream& o) const = 0;
virtual bool isCollision(const Shape &shape) const = 0;
void move(const float x, const float y);
float getTop() const { return pos.top; };
float getBottom() const { return pos.bottom; };
float getLeft() const { return pos.left; };
float getRight() const { return pos.right; };
float getOriginX() const { return (pos.left + pos.right) / 2; }
float getOriginY() const { return (pos.bottom + pos.top) / 2; }
bool getIncreaseXBounds() const { return increaseXBounds; }
void setIncreaseXBounds(const bool increase) { increaseXBounds = increase; }
bool getIncreaseYBounds() const { return increaseYBounds; }
void setIncreaseYBounds(const bool increase) { increaseYBounds = increase; }
/** OPERATOR OVERLOADS **/
bool operator==(const Shape &square) const;
bool operator!=(const Shape &square) const;
protected:
// vtptr RTTI gets created in here for us to use typeid later on
Position pos;
bool increaseXBounds;
bool increaseYBounds;
};
#endif
<file_sep>#ifndef CIRCLE_H
#define CIRCLE_H
#include "Shape.h"
class Circle : public Shape {
public:
/** CONSTRUCTORS & DESTRUCTOR **/
Circle(void);
Circle(const float x, const float y, const float diameter);
Circle(const Circle& copy);
~Circle(void);
/** MEMBER FUNCTIONS **/
std::ostream& print(std::ostream& o) const;
bool isCollision(const Shape &shape) const;
float getDiameter() const { return diameter; };
float getRadius() const { return radius; };
/** OPERATOR OVERLOADS **/
Circle& operator=(const Circle &circle);
friend std::ostream& operator<<(std::ostream& o, const Circle& circle);
private:
float diameter;
float radius;
};
#endif
<file_sep>##CSC3221 Programming for Games
###Overview
Abstract classes and inheritance in C++ and collision detection in computer games.
###Specification
An important topic in many computer games is determining when 2 object collide with one another.
Games looks poor if a car appears to drive into a wall or appear to collide with thin air. Physics
Engines devote considerable effort to solving this problem. In this Project we will start to consider
this issue
Implement an abstract base class Shape to represent moving objects in the game. Derive classes
Circle and Square from Shape with appropriate information to store the positions on a flat
2_D surface. The classes should provide methods to move the position of the shape by a given
amount and a method to detect when two shapes overlap. You will need to deal with overlap of 2
circles, 2 squares and circle and square separately (the latter is difficult and will need some research.
A basic but acceptable solution is to embed the square within a circle of the appropriate radius and
use it for the overlap algorithm).
Write a test game program that creates several shapes and stores them in an array or list or other
data structure of your choosing. The program should then iterate through the data, move each
shape by a small random amount (but keeping them within a grid of a given size) and check to see if
there are any shapes overlapping. If there are, it should output the details about the overlapping
shapes (you do not need to deal with the problem of disentangling overlapping shapes - that is a
much trickier problem in game design!). It should then remove the overlapping shapes from the data
structure and continue the game until at most one shape remains. NO GRAPHICAL OUTPUT is
expected or required and providing some will not score any extra marks (this isn’t a graphics
course!)
###Output
```javascript
***********************
** COLLISON DETECTED **
CIRCLE
Position[Top: 1293.77 , Right: 1946.12 , Bottom: 1285.41 , Left: 1937.75]
Diameter[8.36375]
Radius[4.18188]
Origin[X: 1941.94 , Y: 1289.59]
CIRCLE
Position[Top: 1307.62 , Right: 1944.47 , Bottom: 1292.54 , Left: 1929.38]
Diameter[15.0835]
Radius[7.54173]
Origin[X: 1936.93 , Y: 1300.08]
SHAPES LEFT IN VECTOR: 30
***********************
***********************
** COLLISON DETECTED **
CIRCLE
Position[Top: 1509.99 , Right: 1992.72 , Bottom: 1498.77 , Left: 1981.49]
Diameter[11.2217]
Radius[5.61083]
Origin[X: 1987.1 , Y: 1504.38]
CIRCLE
Position[Top: 1500.47 , Right: 1994.47 , Bottom: 1494.95 , Left: 1988.96]
Diameter[5.51317]
Radius[2.75658]
Origin[X: 1991.72 , Y: 1497.71]
SHAPES LEFT IN VECTOR: 28
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 1071.13 , Right: 1836.36 , Bottom: 1061.61 , Left: 1826.84]
Length[9.51506]
Origin[X: 1831.6 , Y: 1066.37]
CIRCLE
Position[Top: 1063.6 , Right: 1840.94 , Bottom: 1057.32 , Left: 1834.65]
Diameter[6.28544]
Radius[3.14272]
Origin[X: 1837.8 , Y: 1060.46]
SHAPES LEFT IN VECTOR: 26
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 665.917 , Right: 1793.32 , Bottom: 658.017 , Left: 1785.42]
Length[7.90048]
Origin[X: 1789.37 , Y: 661.967]
SQUARE
Position[Top: 672.502 , Right: 1808.62 , Bottom: 656.951 , Left: 1793.07]
Length[15.5504]
Origin[X: 1800.85 , Y: 664.727]
SHAPES LEFT IN VECTOR: 24
***********************
***********************
** COLLISON DETECTED **
CIRCLE
Position[Top: 1904.49 , Right: 1904.36 , Bottom: 1893.27 , Left: 1893.14]
Diameter[11.2212]
Radius[5.6106]
Origin[X: 1898.75 , Y: 1898.88]
SQUARE
Position[Top: 1899.73 , Right: 1906.87 , Bottom: 1894.21 , Left: 1901.34]
Length[5.52232]
Origin[X: 1904.11 , Y: 1896.97]
SHAPES LEFT IN VECTOR: 22
***********************
***********************
** COLLISON DETECTED **
CIRCLE
Position[Top: 1368.68 , Right: 354.086 , Bottom: 1351.66 , Left: 337.067]
Diameter[17.018]
Radius[8.50902]
Origin[X: 345.577 , Y: 1360.17]
CIRCLE
Position[Top: 1359.2 , Right: 339.4 , Bottom: 1345.42 , Left: 325.616]
Diameter[13.7843]
Radius[6.89215]
Origin[X: 332.508 , Y: 1352.31]
SHAPES LEFT IN VECTOR: 20
***********************
***********************
** COLLISON DETECTED **
CIRCLE
Position[Top: 635.11 , Right: 239.235 , Bottom: 616.323 , Left: 220.449]
Diameter[18.786]
Radius[9.39299]
Origin[X: 229.842 , Y: 625.716]
CIRCLE
Position[Top: 634.983 , Right: 221.371 , Bottom: 625.478 , Left: 211.867]
Diameter[9.50453]
Radius[4.75227]
Origin[X: 216.619 , Y: 630.23]
SHAPES LEFT IN VECTOR: 18
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 243.81 , Right: 467.074 , Bottom: 230.492 , Left: 453.755]
Length[13.3192]
Origin[X: 460.414 , Y: 237.151]
CIRCLE
Position[Top: 226.407 , Right: 453.069 , Bottom: 221.305 , Left: 447.967]
Diameter[5.10163]
Radius[2.55081]
Origin[X: 450.518 , Y: 223.856]
SHAPES LEFT IN VECTOR: 16
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 73.3295 , Right: 388.875 , Bottom: 58.0498 , Left: 373.594]
Length[15.2794]
Origin[X: 381.235 , Y: 65.6897]
CIRCLE
Position[Top: 57.804 , Right: 368.891 , Bottom: 52.0535 , Left: 363.14]
Diameter[5.74984]
Radius[2.87492]
Origin[X: 366.015 , Y: 54.9287]
SHAPES LEFT IN VECTOR: 14
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 1862.62 , Right: 1278.38 , Bottom: 1847.14 , Left: 1262.9]
Length[15.4772]
Origin[X: 1270.64 , Y: 1854.88]
CIRCLE
Position[Top: 1874.94 , Right: 1264.27 , Bottom: 1858.07 , Left: 1247.4]
Diameter[16.8706]
Radius[8.43532]
Origin[X: 1255.83 , Y: 1866.5]
SHAPES LEFT IN VECTOR: 12
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 1605.06 , Right: 1443.54 , Bottom: 1598.37 , Left: 1436.85]
Length[6.69286]
Origin[X: 1440.19 , Y: 1601.72]
CIRCLE
Position[Top: 1611.78 , Right: 1467.12 , Bottom: 1593.63 , Left: 1448.97]
Diameter[18.1529]
Radius[9.07643]
Origin[X: 1458.05 , Y: 1602.7]
SHAPES LEFT IN VECTOR: 10
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 1859.43 , Right: 943.553 , Bottom: 1850.33 , Left: 934.451]
Length[9.10077]
Origin[X: 939.002 , Y: 1854.88]
CIRCLE
Position[Top: 1882.06 , Right: 949.826 , Bottom: 1863.93 , Left: 931.704]
Diameter[18.1208]
Radius[9.06041]
Origin[X: 940.765 , Y: 1873]
SHAPES LEFT IN VECTOR: 8
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 1081.18 , Right: 161.924 , Bottom: 1070.76 , Left: 151.499]
Length[10.4237]
Origin[X: 156.712 , Y: 1075.97]
CIRCLE
Position[Top: 1089.05 , Right: 170.943 , Bottom: 1078.83 , Left: 160.716]
Diameter[10.2255]
Radius[5.11277]
Origin[X: 165.83 , Y: 1083.94]
SHAPES LEFT IN VECTOR: 6
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 1527.25 , Right: 1709.12 , Bottom: 1517.13 , Left: 1699]
Length[10.1244]
Origin[X: 1704.06 , Y: 1522.19]
SQUARE
Position[Top: 1533.2 , Right: 1699.02 , Bottom: 1524.88 , Left: 1690.71]
Length[8.31385]
Origin[X: 1694.87 , Y: 1529.04]
SHAPES LEFT IN VECTOR: 4
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 729.169 , Right: 48.8051 , Bottom: 714.753 , Left: 34.3916]
Length[14.416]
Origin[X: 41.5984 , Y: 721.961]
CIRCLE
Position[Top: 717.65 , Right: 30.4217 , Bottom: 711.359 , Left: 24.1355]
Diameter[6.28681]
Radius[3.14341]
Origin[X: 27.2786 , Y: 714.505]
SHAPES LEFT IN VECTOR: 2
***********************
***********************
** COLLISON DETECTED **
SQUARE
Position[Top: 141.728 , Right: 1111.72 , Bottom: 135.992 , Left: 1105.99]
Length[5.73382]
Origin[X: 1108.85 , Y: 138.86]
SQUARE
Position[Top: 139.071 , Right: 1106.04 , Bottom: 127.776 , Left: 1094.76]
Length[11.2844]
Origin[X: 1100.4 , Y: 133.424]
SHAPES LEFT IN VECTOR: 0
***********************
Game finished with 0 shape(s) left...
```<file_sep>#include "Collision.h"
#include "Square.h"
#include <math.h>
#include <iostream>
/** CONSTRUCTORS & DESTRUCTOR **/
/**
* Default constructor
*/
Collision::Collision(void) {
}
/**
* Destructor
*/
Collision::~Collision(void) {
}
/**
* Basic square on square collision detection; we check the top, left, bottom and right sides
* against the other square. If all statements are true we have a collison.
*/
bool Collision::isCollision(const Square &squareOne, const Square &squareTwo) {
return squareOne.getLeft() < squareTwo.getRight() && squareOne.getRight() > squareTwo.getLeft() &&
squareOne.getBottom() < squareTwo.getTop() && squareOne.getTop() > squareTwo.getBottom();
}
/**
* Basic circle on circle collision detection; if the distance between the two origins is less than
* the sum of the two radii then we have a collision.
*/
bool Collision::isCollision(const Circle &circleOne, const Circle &circleTwo) {
float radius = circleOne.getRadius() + circleTwo.getRadius();
float deltaX = circleOne.getOriginX() - circleTwo.getOriginX();
float deltaY = circleOne.getOriginY() - circleTwo.getOriginY();
return (deltaX * deltaX + deltaY * deltaY) <= (radius * radius);
}
/**
* As this was a tricky method to work out I have referenced the forum from which I based
* this code on:
* http://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection
*/
bool Collision::isCollision(const Circle &circle, const Square &square) {
// Calculate the absolute values of the x and y difference between the center of the circle and the center of the rectangle.
float circleDistanceX = abs(circle.getLeft() - square.getLeft());
float circleDistanceY = abs(circle.getBottom() - square.getBottom());
// Eliminate the easy cases where the circle is far enough away from the rectangle (in either direction) that no intersection is possible.
if (circleDistanceX > (square.getLength()/2 + circle.getRadius())) { return false; }
if (circleDistanceY > (square.getLength()/2 + circle.getRadius())) { return false; }
// Handle the easy cases where the circle is close enough to the rectangle (in either direction) that an intersection is guaranteed.
if (circleDistanceX <= (square.getLength()/2)) { return true; }
if (circleDistanceY <= (square.getLength()/2)) { return true; }
// Calculate the difficult case where the circle may intersect the corner of the rectangle.
float cornerDistance_sq = pow(circleDistanceX - square.getLength() / 2, 2) +
pow(circleDistanceY - square.getLength() / 2, 2);
return (cornerDistance_sq <= pow(circle.getRadius(), 2));
}
<file_sep>#ifndef SQUARE_H
#define SQUARE_H
#include "Shape.h"
class Square : public Shape {
public:
/** CONSTRUCTORS & DESTRUCTOR **/
Square(void);
Square(const float x, const float y, const float length);
Square(const Square& copy);
~Square(void);
/** MEMBER FUNCTIONS **/
std::ostream& print(std::ostream& o) const;
bool isCollision(const Shape &shape) const;
float getLength() const { return length; };
/** OPERATOR OVERLOADS **/
Square& operator=(const Square &square);
friend std::ostream& operator<<(std::ostream& o, const Square& square);
private:
float length;
};
#endif
<file_sep>#include "Circle.h"
#include "Collision.h"
#include <iostream>
/** CONSTRUCTORS & DESTRUCTOR **/
/**
* Default constructor
*/
Circle::Circle(void)
: Shape() {
this->diameter = 0;
this->radius = 0;
}
/**
* Constructor with explicit x, y, diameter values
*/
Circle::Circle(const float x, const float y, const float diameter)
: Shape(x, y, diameter, diameter) {
this->diameter = diameter;
this->radius = diameter / 2;
}
/**
* Copy constructor
*/
Circle::Circle(const Circle& copy) {
pos.left = copy.pos.left;
pos.top = copy.pos.top;
pos.right = copy.pos.right;
pos.bottom = copy.pos.bottom;
diameter = copy.diameter;
radius = copy.radius;
}
/**
* Destructor
*/
Circle::~Circle(void) {
}
/** MEMBER FUNCTIONS **/
/**
* As we cant make the << operator virtual in the base class this function
* gets an ostream passed in and just calls this classes own << overload so
* we can print out the circles output.
*/
std::ostream& Circle::print(std::ostream& o) const {
o << *this;
return o;
}
/**
* Checks the run time type ID for the shape being passed in and
* calls the correct collision method in the Collision class respectivly
*/
bool Circle::isCollision(const Shape &shape) const {
try {
if(typeid(shape) == typeid(Square)) {
return Collision::isCollision(*this, dynamic_cast<const Square&>(shape));
} else if(typeid(shape) == typeid(Circle)) {
return Collision::isCollision(dynamic_cast<const Circle&>(shape), *this);
}else {
throw "Error: Cannot define derived shape type";
}
}catch (char const* &e) {
std::cout << e;
}
return false;
}
/** OPERATOR OVERLOADS **/
/**
* Overloads assignment operator
*/
Circle& Circle::operator=(const Circle &circle) {
if(this != &circle){
pos.left = circle.pos.left;
pos.top = circle.pos.top;
pos.right = circle.pos.right;
pos.bottom = circle.pos.bottom;
diameter = circle.diameter;
radius = circle.radius;
}
return *this;
}
/**
* Overloads ostream operator
*/
std::ostream& operator<<(std::ostream& o, const Circle& circle) {
o << "CIRCLE" << std::endl <<
"Position[Top: " << circle.pos.top << " , Right: " << circle.pos.right << " , Bottom: " << circle.pos.bottom << " , Left: " << circle.pos.left << "]" << std::endl <<
"Diameter[" << circle.diameter << "]" << std::endl <<
"Radius[" << circle.radius << "]" << std::endl <<
"Origin[X: " << circle.getOriginX() << " , Y: " << circle.getOriginY() << "]" << std::endl;
return o;
}<file_sep>#include "Shape.h"
#include <iostream>
/** CONSTRUCTORS & DESTRUCTOR **/
/**
* Default constructor
*/
Shape::Shape(void) {
pos.top = 0;
pos.bottom = 0;
pos.left = 0;
pos.right = 0;
increaseXBounds = true;
increaseYBounds = true;
}
/**
* Constructor with explicit x, y, width & height values
*/
Shape::Shape(const float x, const float y, const float width, const float height) {
pos.top = y + height;
pos.bottom = y;
pos.left = x;
pos.right = x + width;
increaseXBounds = true;
increaseYBounds = true;
}
/**
* Destructor
*/
Shape::~Shape(void) {
}
/** MEMBER FUNCTIONS **/
/**
* Updates the shape with the x and y values passed in
*/
void Shape::move(const float x, const float y) {
pos.top += y;
pos.bottom += y;
pos.left += x;
pos.right += x;
}
/** OPERATOR OVERLOADS **/
/**
* Overloads equal operator
*/
bool Shape::operator==(const Shape &square) const {
return (this == &square) ? true : false;
}
/**
* Overloads not equal operator
*/
bool Shape::operator!=(const Shape &square) const {
return (this == &square) ? false : true;
}<file_sep>#include "Square.h"
#include "Circle.h"
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
vector<Shape*> shapeVector;
const int GRID_WIDTH = 2000;
const int GRID_HEIGHT = 2000;
const int NUM_OF_SHAPES = 60;
const float MAX_SHAPE_SPEED = 0.2f;
const float MAX_SHAPE_WIDTH = 20.0f;
const float MIN_SHAPE_WIDTH = 5.0f;
void setupShapeVector();
void updateShapePositions();
void updateCollisions();
void outputCollisionData(Shape* shapeOne, Shape* shapeTwo);
float randomFloat(float min, float max);
int randomInt(int min, int max);
/**
* Main game loop, sets up the shape vector then updates each shape and checks
* for collisons until vector is empty or has only one shape left.
*/
int main () {
// Allows read friendly booleans
cout.setf(ios::boolalpha);
// Seed rand
srand (time(0));
setupShapeVector();
while(true) {
// End program if vector size is <= 1
if(shapeVector.size() <= 1) { break; }
updateShapePositions();
updateCollisions();
}
cout << "Game finished with " << shapeVector.size() << " shape(s) left..." << endl;
// Clean up
for(int i = 0; i < shapeVector.size(); i++) {
delete shapeVector[i];
}
// Keep console window open
std::cin.get();
return 0;
}
/**
* Adds X amount of random shapes (circles & squares) to the shape vector
* with random x, y and width properties. It doesn't matter if the are slightly outside
* the grid as the movement functions takes care of this.
*/
void setupShapeVector() {
for(int i = 0; i < NUM_OF_SHAPES; i++) {
// Random 0 or 1 to used to choose either square or circle
int bit = randomInt(0, 2);
float x = randomFloat(0, GRID_WIDTH);
float y = randomFloat(0, GRID_HEIGHT);
float width = randomFloat(MIN_SHAPE_WIDTH, MAX_SHAPE_WIDTH);
// Create a random shape with random properties and add to vector
if(bit == 0) {
shapeVector.push_back(new Circle(x, y, width));
}else {
shapeVector.push_back(new Square(x, y, width));
}
}
}
/**
* For each shape we check if it is outside the grid so we can decide on with
* direction to move (either positive or negative). We then add random x and y speed in
* that direction.
*/
void updateShapePositions() {
for(int i = 0; i < shapeVector.size(); i++) {
if(shapeVector[i]->getTop() > GRID_HEIGHT) {
shapeVector[i]->setIncreaseYBounds(false);
}else if(shapeVector[i]->getBottom() < 0){
shapeVector[i]->setIncreaseYBounds(true);
}
if(shapeVector[i]->getLeft() < 0) {
shapeVector[i]->setIncreaseXBounds(true);
}else if(shapeVector[i]->getRight() > GRID_WIDTH) {
shapeVector[i]->setIncreaseXBounds(false);
}
float x = (shapeVector[i]->getIncreaseXBounds()) ? randomFloat(0, MAX_SHAPE_SPEED) : randomFloat(0, -MAX_SHAPE_SPEED);
float y = (shapeVector[i]->getIncreaseYBounds()) ? randomFloat(0, MAX_SHAPE_SPEED) : randomFloat(0, -MAX_SHAPE_SPEED);
shapeVector[i]->move(x, y);
}
}
/**
* Checks each shape in the vector for collisions, it does not check itself. The comments
* below explain what is happening...
*/
void updateCollisions() {
// For each shape...
for(int i = 0; i < shapeVector.size(); i++) {
// Check against every other shape...
for(int j = 0; j < shapeVector.size(); j++) {
// But not if it that shape is itself...
if(shapeVector[i] != shapeVector[j]) {
// Then check if we have a collision...
if(shapeVector[i]->isCollision(*shapeVector[j])) {
// If we do we need to check the values of i & j to delete correct element
// as the vector will shift left after erasing a value. We also free
// memory before erasing...
outputCollisionData(shapeVector[i], shapeVector[j]);
if(i < j) {
delete shapeVector[i];
shapeVector.erase(shapeVector.begin() + i);
delete shapeVector[j - 1];
shapeVector.erase(shapeVector.begin() + (j - 1));
}else {
delete shapeVector[i];
shapeVector.erase(shapeVector.begin() + i);
delete shapeVector[j];
shapeVector.erase(shapeVector.begin() + j);
}
cout << "SHAPES LEFT IN VECTOR: " << shapeVector.size() << endl;
cout << "***********************" << endl;
cout << endl;
}
}
}
}
}
/**
* Outputs the collision between two shapes formatted nicely.
*/
void outputCollisionData(Shape* shapeOne, Shape* shapeTwo) {
cout << endl;
cout << "***********************" << endl;
cout << "** COLLISON DETECTED **" << endl;
cout << endl;
shapeOne->print(cout) << endl;
shapeTwo->print(cout) << endl;
}
/**
* Returns a random float between two floats.
*/
float randomFloat(float min, float max) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = max - min;
float r = random * diff;
return min + r;
}
/**
* Returns a random int between two ints.
*/
int randomInt(int min, int max) {
return (rand()%(max-min))+min;
} | eaddffeba959d18a59c720e61ebe723a024270a0 | [
"Markdown",
"C++"
] | 10 | C++ | StephenCathcart/programming-for-games | 26fbcecb8044208a0245dec4a985cd311745835c | 9ebb47099a8eaf6ef098c7854a400344e4aa315f |
refs/heads/master | <file_sep>var express = require("express");
var mongoose = require("mongoose");
var path = require("path");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var session = require("express-session");
var flash = require("connect-flash");
var routes = require("./routes");
var app = express();
mongoose.connect("mongodb://localhost:27017/zombie_nest");
app.set("port", process.env.PORT || 3000);
app.set("viwe engine","ejs");
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
app.use(session({
secret:"holamundo",
resave:true,
saveUninitialized:true
}));
app.use(flash());
app.use(routes);
app.listen(app.get("port"),() =>{
console.log("la aplicacion esta corriendo por el puerto" + app.get("port"));
}); | b7398e96f10f8239132248d53fa70ac41d149818 | [
"JavaScript"
] | 1 | JavaScript | Alfredsant/zombie-social | aa55004cf72711ea393be6a9797aa6241ad7a849 | cf873a6f8b3738de22583921ffae38dd7496e2ed |
refs/heads/master | <file_sep>class Racer extends Employee {
Racer() {
setRate(2);
}
@Override
void countSalary() {
setSalary(getQuantity() * getRate());
}
}
<file_sep>class YoungEngineer extends Engineer {
YoungEngineer() {
setRate(getRate() / 2);
}
@Override
void countSalary() {
super.countSalary();
super.drink();
}
}
<file_sep>/**
* Class with main method for showing resulting info
*/
public class Main {
public static void main(String[] args) {
Input in = new Input();
System.out.printf("Amount of numbers %d%n", in.getElements().length);
System.out.printf("Sum of numbers %.2f%n", in.sum(in.getElements()));
System.out.printf("Arithmetic mean %.2f%n", in.sum(in.getElements()) / in.getElements().length);
}
}
<file_sep>class Number {
private String[] hundreds = new String[]{"сто", "двести", "триста", "четыреста", "пятьсот", "шестьсот", "семьсот",
"восемьсот", "девятьсот"};
private String[] tens = new String[]{"десять", "двадцать", "тридцать", "сорок", "пятьдесят", "шестьдесят", "семьдесят",
"восемьдесят", "девяносто"};
private String[] units = new String[]{"один", "два", "три", "четыре", "пять", "шесть", "семь", "восемь", "девять"};
private String[] elevens = new String[]{"одиннадцать", "двенадцать", "тринадцать", "четырнадцать", "пятнадцать",
"шестнадцать", "семнадцать", "восемнадцать", "девятнадцать"};
String[] getHundreds() {
return hundreds;
}
String[] getTens() {
return tens;
}
String[] getUnits() {
return units;
}
String[] getElevens() {
return elevens;
}
}
<file_sep>abstract class Employee {
private String name;
private double percent = 0.13;
private double salary = 0;
/**
* field rate has this value by default and can be changed with setRate
*/
private double rate = 1.5;
/**
* amount of races or working hours
*/
private int quantity;
int getQuantity() {
return quantity;
}
void setQuantity(int quantity) {
this.quantity = quantity;
}
double getRate() {
return rate;
}
void setRate(double rate) {
this.rate = rate;
}
double getSalary() {
return salary;
}
void setSalary(double salary) {
this.salary = salary;
}
void setPercent(double percent) {
this.percent = percent;
}
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
void printName() {
System.out.println("Name: " + name);
}
abstract void countSalary();
double taxCounter() {
if(salary == 0){
System.out.println("The salary hasn't been counted yet. Please count salary first");
}
return salary * percent;
}
}
<file_sep>import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class WorkingWithArrays {
private static void task1() {
int[] arr = new int[100];
int i = 1;
int m = 0;
do {
if (i % 13 == 0 || i % 17 == 0) {
arr[m] = i;
m++;
}
i++;
} while (m < 100);
out.println(Arrays.toString(arr));
}
private static void task2() {
int maxI = 0, m = 0, minI = 0;
out.println("Please input array length");
Scanner sc = new Scanner(System.in);
int amountOfNumbers = sc.nextInt();
sc.close();
int[] arr = new int[amountOfNumbers];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (100 * Math.random());
}
out.println(Arrays.toString(arr));
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= max) {
max = arr[i];
maxI = i;
}
}
out.println("max " + maxI);
int min = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] <= min) {
min = arr[i];
minI = i;
}
}
out.println("min " + minI);
for (int i = 0; i < arr.length; i++) {
if ((i > minI && i < maxI) || (i > maxI && i < minI)) {
m += arr[i];
}
}
if (m == 0) {
out.println("Elements are next to each other, value is 0");
} else {
out.println("Value " + m);
}
}
private static void task3() {
int k = 0;
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
sc.close();
for (int i = 2; i < num; i++) {
if (num % i == 0) {
k++;
}
}
if (k == 0) {
out.println("Prime");
} else {
out.println("Not prime");
}
}
private static void task4(String[] args) {
Scanner sc = new Scanner(System.in);
out.println("Please input array dimensions");
int sizeX = sc.nextInt();
int sizeY = sc.nextInt();
int[][] arr = new int[sizeX][sizeY];
int find = Integer.parseInt(args[1]);
int findX = 0, findY = 0;
int delta = Integer.parseInt(args[2]);
for (int i = 0; i < sizeX; i++) {
for (int k = 0; k < sizeY; k++) {
arr[i][k] = (int) (100 * Math.random());
}
}
int check = 0;
for (int[] n : arr) {
out.println(Arrays.toString(n));
}
for (int i = 0; i < sizeX; i++) {
for (int k = 0; k < sizeY; k++) {
if (arr[i][k] == find) {
findX = i;
findY = k;
check++;
break;
}
}
}
if (check == 0) {
out.println("No matches");
} else {
out.printf("Found coordinates! %d %d \n", findX, findY);
}
int m = 0;
loop:
for (int i = 0; i < sizeX; i++) {
for (int k = 0; k < sizeY; k++) {
m++;
if (arr[i][k] == find) {
findX = i;
findY = k;
check++;
break loop;
}
}
}
if (check == 0) {
out.println("No matches");
} else {
out.printf("Found coordinates and iterations! %d %d %d \n", findX, findY, m);
}
int check1 = 0;
for (int i = 0; i < sizeX; i++) {
for (int k = 0; k < sizeY; k++) {
if ((arr[i][k] < (find - delta)) || (arr[i][k] > (find + delta))) {
check1++;
}
}
}
out.println(check1);
}
private static void task5() {
int[] arr = new int[4];
for (int i = 0; i < 4; i++) {
arr[i] = 10 + (int) (90 * Math.random());
}
out.println(Arrays.toString(arr));
int[] arr1 = Arrays.copyOf(arr, 4);
Arrays.sort(arr1);
out.println(Arrays.toString(arr1));
if (Arrays.equals(arr, arr1)) {
out.println("The array is an ascending sequence");
} else {
out.println("Sorry");
}
}
private static void task6() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[][] arr = new String[n][n];
int i, j;
for (i = 0; i < arr.length / 2 + 1; i++) { //до середины нечетного и включая середину четного
for (j = 0; j < arr[i].length; j++) {
if ((j < i) || (j > (arr[i].length - i - 1)))
arr[i][j] = " ";
else
arr[i][j] = "*";
}
}
for (i = arr.length - 1; i >= arr.length / 2; i--) { //с конца вверх до середины включительно
for (j = 0; j < arr[i].length; j++) {
if ((j < (arr[i].length - 1 - i)) || (j > i))
arr[i][j] = " ";
else
arr[i][j] = "*";
}
}
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
out.print(arr[i][j]);
}
out.println(" ");
}
}
private static void task7() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[][] arr = new String[n][n];
int i = 0, j = 0;
while (i < arr.length / 2 + 1) {
while (j < arr[i].length) {
if ((j < i) || (j > (arr[i].length - i - 1))) {
arr[i][j] = " ";
} else {
arr[i][j] = "*";
}
j++;
}
i++;
j = 0;
}
i = arr.length - 1;
j = 0;
while (i >= arr.length / 2) {
while (j < arr[i].length) {
if ((j < arr[i].length - 1 - i) || (j > i)) {
arr[i][j] = " ";
} else {
arr[i][j] = "*";
}
j++;
}
j = 0;
i--;
}
i = 0;
j = 0;
while (i < arr.length) {
while (j < arr[i].length) {
out.print(arr[i][j]);
j++;
}
out.println(" ");
j = 0;
i++;
}
}
private static void task8() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[][] arr = new String[n][n];
int i = 0, j = 0;
do {
do {
if ((j < i) || (j > (arr[i].length - i - 1))) {
arr[i][j] = " ";
} else {
arr[i][j] = "*";
}
j++;
} while (j < arr[i].length);
i++;
j = 0;
} while (i < arr.length / 2 + 1);
i = arr.length - 1;
j = 0;
do {
do {
if ((j < arr[i].length - 1 - i) || (j > i)) {
arr[i][j] = " ";
} else {
arr[i][j] = "*";
}
j++;
} while (j < arr[i].length);
j = 0;
i--;
} while (i >= arr.length / 2);
i = 0;
j = 0;
do {
do {
out.print(arr[i][j]);
j++;
} while (j < arr[i].length);
out.println(" ");
j = 0;
i++;
} while (i < arr.length);
}
private static void task9() {
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] values = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen",
"King", "Ace"};
String[] card = new String[2];
int i = (int) (13 * Math.random());
int j = (int) (4 * Math.random());
card[0] = values[i];
card[1] = suits[j];
out.println(card[0] + " of " + card[1]);
}
private static void task10() {
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] values = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen",
"King", "Ace"};
String[] cards = new String[52];
for (int k = 0; k < cards.length; ) {
for (String suit : suits) {
for (String value : values) {
cards[k] = value + " of " + suit;
k++;
}
}
}
out.println(Arrays.toString(cards));
Random rnd = new Random();
for (int i = 0; i < cards.length; i++) {
int j = rnd.nextInt(i + 1);
String temp = cards[i];
cards[i] = cards[j];
cards[j] = temp;
}
out.println(Arrays.toString(cards));
}
public static void main(String[] args) {
for (String arg : args) {
out.println(arg);
}
if (args.length > 0) {
switch (args[0]) {
case "1":
task1();
break;
case "2":
task2();
break;
case "3":
task3();
break;
case "4":
task4(args);
break;
case "5":
task5();
break;
case "6":
task6();
break;
case "7":
task7();
break;
case "8":
task8();
break;
case "9":
task9();
break;
case "10":
task10();
break;
default:
out.println("Unknown pattern");
}
} else {
out.println("Please input at least one parameter");
}
}
}
<file_sep>package task8;
public class Mistake {
public static boolean checkStringCombination(String evenSymbols, String oddSymbols, String checkString) {
int i = 0, j = 0, k = 0;
int evenLength = evenSymbols.length();
int oddLength = oddSymbols.length();
int stringLength = checkString.length();
if (evenLength + oddLength != stringLength){
return false;
}
while (k < stringLength){
if (i < oddLength && oddSymbols.charAt(i) == checkString.charAt(k)){
i++;
} else {
return false;
}
k++;
if (k == stringLength){
break;
}
if (j < evenLength && evenSymbols.charAt(j) == checkString.charAt(k)){
j++;
} else{
return false;
}
k++;
if (k == stringLength){
break;
}
}
return i == oddLength && j == evenLength;
}
}
<file_sep>package task3;
public class Counter {
public static int count(String s) {
int count = 0;
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length - 2; i++) {
if (arr[i] == arr[i + 1] && arr[i + 1] == arr[i + 2]){
count++;
}
}
return count;
}
}
<file_sep>import java.util.Scanner;
/**
* Class checking whether an inputted ticket number is lucky or not
*/
class Lucky {
/**
* Stores "lucky" value
*/
private boolean ch;
Lucky() {
ch = check(toArray(input()));
}
/**
* Method for inputting a ticket number
*
* @return - returns number
*/
private static int input() {
int num;
Scanner sc = new Scanner(System.in);
while (true) {
try {
num = Integer.parseInt(sc.nextLine());
if (num > 999999) {
throw new Exception();
}
break;
} catch (Exception e) {
System.out.println("Wrong input! Please try again!");
}
}
return num;
}
/**
* Method checking whether the number is lucky or not
*
* @param arr - array storing ticket number
* @return - returns true if lucky
*/
private static boolean check(int[] arr) {
int i = arr[0] + arr[1] + arr[2];
int k = arr[3] + arr[4] + arr[5];
return k == i;
}
/**
* Method converting the ticket number into an array
*
* @param num - initial ticket number
* @return - returns ticket number converted into an array
*/
private int[] toArray(int num) {
int[] arr = new int[6];
for (int i = 1; i < 7; i++) {
arr[i - 1] = num % 10;
num -= arr[i - 1];
num /= 10;
}
return arr;
}
/**
* Method for printing Lucky class object
*
* @return - String with lucky/not lucky value
*/
@Override
public String toString() {
if (ch) {
return "Lucky ticket!";
} else {
return "Sorry, not this time";
}
}
}
<file_sep>/**
* Class for showing the resulting amount of money with main method
*/
public class Main {
public static void main(String[] args) {
Count ct = new Count();
System.out.printf("The amount of money you'll get in %d month(s) is %.2f", ct.getMonths(), ct.getInvest());
}
}
<file_sep>import java.util.Scanner;
/**
* Class for counting the amount of money
*/
class Count {
/**
* Money to invest
*/
private double invest;
/**
* Stores the amount of months in which the initial investment'll double
*/
private int months;
Count() {
System.out.println("Please input the amount of money you would like to invest");
this.invest = input();
System.out.println("Please input the monthly percent");
double percent = input();
double x = this.invest;
do {
this.invest += (x * (percent / 100));
this.months++;
} while (this.invest < x * 2);
}
/**
* method for inputting the amount of money and months
*
* @return - returns the inputted integer value
*/
private static int input() {
int num;
Scanner sc = new Scanner(System.in);
while (true) {
try {
num = Integer.parseInt(sc.nextLine());
break;
} catch (Exception e) {
System.out.println("Wrong input! Please try again!");
}
}
return num;
}
int getMonths() {
return months;
}
double getInvest() {
return invest;
}
}
<file_sep>package task5;
import java.util.Arrays;
import java.util.Comparator;
public class DigitSwapper{
public static String swap(String s){
s = s.trim();
String[] arr = s.split(" ");
Arrays.sort(arr, new DigitComparator());
return String.join(" ", arr);
}
private static class DigitComparator implements Comparator <String> {
@Override
public int compare(String o1, String o2) {
int first = Integer.parseInt(o1);
int second = Integer.parseInt(o2);
int sumFirst = 0;
int sumSecond = 0;
while (first != 0) {
sumFirst = first % 10;
first /= 10;
}
while (second != 0){
sumSecond = second % 10;
second /= 10;
}
return sumFirst - sumSecond;
}
}
}
<file_sep>public class Main {
public static void main(String[] args) {
int m = Check.input();
Check ch = new Check();
ch.check(m);
System.out.println(ch.getWord());
}
}
| 43506948d795cc082fa3d46f0d5ad190a9858d7d | [
"Java"
] | 13 | Java | yanrishbe/sam-labs | 2072a6ef67b6ede815c1b4857341bf71c5a8d3e1 | df7f69220b444a5949ebb3131be9a6448b0513fc |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hill : MonoBehaviour {
public float size;
public flo
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class World
{
/// <summary>
/// length in milimeters
/// </summary>
public int Width = 100000;
/// <summary>
/// length in milimeters
/// </summary>
public int Height = 100000;
/// <summary>
/// length in milimeters
/// </summary>
public int ChunkWidth = 500;
/// <summary>
/// length in milimeters
/// </summary>
public int ChunkHeight = 500;
public Vector2 Seed = Vector2.zero;
private Chunk[,] chunks;
private World() { }
public static World Create()
{
var w = new World();
w.chunks = new Chunk[w.Width / w.ChunkWidth, w.Height / w.ChunkHeight];
for (int x = 0; x < w.chunks.GetLength(0); x++)
{
for (int y = 0; y < w.chunks.GetLength(1); y++)
{
w.chunks[x, y] = new Chunk(w.Perlin(x, y, 20), w.Perlin(x, y, 20, new Vector2(10, 0)), w.Perlin(x, y, 20, new Vector2(20, 0)), w.Perlin(x, y, 20, new Vector2(30, 0)));
}
}
return w;
}
public float Perlin(float x, float y, float scaleInvers)
{
return Perlin(x, y, scaleInvers, Vector2.zero);
}
public float Perlin(float x, float y, float scaleInvers, Vector2 offset)
{
offset += Seed;
return Mathf.PerlinNoise(x / scaleInvers + offset.x, y / scaleInvers + offset.y);
}
public static float Perlin(Vector2 seed, float x, float y, float scaleInvers, Vector2 offset)
{
offset += seed;
return Mathf.PerlinNoise(x / scaleInvers + offset.x, y / scaleInvers + offset.y);
}
}
public struct Chunk
{
/// <summary>
/// 0: nothing; 1: water
/// </summary>
public float soilHumidity;
/// <summary>
/// 0: nothing; 1: granit stone
/// </summary>
public float soilDensity;
/// <summary>
/// 0: nothing; 1: 10 Newton to seperate one square cm of material (1: tape that holds one kg in the air)
/// </summary>
public float soilStickyness;
/// <summary>
/// 0: perfectly flat surface; 1: the actual walking distance in a straight line on average is 3 times as high as the distance with no imperfections
/// </summary>
public float soilImperfections;
public float Walkability()
{
//TODO
throw new System.NotImplementedException();
}
public Chunk(float soilHumidity, float soilDensity, float soilStickyness, float soilImperfections)
{
this.soilHumidity = soilHumidity;
this.soilDensity = soilDensity;
this.soilStickyness = soilStickyness;
this.soilImperfections = soilImperfections;
}
} | 170ee0ed53aa5c5b847f7cae8b827c92480aae79 | [
"C#"
] | 2 | C# | VinniplayDE/AmeisenSimulation2D | 80ffa512d778b53d095dd7e6db453123af639247 | 8c2f2af9c2a855651fbb41114a6d9cf7888e76c1 |
refs/heads/master | <file_sep>package com.sn.cacryptocurrencyapp.data.repository
import com.sn.cacryptocurrencyapp.data.remote.CoinPaprikaApi
import com.sn.cacryptocurrencyapp.data.remote.dto.CoinDetailDto
import com.sn.cacryptocurrencyapp.data.remote.dto.CoinDto
import com.sn.cacryptocurrencyapp.domain.repository.CoinRepository
import javax.inject.Inject
class CoinRepositoryImpl @Inject constructor(
private val api: CoinPaprikaApi
) : CoinRepository {
override suspend fun getCoins(): List<CoinDto> =
api.getCoins()
override suspend fun getCoinsBId(coinId: String): CoinDetailDto =
api.getCoinById(conId = coinId)
}<file_sep>package com.sn.cacryptocurrencyapp.common
object Constants {
const val BASE_URL = "https://api.coinpaprika.com/"
const val PARENT_COIN_ID = "coinId"
}<file_sep>package com.sn.cacryptocurrencyapp.domain.repository
import com.sn.cacryptocurrencyapp.data.remote.dto.CoinDetailDto
import com.sn.cacryptocurrencyapp.data.remote.dto.CoinDto
interface CoinRepository {
suspend fun getCoins(): List<CoinDto>
suspend fun getCoinsBId(coinId: String): CoinDetailDto
}<file_sep>package com.sn.cacryptocurrencyapp.domain.use_cases.get_coin
import com.sn.cacryptocurrencyapp.common.Resource
import com.sn.cacryptocurrencyapp.data.remote.dto.toCoinDetail
import com.sn.cacryptocurrencyapp.domain.model.CoinDetail
import com.sn.cacryptocurrencyapp.domain.repository.CoinRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject
class GetCoinUseCase @Inject constructor(
private val repository: CoinRepository
) {
operator fun invoke(coinId: String): Flow<Resource<CoinDetail>> = flow {
try {
emit(Resource.Loading<CoinDetail>())
val coin = repository.getCoinsBId(coinId).toCoinDetail()
emit(Resource.Success<CoinDetail>(coin))
} catch (e: HttpException) {
emit(Resource.Error<CoinDetail>(e.localizedMessage ?: "An unexpected error occurred"))
} catch (e: IOException) {
emit(Resource.Error<CoinDetail>("Couldn't reach server'. check your internet connection"))
}
}
}<file_sep># CaCryptocurrencyApp
<td align="center"> <img src="mad/jetpack.png" width="600" ></td>
<td align="center"> <img src="mad/summary.png" width="600" ></td>
<td align="center"> <img src="mad/kotlin.png" width="600" ></td>
<file_sep>package com.sn.cacryptocurrencyapp.data.remote
import com.sn.cacryptocurrencyapp.data.remote.dto.CoinDetailDto
import com.sn.cacryptocurrencyapp.data.remote.dto.CoinDto
import retrofit2.http.GET
import retrofit2.http.Path
interface CoinPaprikaApi {
@GET("v1/coins")
suspend fun getCoins(): List<CoinDto>
@GET("v1/coins/{coinId}")
suspend fun getCoinById(@Path("coinId") conId: String): CoinDetailDto
} | 1ed5e08162bcc80a055359a7e75ee9fd6594971d | [
"Markdown",
"Kotlin"
] | 6 | Kotlin | SaeedNoshadi89/CaCryptocurrencyApp | 43d20445590033a9e5114e77f7cd3a2ee7ae2db2 | ccb390060a80f61ab5146140e2803c171a663f98 |
refs/heads/master | <file_sep>using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor;
using UnityEditor.SceneManagement;
using System.Linq;
using System;
public class MyShader : ShaderGUI
{
private Material targetMat;
private GUIStyle style, bigLabelStyle, smallLabelStyle;
private const int bigFontSize = 16, smallFontSize = 11;
private string[] oldKeyWords;
private int effectCount = 1;
private Material originalMaterialCopy;
private MaterialEditor matEditor;
private MaterialProperty[] matProperties;
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
//변수 초기화
matEditor = materialEditor;
matProperties = properties;
targetMat = materialEditor.target as Material;
effectCount = 1;
oldKeyWords = targetMat.shaderKeywords;
style = new GUIStyle(EditorStyles.helpBox);
style.margin = new RectOffset(0, 0, 0, 0);
bigLabelStyle = new GUIStyle(EditorStyles.boldLabel);
bigLabelStyle.fontSize = bigFontSize;
smallLabelStyle = new GUIStyle(EditorStyles.boldLabel);
smallLabelStyle.fontSize = smallFontSize;
//
DrawProperty(0);
DrawLine(Color.grey, 1, 3);
//
GUILayout.Label("Select Effect", bigLabelStyle);
DrawToggle("Glow", "GLOW_ON", 1, 2);
DrawToggle("Negative", "NEGATIVE_ON", 3);
DrawToggle("greyscale", "GREYSCALE_ON", 4);
DrawToggle("gradient", "GRADIENT_ON", 5,15);
DrawToggle("radical gradient", "RADIALGRADIENT_ON", 16,21);
DrawToggle("pixelate", "PIXELATE_ON", 22);
DrawToggle("blur", "BLUR_ON", 23);
DrawToggle("shadow", "SHADOW_ON", 24,27);
DrawToggle("outline", "OUTLINE_ON", 28,30, () =>
{
MaterialProperty outline8dir = matProperties[30];
if (outline8dir.floatValue == 1) targetMat.EnableKeyword("OUTBASE8DIR_ON");
else targetMat.DisableKeyword("OUTBASE8DIR_ON");
});
DrawToggle("wave", "WAVEUV_ON", 31, 35);
DrawToggle("offset", "OFFSETUV_ON", 36,37);
DrawToggle("sine wave", "SINEWAVE_ON", 38,40);
//
DrawLine(Color.grey, 1, 3);
materialEditor.RenderQueueField();
}
private void DrawToggle(string inspectorDisplayName, string shaderKeyword, int startProperty, int endProperty = 0,Action action=null)
{
bool toggle = oldKeyWords.Contains(shaderKeyword);
bool ini = toggle;
GUIContent effectNameLabel = new GUIContent();
effectNameLabel.text = effectCount + "." + inspectorDisplayName;
toggle = EditorGUILayout.BeginToggleGroup(effectNameLabel, toggle);
effectCount++;
if (ini != toggle && !Application.isPlaying)
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
if (toggle)
{
targetMat.EnableKeyword(shaderKeyword);
EditorGUILayout.BeginVertical(style);
{
for (int i = startProperty; i <(endProperty != 0 ? endProperty : startProperty) + 1 ; i++)
{
DrawProperty(i);
}
if (action != null)
{
action();
}
}
EditorGUILayout.EndVertical();
}
else targetMat.DisableKeyword(shaderKeyword);
EditorGUILayout.EndToggleGroup();
}
private void DrawProperty(int index, bool noReset = false)
{
MaterialProperty targetProperty = matProperties[index];
EditorGUILayout.BeginHorizontal();
{
GUIContent propertyLabel = new GUIContent();
propertyLabel.text = targetProperty.displayName;
matEditor.ShaderProperty(targetProperty, propertyLabel);
if (!noReset)
{
GUIContent resetButtonLabel = new GUIContent();
resetButtonLabel.text = "R";
if (GUILayout.Button(resetButtonLabel, GUILayout.Width(20))) ResetProperty(targetProperty);
}
}
EditorGUILayout.EndHorizontal();
}
private void ResetProperty(MaterialProperty targetProperty)
{
if (originalMaterialCopy == null) originalMaterialCopy = new Material(targetMat.shader);
if (targetProperty.type == MaterialProperty.PropType.Float ||
targetProperty.type == MaterialProperty.PropType.Range)
{
targetProperty.floatValue = originalMaterialCopy.GetFloat(targetProperty.name);
}
else if (targetProperty.type == MaterialProperty.PropType.Color)
{
targetProperty.colorValue = originalMaterialCopy.GetColor(targetProperty.name);
}
}
private void DrawLine(Color color, int thickness = 2, int padding = 10)
{
Rect r = EditorGUILayout.GetControlRect(GUILayout.Height(padding + thickness));
r.height = thickness;
r.y += (padding / 2);
r.x -= 2;
r.width += 6;
EditorGUI.DrawRect(r, color);
}
}<file_sep># Changelog
처음 써보는 changelog. ( 참고 : https://keepachangelog.com/ko/1.0.0/ )
## [1.0.1] - 2021-08-27
- 시연영상 : https://youtu.be/ZUT8UF364n4
### Added
- gradient 효과 추가
- radical gradient 효과 추가
- pixelate 효과 추가
- blur 효과 추가
- shadow 효과 추가
- outline 효과 추가
- wave 효과 추가
- offset 효과 추가
- sine wave 효과 추가
### fixed
- 쉐이더 커스텀 인스펙터 코드수정
## [1.0.0] - 2021-08-13
- 시연영상 : https://youtu.be/L_HImGdrUMU
### Added
- 쉐이더 커스텀 인스펙터 제작
- glow 효과 추가
- negative 효과 추가
- greyscale 효과 추가
<file_sep># 쉐이더를 알아보자.
1. glow 효과
2. negative 효과
3. greyscale 효과
4. gradient 효과
5. radical gradient 효과
6. pixelate 효과
7. blur 효과
8. shadow 효과
9. outline 효과
10. wave 효과
11. offset 효과(?)
12. sine wave 효과
- 총 12가지 쉐이더를 구현하였고,
- 쉐이더 인스펙터를 커스텀제작 하였으며,
- 또한, 효과들이 중첩사용이 가능하도록 제작하였음.
시연영상 유튜브 링크 : https://youtu.be/ZUT8UF364n4
[](https://youtu.be/ZUT8UF364n4)
- 작업기간 : 2021.08월 초 ~ 2021.08월 말.
- 작업후기 : 쉐이더는 이제... 그만 알아보도록 하자.
| 2b5eaf1f3d02513d350c8aac83e6da393244cb4b | [
"Markdown",
"C#"
] | 3 | C# | cucuPOPs/ShaderStudy | 83b78b74a20ac6656a5bcc0cf85fd1602fb2d41b | 8777b2c1401da5a2ee8c0edb2bd8df28c0ba988d |
refs/heads/master | <file_sep>var Ticket = require('../models/ticket');
var Flight = require('../models/flight');
module.exports = {
create,
delete: deleteTicket
};
function create(req, res) {
var ticket = new Ticket({seat: req.body.seat, price: req.body.price, flight: req.params.id});
ticket.save(function(err){
if(err) {
console.log(err.message);
} else {
res.redirect('/flights/' + req.params.id);
}
})
}
function deleteTicket(req, res) {
Ticket.findById(req.params.id, function(err, ticket) {
var flight_id = ticket.flight; //to redirect to /flights/:id
ticket.delete(function(err, ticket){
if(err){
console.log('error deleting ticket')
} else {
res.redirect('/flights/' + ticket.flight);
}
});
});
} | f9ddcc91860c142c01bf6c028be8a22fe696111f | [
"JavaScript"
] | 1 | JavaScript | themichellemcguire/mongoose-flights | 30a0b10405c8dc73bb746c5a2842409941df5627 | 6e23a5452e4880db5a44a9b1317cd80ddeb2c2d0 |
refs/heads/master | <file_sep>from TimeApp.models import Projects, Time, Comments, CommentsForm, TimeForm, ProjectsForm, QuickTimeForm
from django.shortcuts import get_list_or_404, get_object_or_404, render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required, permission_required
import datetime
@login_required
def add_time(request):
message = ''
if request.method == 'POST':
form = TimeForm(request.POST)
if form.is_valid:
form.save()
form = TimeForm()
message = "time added!"
else:
form = TimeForm()
return render(request, 'TimeAppTemplates/add.html', {'form': form, "value": "Add entry to TimeApp", 'message': message})
@login_required
def quick_add_time(request):
message = ''
if request.method == 'POST':
form = QuickTimeForm(request.POST)
try:
if(request.POST['IO'] == '1'):
if form.is_valid:
t = form.save(commit=False)
t.t_in = datetime.datetime.now()
t.t_out = datetime.datetime.now()
t.t_user = User.objects.get(username=request.user.username)
t.save()
form = QuickTimeForm()
message = "Time started!"
elif(request.POST['IO'] == '2'):
form = QuickTimeForm()
message = "This function is yet to be defined"
except:
form = QuickTimeForm()
message = "Select in or out"
else:
form = QuickTimeForm()
return render(request, 'TimeAppTemplates/add.html', {'form': form, "value": "Add entry to TimeApp", 'message': message})
@login_required
def add_comment(request):
message = ''
if request.method == 'POST':
form = CommentsForm(request.POST)
if form.is_valid:
co = form.save(commit=False)
co.co_user = User.objects.get(username=request.user.username)
co.save()
form = CommentsForm()
message = "Comment added!"
else:
form = CommentsForm()
return render(request, 'TimeAppTemplates/add.html', {'form': form, "value": "Add entry to TimeApp", 'message': message})
@login_required
def add_projects(request):
message = ''
if request.method == 'POST':
form = ProjectsForm(request.POST)
if form.is_valid:
form.save()
form = ProjectsForm()
message = "Project added!"
else:
form = ProjectsForm()
return render(request, 'TimeAppTemplates/add.html', {'form': form, "value": "Add entry to TimeApp", 'message': message})
@login_required
def list_all(request):
list_all_comments = get_list_or_404(Comments.objects)
return render(request, 'TimeAppTemplates/listAll.html', {'list_all_comments' : list_all_comments})
<file_sep>from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'jcj.views.home', name='home'),
# url(r'^jcj/', include('jcj.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# TimeApp urls
url(r'^TimeApp/addtime/$', 'TimeApp.views.add_time', name='AddTime'),
url(r'^TimeApp/quickadd/$', 'TimeApp.views.quick_add_time', name='QuickAddTime'),
url(r'^TimeApp/addproject/$', 'TimeApp.views.add_projects', name='AddProject'),
url(r'^TimeApp/addcomment/$', 'TimeApp.views.add_comment', name='AddComment'),
# LoginApp urls
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'LoginAppTemplates/login.html'}, name = 'login'),
url(r'^logout/$', 'LoginApp.views.logout_view', name='logout'),
)
if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
<file_sep># Create your views here.
from django.contrib.auth import logout
from django.shortcuts import redirect
def logout_view(request):
logout(request)
return redirect('/login/')<file_sep>jcj
===
Django Project<file_sep>from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
from django import forms
from django.forms.widgets import DateTimeInput
# Create your models here.
# class Client(models.Model):
# cl_name = models.CharField("Client name", max_length=200)
# cl_address = models.CharField("Address", max_length=300)
# cl_postalcode = models.CharField("Postal code", max_length=10)
# cl_city = models.CharField("City", max_length=30)
# cl_orgnr = models.CharField("identification number", max_length=20)
class Projects(models.Model):
p_name = models.CharField("Project name", max_length=200)
p_desc = models.TextField()
p_user = models.ManyToManyField(User)
class Meta:
verbose_name = 'Project'
verbose_name_plural = 'Projects'
def __unicode__(self):
return self.p_name
class ProjectsForm(ModelForm):
class Meta:
model = Projects
class Time(models.Model):
t_in = models.DateTimeField()
t_out = models.DateTimeField(blank = True)
t_project = models.ForeignKey(Projects)
t_user = models.ForeignKey(User)
def t_duration(self):
if (self.t_out == None):
return None
else:
timeDiff = self.t_out - self.t_in
hours = timeDiff.seconds/3600
minuits = timeDiff.seconds%3600/60
return "%dh %dm" %(hours, minuits)
def is_checked_in(self):
if (self.t_in == self.t_out):
return True
else:
return False
# Form models for adding
class TimeForm(ModelForm):
class Meta:
model = Time
class QuickTimeForm(ModelForm):
IO = forms.ChoiceField(label="In/out", widget=forms.RadioSelect, choices=(('1', 'In'), ('2', 'Out')))
class Meta:
model = Time
fields = ['t_project']
class Comments(models.Model):
co_title = models.CharField("Comment title", max_length=50)
co_text = models.TextField("Comment")
co_date = models.DateTimeField(auto_now_add=True)
co_project = models.ForeignKey(Projects)
co_user = models.ForeignKey(User)
class Meta:
verbose_name_plural = 'Comments'
class CommentsForm(ModelForm):
class Meta:
model = Comments
exclude = ('co_user',)<file_sep>from TimeApp.models import Projects, Time, Comments
from django.contrib import admin
class TimeAdmin(admin.ModelAdmin):
list_display = ('t_user', 't_project', 't_in', 't_out', 't_duration', 'is_checked_in')
admin.site.register(Projects)
admin.site.register(Time, TimeAdmin)
admin.site.register(Comments) | f64a7d939c5b76492ad0bd2ca45abea5bb712331 | [
"Markdown",
"Python"
] | 6 | Python | jherrlin/jcj | 0c9267797d1da8b024bec689a5db7e87a8419064 | 6960505179718118932d2ab8508f7458a3306bfd |
refs/heads/master | <file_sep>import * as data from './nodes.js';
import { findASearchPath } from './a_search.js';
import { findCSPSearchPath } from './csp.js';
import { displayTotalAlgorithmExec, removeExecTime} from "./utils.js";
loadCities();
addActiveClass();
addActiveClassAlg();
Array.from(document.getElementsByClassName("algorithm-btn")).forEach(function(item) {
item.addEventListener('click', () => { setAlgorithm(item)});
});
var algorithm = "a_search";
function setAlgorithm(btn){
algorithm = btn.id;
}
function loadCities() {
//Setting the city buttons to be able to choose
//the starting point and the destination
for(let i=0; i< data.cities.length; i++)
{
let city = data.cities[i];
let cityButton = document.createElement("button");
let cityButtonText;
cityButton.value = city.name;
cityButton.name = city.name;
if(i==0) {
cityButton.className = "city-btn city-btn-active";
}else{
cityButton.className = "city-btn";
}
cityButtonText = document.createTextNode(city.name);
cityButton.appendChild(cityButtonText)
document.getElementById("from-city").appendChild(cityButton);
let cityButton2 = document.createElement("button");
let cityButtonText2;
cityButton2.value = city.name;
cityButton2.name = city.name;
if(i==0) {
cityButton2.className = "city-btn city-btn-active";
}else{
cityButton2.className = "city-btn";
}
cityButtonText2 = document.createTextNode(city.name);
cityButton2.appendChild(cityButtonText2)
document.getElementById("to-city").appendChild(cityButton2);
}
}
function addActiveClass(){
let header = document.getElementById("from-city");
let buttons = header.getElementsByClassName("city-btn");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
let current = header.getElementsByClassName("city-btn-active");
current[0].className = current[0].className.replace(" city-btn-active", "");
this.className += " city-btn-active";
});
}
let header2 = document.getElementById("to-city");
let buttons2 = header2.getElementsByClassName("city-btn");
for (let i = 0; i < buttons2.length; i++) {
buttons2[i].addEventListener("click", function() {
let current2 = header2.getElementsByClassName("city-btn-active");
current2[0].className = current2[0].className.replace(" city-btn-active", "");
this.className += " city-btn-active";
});
}
//Setting the search-btn event listener
document.getElementById("search-btn").addEventListener("click", findPath);
}
function addActiveClassAlg(){
let header = document.getElementById("algorithm-options");
let buttons = header.getElementsByClassName("algorithm-btn");
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
let current = header.getElementsByClassName("algorithm-btn-active");
current[0].className = current[0].className.replace(" algorithm-btn-active", "");
this.className += " algorithm-btn-active";
});
}
}
function findPath(){
//Firstly check if the cities are the same
let fromCityHeader = document.getElementById("from-city");
let fromCity = fromCityHeader.getElementsByClassName("city-btn city-btn-active")[0];
let toCityHeader = document.getElementById("to-city");
let toCity = toCityHeader.getElementsByClassName("city-btn city-btn-active")[0];
if(fromCity.value === toCity.value){
alert("Cannot calculate the route to the same city");
}else {
//Find the json objects of toCity and fromCity in the cities array
data.cities.forEach(city => {
if(city.name == fromCity.value){
fromCity = city;
}else if(city.name == toCity.value){
toCity = city;
}
})
let header = document.getElementById("algorithm-options");
let algorithms = header.getElementsByClassName("algorithm-btn");
let finder = {
a_search : (fromCity,toCity) => findASearchPath(fromCity, toCity),
csp : (fromCity,toCity) => {
removeExecTime();
let timeBegin = performance.now();
while(findCSPSearchPath(fromCity, toCity).isSolved()) ;
let timeFinal = performance.now();
displayTotalAlgorithmExec((timeFinal-timeBegin).toFixed(3));
}
}
finder[algorithm](fromCity, toCity);
}
}
<file_sep>//import * as data from "../resources/spain_routes.json"
let json = {};
const jsonFile = 'spain_routes.json';
const request = async () => {
const response = await fetch(`./resources/${jsonFile}`);
json = await response.json();
}
await request();
export const {cities, connections} = json;
<file_sep>// Containers
const finalPath = document.getElementById("final-path");
const execTime = document.getElementById("exec-time");
/*
Displaying the final path in html
*/
export function displayFinalPath(path){
for(let i=0; i<path.length; i++){
let city = path[i];
let pathItem = document.createElement("p");
let cityText = document.createTextNode(city.name);
pathItem.appendChild(cityText)
pathItem.title = city.name;
finalPath.appendChild(pathItem)
}
}
/*
Deleting the previous path from html
*/
export function removePrevPath(){
finalPath.textContent = ''
}
/*
Deleting the previous execution time from html
*/
export function removeExecTime(){
execTime.textContent = ''
}
/*
Displaying total time of the algorithm execution
*/
export function displayTotalAlgorithmExec(time){
let execItem = document.createElement("p");
let text = document.createTextNode("The algorithm took " + time + " milliseconds to be executed");
execItem.appendChild(text);
execTime.appendChild(execItem)
}
/*
Displaying total distance of the path
*/
export function displayTotaldistance(totalDistance){
let distItem = document.createElement("p");
let text = document.createTextNode("Total distance = " + totalDistance + "m");
distItem.appendChild(text);
finalPath.appendChild(distItem)
}<file_sep>import { cities, connections } from "./nodes.js";
import { displayFinalPath, removePrevPath, displayTotalAlgorithmExec, displayTotaldistance} from "./utils.js";
let citiesCopy = [];
let path = [];
let totalDistance = 0;
/*
fromCity and toCity are json city objects from the cities array
*/
export function findASearchPath(fromCity, toCity){
path.splice(0, path.length);
removePrevPath();
// console.log("fromCity", fromCity)
citiesCopy = JSON.parse(JSON.stringify(cities)); //
console.log(citiesCopy);
//From the starting point, calculate the total cost of the route for each child on the way
//If the child was already checked, set the 'checked' attribute to true
let timeBegin = performance.now()
calculateHeuristicValueForEachCity(toCity);
// console.log(citiesCopy)
// console.log(cities)
//Setting the checked value to true of the first from city, using the findCityInObj array
findCityObjInTheArray(fromCity.name);
// console.log("path", path);
path.push(fromCity)
let child = findBestChild(fromCity, toCity);
path.push(child.city);
// console.log(toCity.name)
totalDistance = 0;
while(child.city.name !== toCity.name){
child = findBestChild(child.city, toCity);
if(child != null) {
// console.log("child: ", child)
path.push(child.city);
totalDistance += child.city.distance;
// console.log("path: ", path);
}else{
break;
}
}
let timeFinal = performance.now();
//console.log("It took " + (timeFinal - timeBegin ) + " miliseconds");
displayFinalPath(path);
displayTotalAlgorithmExec((timeFinal-timeBegin).toFixed(3))
displayTotaldistance(totalDistance);
console.log("Final path", path)
console.log(totalDistance);
// Emptying arrays:
citiesCopy.splice(0, citiesCopy.length);
// console.log("citiesCopy", citiesCopy)
}
/*
This function assigns heuristic values for each city before finding the best path
*/
function calculateHeuristicValueForEachCity(toCity){
citiesCopy.forEach(city => {
city.heuristic = heuristicDistance(
city.latitude,
city.longitude,
toCity.latitude,
toCity.longitude
)
})
}
/*
Finding the fastest path of the city children
*/
function findBestChild(city, toCity){
let children = [];
connections.forEach(connection => {
if(connection.from == city.name){
let cityObj = findCityObjInTheArray(connection.to)
if(cityObj != null) {
let child = {
"city": {...cityObj, "distance": connection.distance },
"cost": calculateTotalCost(cityObj.heuristic, connection.distance)
}
children.push(child);
}
}
})
//console.log(children)
return children.length != 0 ? findMinCostChild(children, toCity) : null;
}
/*
Finding the city in the array, this function is used to find children of the city
It is also setting the checked value to true, so that we don't loop in the graph
*/
export function findCityObjInTheArray(cityName){
let filteredCity = citiesCopy.filter(city => {
if(!city.checked) {
if (city.name == cityName) {
city.checked = true;
return city;
}
}
});
return filteredCity ? filteredCity[0] : null;
}
function calculateTotalCost(heuristic, distance){
return heuristic != 0? heuristic + distance: 0;
}
function findMinCostChild(children, toCity){
let min = children[0].cost;
let child = children[0];
for (let i = 1; i < children.length; i++) {
if(children[i].cost < min){
min = children[i].cost;
child = children[i]
}
}
return child;
}
function heuristicDistance(lat1, lon1, lat2, lon2){
let R = 6371; // km
let dLat = toRad(lat2 - lat1);
let dLon = toRad(lon2 - lon1);
lat1 = toRad(lat1);
lat2 = toRad(lat2);
let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
let d = R * c;
return d;
}
function toRad(Value) {
return Value * Math.PI / 180;
}<file_sep># Search algorithms
Project to explore different search-path algorithms within a set of routes given in a json file.
## How to
In order to execute/run the program, you must setup a local server and execute the project as a plain/static web.
Or you can just check it in this GitHub Pages (from this repository):
https://javierbmm.github.io/search-algorithms/
## About
### A*
From https://www.educative.io/edpresso/what-is-the-a-star-algorithm
*A * algorithm is a searching algorithm that searches for the shortest path between the initial and the final state. It
is used in various applications, such as maps.*
*In maps the A\* algorithm is used to calculate the shortest distance between the source (initial state) and the
destination
(final state).*
The algorithm has three parameters: the costs of moving from the initial cell to current cell, the heuristic value, and
the sum of the two parameters. The algorithm will then rearrange the distances from the shortest to longest distance, at
every node visited. It also allows us to cut execution costs by not having to visit every node in the map. This is
because the duration between cities of the two places are taken into consideration, not the closest one.
#### Heuristic value
As mentioned before, A* algorithms have heuristics Euclidean distance values from itself to the node destination. In our
program, we allow the user to choose both the source and destination city. We were asked to calculate the distances in a
straight line, so we chose to do the calculations as Euclidian, in order to provide an estimate that is less or equal to
the actual cost of the path.
### CSP
Standard search problems can search in a space of states, while constraint search problems serve as a generally proposed
heuristic. Constraint satisfaction problems are made up of a finite set of variables that represent the finite domain of
values, and a set of constraints. Each variable in this space must have to satisfy constraints that they are given. We
used the backtracking algorithm in order to loop through each set, in our solution space, checking at each branch, if
the path meets the constraints we specify in our CSP.
#### Constraints
The constraints that we chose to consider for our CSP was that we should not go through the same city twice and to
eliminate loops. Another constraint was to not travel more than the sum of all the distances calculated in the map. We
want to find a path that is less than or equal to the best path cost so we cannot take distances that are larger than
needed.
#### Heuristic value
In the case of our implementation, we calculated the heuristic distance between the node and the destination node as the
straight line between them based on the longitude and latitude values. | dd45e1343d582f7fef5e1c4f811f2bc9d5cecbc7 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | javierbmm/search-algorithms | 1785c451e24630893bc2b483e4320449e463d6d2 | e04488ae5455f92e215771453c97ef7ad9caee60 |
refs/heads/master | <repo_name>karbonara/react-learn<file_sep>/src/components/Nav.js
import React from 'react'
function Nav() {
return (
<nav className="container nav">
<ul className="nav__item-title">
<li><a className="nav__item-link" href="...">Магазины</a></li>
<li><a className="nav__item-link" href="...">Акции</a></li>
<li><a className="nav__item-link" href="...">Доставка и оплата</a></li>
</ul>
<a href="..."><img src="https://i.imgur.com/98oIJgd.png" alt="..." width="102"></img></a>
<div>
<p>Санкт-Петербург, <br />
ул Большая Конюшенная, д 19</p>
</div>
<ul className="nav__item-title">
<li><a href="..."><img src="https://i.imgur.com/XqgrtnX.png" alt=".."></img></a></li>
<li><a href="..."><img src="https://i.imgur.com/WqsGJ9n.png" alt="..."></img></a></li>
<li><a href="..."><img src="https://i.imgur.com/UjId0on.png" alt="..."></img></a></li>
</ul>
</nav>
)
}
export default Nav<file_sep>/src/components/Categories.js
import React from 'react'
function Categories() {
return (
<div className="container">
<ul className="categories__items">
<li className="categories__item">
<div>
<p>Автохимия</p>
<a href="...">Перейти ></a>
</div>
<img src="..." alt="..."></img>
</li>
<li className="categories__item">
<div>
<p>Автохимия</p>
<a href="...">Перейти ></a>
</div>
<img src="..." alt="..."></img>
</li>
<li className="categories__item">
<div>
<p>Автохимия</p>
<a href="...">Перейти ></a>
</div>
<img src="..." alt="..."></img>
</li>
</ul>
</div>
)
}
export default Categories<file_sep>/src/components/Article.js
import React from 'react';
function Article() {
return (
<div className="nav__menu">
<div className="container square__main">
<ul className="nav__item-title nav__menu-items">
<li className="nav__menu-item"><a href="...">Каталог Запчастей</a></li>
<li className="nav__menu-item"><a href="...">Каталог ТО</a></li>
<li className="nav__menu-item"><a href="...">Шины</a></li>
<li className="nav__menu-item"><a href="...">Диски</a></li>
<li className="nav__menu-item"><a href="...">Аккумуляторы</a></li>
<li className="nav__menu-item"><a href="...">Автомасла</a></li>
<li className="nav__menu-item"><a href="...">Автолампы</a></li>
<li className="nav__menu-item"><a href="...">Аксессуары</a></li>
</ul>
</div>
</div>
)
}
export default Article<file_sep>/src/components/App.js
import React from 'react'
import '../index.css'
import 'bootstrap/dist/css/bootstrap.min.css';
import Article from './Article'
import Banner from './Banner'
import Search from './Search'
import Categories from './Categories'
import Nav from './Nav'
import Popular from './Popular';
import FooterNav from './FooterNav';
import BannerFooter from './BannerFooter';
function App() {
return (
<div>
<Nav />
<Article />
<Banner />
<Search />
<Categories />
<Categories />
<Popular />
<BannerFooter />
<Popular />
<FooterNav />
</div>
)
}
export default App<file_sep>/src/components/BannerFooter.js
import React from 'react'
function BannerFooter() {
return (
<div className="container">
<img src="https://i.imgur.com/nAkxdyF.png" width="1140" alt="..."></img>
</div>
)
}
export default BannerFooter<file_sep>/src/components/Search.js
import React from 'react'
function Search() {
return (
<div className="container">
<ul className="nav__item-title search__items">
<li><a className="search__item" href="...">Поиск по Vin</a></li>
<li><a className="search__item" href="...">Поиск по марке</a></li>
<li><a className="search__item" href="...">Поиск по названию товара</a></li>
<li><a className="search__item" href="...">Поиск по артиклу</a></li>
</ul>
</div>
)
}
export default Search<file_sep>/src/components/Section.js
import React from 'react'
function Section() {
return (
<div className="container">
<h2>React</h2>
</div>
)
}
export default Section<file_sep>/src/components/Popular.js
import React from 'react'
function Popular() {
return (
<div className="container popular">
<h2>Популярные товары</h2>
<ul className="breadcrumb">
<li><a href="..">запчасти</a></li>
<li><a href="..">автохимия</a></li>
<li><a href="..">шины и диски</a></li>
<li><a href="..">автоэлектроника</a></li>
<li><a href="..">инструменты</a></li>
<li><a href="..">аксессуары и другое</a></li>
</ul>
<ul className="categories__items popular__items">
<li className="popular__item">
<div className="banner__stock">
<p>Sale</p>
</div>
<img className="popular__like-img" src="https://i.imgur.com/g9BzJgV.png" alt="..."></img>
<img src="https://i.imgur.com/lzhYjan.png" alt=".."></img>
<h2>Ремень</h2>
<p>440Р</p>
<div>
<img src="..." alt="..."></img>
</div>
</li>
<li className="popular__item">
<img className="popular__like-img" src="https://i.imgur.com/g9BzJgV.png" alt="..."></img>
<img src="https://i.imgur.com/lzhYjan.png" alt=".."></img>
<h2>Ремень</h2>
<p>440Р</p>
<div>
<img src="..." alt="..."></img>
</div>
</li>
<li className="popular__item">
<img className="popular__like-img" src="https://i.imgur.com/g9BzJgV.png" alt="..."></img>
<img src="https://i.imgur.com/lzhYjan.png" alt=".."></img>
<h2>Ремень</h2>
<p>440Р</p>
<div>
<img src="..." alt="..."></img>
</div>
</li>
<li className="popular__item">
<img className="popular__like-img" src="https://i.imgur.com/g9BzJgV.png" alt="..."></img>
<img src="https://i.imgur.com/lzhYjan.png" alt=".."></img>
<h2>Ремень</h2>
<p>440Р</p>
<div>
<img src="..." alt="..."></img>
</div>
</li>
</ul>
</div>
)
}
export default Popular | e9b36d75ba8f7f5e9f6f161a54ccf09c8c2d55e1 | [
"JavaScript"
] | 8 | JavaScript | karbonara/react-learn | 525a8091a37a0cd1f3ab9e90d79116c76e228daf | aaca26a9064373707c500c2ae6de0f4e53e7a0de |
refs/heads/master | <repo_name>gep13/CakeVstsTest<file_sep>/Build/build.cake
#tool "nuget:?package=NUnit.ConsoleRunner&version=3.2.1"
#tool "nuget:?package=GitVersion.CommandLine"
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var zipDir = Argument("zipDir","./");
var outputDirectory = Argument("OutputDirectory", "./");
var buildScriptsDirectory = Argument("BuildScriptsDirectory", "./");
var majorVersion = Argument("MajVer", "1");
var minorVersion = Argument("MinVer", "2");
var patchNumber = Argument("Patch", "3");
GitVersion versionInfo = null;
//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
Information("Cleaning...");
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
Information("Restoring nuget packages...");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
Information("Building Solution...");
Information("ZipDir: " + zipDir);
Information("OutputDirectory: " + outputDirectory);
Information("MajorVersion: " + majorVersion);
Information("MinorVersion: " + minorVersion);
Information("Patch: " + patchNumber);
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
Information("Running Unit Tests...");
versionInfo = GitVersion(new GitVersionSettings{ OutputType = GitVersionOutput.Json });
});
Task("Patch-Assembly-Info")
.Does(() =>
{
Information("Patching Assembly Info...");
});
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Default")
.IsDependentOn("Run-Unit-Tests");
Task("Build-Nuget")
.IsDependentOn("Run-Unit-Tests")
.Does(() =>
{
Information("Running Unit Tests...");
});
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);
| 41d690ece202c1de5508e2abe502d3bac19c4694 | [
"C#"
] | 1 | C# | gep13/CakeVstsTest | a00a9a8ae6540317da4592d898825f8513ef535a | 4d6d78bdbef9f0e1b367dcfc3b35d4f265f13bd4 |
refs/heads/master | <file_sep>import { gsap, TimelineLite, TweenLite,Circ } from 'gsap/all';
import { isMobile } from 'mobile-device-detect';
function rotatingLogo() {
const logo = document.querySelectorAll( '.logo' );
logo.forEach( ( el, i ) => {
const iconLogo = el.firstElementChild;
const iconBackLogo = el.lastElementChild;
const duration = 1.5;
gsap.set( iconBackLogo, {
rotationY: 180
} )
const timeline = new TimelineLite( {
paused: true,
reversed: true,
ease: Circ.easeInOut
} )
.to( iconLogo, duration, {
rotationY: 360
}, 'rotate' )
.to( iconBackLogo, duration, {
rotationY: -180
}, 'rotate' )
if ( !isMobile ) {
el.addEventListener( 'mouseenter', ( e ) => {
e.preventDefault();
timeline.reversed() ? timeline.play() : null
} );
el.addEventListener( 'mouseleave', ( e ) => {
e.preventDefault();
TweenLite.delayedCall( .3, function () {
timeline.reverse();
} );
} );
} else {
const tapEvent = new Hammer.Manager( el );
const Tap = new Hammer.Tap( {
time: 250
} );
tapEvent.add( Tap );
tapEvent.on( 'tap', ( e ) => timeline.reversed() ? timeline.play() : timeline.reverse() );
}
} );
}
export function logo() {
rotatingLogo();
}
<file_sep>import 'hammerjs';
import { gsap, TimelineMax, Quad, ScrollToPlugin } from 'gsap/all';
gsap.registerPlugin( ScrollToPlugin );
function nav() {
const app = document.querySelector( '#app' );
const buttonNav = document.querySelectorAll('.button-nav');
const nav = document.querySelector('nav[role="navigation"]');
const navClass = 'open';
const duration = parseFloat(window.getComputedStyle(nav, null).getPropertyValue('transition-duration') ) / 2;
buttonNav.forEach((el, i) => {
/* BURGER MENU ICON ANIMATION */
const iconRects = el.querySelectorAll('rect');
const heightGroup = iconRects[i].parentElement.getBBox().height;
const heightLine = parseInt(iconRects[i].attributes.height.nodeValue);
const spaceLines = parseInt(heightLine + (heightGroup - heightLine * 3) / 2);
const timeline = new TimelineMax( { paused: true, reversed: true, ease: Quad.easeInOut } )
.to( iconRects[0], duration, { y: spaceLines }, 'position' )
.to(iconRects[2], duration, {y: -spaceLines},'position')
.to(iconRects[0], duration, {rotation: 135,transformOrigin: '50% 50%'},'rotate')
.to(iconRects[2],duration,{rotation: 225,transformOrigin: '50% 50%'},'rotate')
.to(iconRects[1],duration,{scaleX: 0,transformOrigin: '50% 50%'},'rotate');
nav.classList == navClass ? timeline.seek('-=0', false).reversed(!timeline.reversed()) : null;
const navEvents = () => {
timeline.reversed() ? timeline.play() : timeline.reverse();
nav.classList.toggle( navClass );
el.getAttribute( 'aria-expanded' ) === 'false' ? el.setAttribute('aria-expanded', 'true') : el.setAttribute('aria-expanded', 'false');
};
/// PRESS EVENT
const pressEvent = new Hammer.Manager(el);
const Press = new Hammer.Press({time: 0 });
pressEvent.add(Press);
pressEvent.on('press', (e) => navEvents());
/// KEYBOARD EVENT
document.addEventListener('keydown', (e) => el === document.activeElement && (e.code === 'Enter' || e.code === 'Space') ? navEvents() : null);
/// SWIPE EVENT
const recognizer = {
recognizers: [
[ Hammer.Swipe,{direction: Hammer.DIRECTION_HORIZONTAL} ]
]
};
let deltaX = 0;
const swipeEvent = new Hammer.Manager(nav.firstElementChild, recognizer);
const Swipe = new Hammer.Swipe();
swipeEvent.add(Swipe);
swipeEvent.on('swipe', (e) => {
deltaX = deltaX + e.deltaX;
const right = app.classList.contains( 'right-nav' );
e.offsetDirection === 2 && !(right) || e.offsetDirection === 4 && right ? navEvents() : null;
});
const links = nav.querySelectorAll('a');
const body = document.querySelector('body');
const sizeMediaQueries = window.getComputedStyle(body, ':before').getPropertyValue('content').split('"').join('');
const mq = window.matchMedia(sizeMediaQueries);
links.forEach((elems, i) => {
////// smoothScroll when desktop
////// close menu when mobile
elems.addEventListener('click', (e) => {
if (mq.matches) {
e.preventDefault();
gsap.to(window, { duration: duration,scrollTo: elems.getAttribute('href'), ease: Quad });
} else {
navEvents();
}
});
/// SWIPE EVENT
const swipeLinks = new Hammer.Manager(elems, recognizer);
swipeLinks.on('swipe', (e) => {
e.srcEvent.preventDefault();
return false;
});
/// KEYBOARD EVENT
document.addEventListener('keydown', (e) => {
if (elems === document.activeElement) {
if (e.code === 'Escape') {
navEvents();
el.focus();
}
e.code === 'Space' ? e.preventDefault() : null;
}
});
});
});
}
export function navigation() {
nav();
}
<file_sep>'use strict';
import '../assets/fonts/stylesheet.css';
import './styleguide.scss';
import { navigation } from './../components/nav/nav';
import { utils } from './../assets/scripts/utils';
import { logo } from './../components/header/header';
utils();
logo();
navigation();
function hsl() {
const sass = require( 'sass-extract-loader!./styleguide.scss' );
const globalSass = sass.global;
const colorValues = Object.keys( globalSass.$colors.value );
document.querySelectorAll( '.styleguide-colors p' ).forEach( ( el, i ) => {
const color = colorValues[i];
switch (color) {
case 'primary':
const huePrimary = globalSass.$colors.value.primary.value.hue.value;
const saturationPrimary = globalSass.$colors.value.primary.value.saturation.value;
const lightnessPrimary = globalSass.$colors.value.primary.value.lightness.value;
el.innerHTML = `hsl(${huePrimary}, ${saturationPrimary}%, ${lightnessPrimary}%)`;
break;
case 'dark':
const hueDark = globalSass.$colors.value.dark.value.hue.value;
const saturationDark = globalSass.$colors.value.dark.value.saturation.value;
const lightnessDark = globalSass.$colors.value.dark.value.lightness.value;
el.innerHTML = `hsl(${hueDark}, ${saturationDark}%, ${lightnessDark}%)`;
break;
case 'neutral':
const hueNeutral = globalSass.$colors.value.neutral.value.hue.value;
const saturationNeutral = globalSass.$colors.value.neutral.value.saturation.value;
const lightnessNeutral = globalSass.$colors.value.neutral.value.lightness.value;
el.innerHTML = `hsl(${hueNeutral}, ${saturationNeutral}%, ${lightnessNeutral}%)`;
break;
case 'light':
const hueLight = globalSass.$colors.value.light.value.hue.value;
const saturationLight = globalSass.$colors.value.light.value.saturation.value;
const lightnessLight = globalSass.$colors.value.light.value.lightness.value;
el.innerHTML = `hsl(${hueLight}, ${saturationLight}%, ${lightnessLight}%)`;
break;
}
} );
}
hsl();
///////////////////////////////
import { categories, iconClasses } from '../assets/scripts/utils.js';
const catIcons = [categories[0], categories[1], categories[2] + "Fontface", categories[2] + "Unicode", categories[3] + "Fontface", categories[3] + "Unicode"];
const wrapClass = "wrap-icon";
const pages = document.querySelectorAll( '.styleguide-pages a' );
const urls = [];
pages.forEach( ( page ) => {
urls.push( `/${page.innerHTML}` );
} );
urls.push( window.location.pathname );
urls.forEach( ( url, indexRequest ) => {
requestUrls( url, indexRequest );
});
function requestUrls( url, indexRequest ) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
domParser( e, indexRequest );
} else {
console.error(xhr);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send( null );
}
function domParser(e, indexRequest) {
const parser = new DOMParser();
const doc = parser.parseFromString( e.target.responseText, "text/html" );
const icons = doc.querySelectorAll( iconClasses );
noDuplicate( icons, indexRequest );
}
const arrIcons = [];
function noDuplicate(icons, indexRequest) {
icons.forEach( ( icon ) => {
arrIcons.push( icon.outerHTML.replace( /\s+/g, ' ' ).trim() );
} );
if ( indexRequest === urls.length - 1)
{
const noDuplicateIcons = new Set( arrIcons );
noDuplicateIcons.forEach( ( icon ) => {
icon = document.createRange().createContextualFragment( icon ).firstElementChild;
const wrapper = document.createElement( 'div' );
wrapper.className = wrapClass;
document.querySelectorAll('.no-icon').forEach(el => el.remove());
icon.parentNode.insertBefore(wrapper, icon);
wrapper.appendChild( icon );
nameIcon( icon );
iconsCategory( wrapper, icon );
} );
}
}
function nameIcon(icon) {
const txt = document.createElement( 'p' );
icon.after( txt );
if (icon.classList.contains(categories[0]+'-icon'))
{
const linkHref = icon.querySelector( 'use' ).getAttribute( 'xlink:href' );
txt.innerHTML = linkHref.substring(linkHref.indexOf('#') + 1);
}
else if ( icon.classList.contains( categories[1]+'-icons' ) )
{
txt.innerHTML = icon.innerHTML;
}
else if ( icon.classList.contains( categories[2] ) || icon.classList.contains( categories[3] ) && icon.tagName === "I")
{
const classes = icon.getAttribute( 'class' );
txt.innerHTML = classes.substring(classes.indexOf('-') + 1);
}
else if ( icon.classList.contains( categories[2]+'-icon' ) || icon.classList.contains( categories[3] ) && icon.tagName === "svg" )
{
txt.innerHTML = icon.querySelector('text').getAttribute('data-unicode');
}
txt.innerHTML = `\"${txt.innerHTML}\"`;
}
function iconsCategory( wrapper, icon ) {
const str = icon.outerHTML.replace( /\s+/g, ' ' ).trim();
const appendWrapper = ( cat ) => {
const category = document.querySelector( `.styleguide-icons--${cat}` );
category.append( wrapper );
};
str.includes( catIcons[0] ) ? appendWrapper(catIcons[0]) : null;
str.includes( catIcons[1] ) ? appendWrapper(catIcons[1]) : null;
str.includes( categories[2]+' '+categories[2]+'-' ) ? appendWrapper(catIcons[2]) : null;
str.includes( categories[2]+'-icon' ) ? appendWrapper(catIcons[3]) : null;
str.includes( categories[3] + ' ' + categories[3] + '-' ) ? appendWrapper(catIcons[4]) : null;
str.includes( categories[3] + '\"' ) ? appendWrapper( catIcons[5] ) : null;
}
<file_sep>
# Styleguide starter
A starter and styleguide for any quick setup of HTML/CSS components.
You can have an overview of what the styleguide looks like at the start with this [demo](https://www.marvinx.com).
### Tech
* [webpack](https://webpack.js.org/) - Module bundler
* [pugJS](https://pugjs.org) - Clean, whitespace sensitive syntax for writing HTML
* [SCSS](https://sass-lang.com/) - CSS preprocessor
### Installation
Install all your dependencies:
```sh
$ npm install
```
Start the application:
```sh
$ npm start
```
Create a non minified bundle of your app:
```sh
$ npm run build
```
Build a minified and optimized final bundle:
```sh
$ npm run build:prod
```
### Components
#### Colors
In `variables.scss`, pick your main color in hsl values and play with the lightness and the saturation to get your palette color. You can after play with that color with these three sass functions:
* `lightness(var(--$color), $multiplier)`
* `saturation(var(--$color), $multiplier)`
* `alpha(var(--$color), $opacity)`
#### Typography
You can use a google font `fontFamilyName` or a local custom font `fontCustomName` on your main project. Params it in `default.pug`
#### Titles
In `titles.scss`, you can style titles `h1, h2, h3, h4, h5, h6` or use class `.style-h#{nbr}` on it.
#### Icons
Find here all icons used into your project.
Icons are automatically generate in `styleguide.js`.
`font-awesome` `material-icons` and `glyphicon` librairies are already included and you can use it with this pug mixin: `+icon("nameIcon","nameLibrary")`.
You can also use a custom svg icon in `assets/icons/nameIcon.svg`. That will create a `sprite.svg` that you can call into your pug pages simply this way: `+icon("nameIcon")`.
#### Breakpoints
In `breakpoints.scss`, find differents mixins:
* `breakpoints-min($breakpoint)`
* `breakpoints-max($breakpoint)`
* `breakpoints-between($breakpoint)`
to play with differents devices points.
#### Grid
Find in `grid.scss`, a simple grid system which work with class `.grid` as a container.
Add an additionnal class to it to put the number of wanted columns `.col--$numberCol`.
Inside it, put other children with the class `.col`. You can nested this system.
#### Menu
By default, the main layout is a left nav with a burger menu.
On container `#app`, you can change it by putting class `.right-nav` to have the same system but in right side.
You can also use class `.top-nav` and add a top bar navigation system.
#### Buttons
The class `.btn` can be use on a link or a button. Put additionnals classes to style it: `.radius` `.outlined` `.rounded`
#### Tags
As buttons, put additionnals classes to `.tag` class: `.radius` `.outlined` `.rounded`.
#### Tooltip
Base on the [script van11y-accessible-simple-tooltip-aria](https://github.com/nico3333fr/van11y-accessible-hide-show-aria), you can add any tooltip with the class `.js-simple-tooltip`.
Add an additionnal class to set the position of your tooltip:
* `.tooltip--top`
* `.tooltip--right`
* `.tooltip--bottom`
* `.tooltip--left`
* `.tooltip--top-left`
* `.tooltip--top-right`
* `.tooltip--bottom-left`
* `.tooltip--bottom-right`
All tooltips are accessible and visible on focus.
#### Forms
All the forms elements are styled with css only in `forms.scss` at the exception of `input="file"` (simple javascript script) and select dropdown.
Last ones work with Jquery, and the plugin [select2.js](https://select2.org/getting-started/installation).
That make those selects entirely accessibles (keyboard navigation, focus...)
#### Images
Call any jpg, png or webp images like this in your pug files: `require(imgDir+"image.ext").src`.
If you want to use a data-uri image, just call it this way: `require(imgDir+"image.ext").placeholder`.
Thanks to `responsive-loader` package in `webpack.config.js`, we automatically generate the differents images in the good srcset dimensions.
You can also params the quality of your images with `ImageminPlugin`.
If you add the class `.lazyload` and replace src attribute by data-src to any images or elements with a background-image in css, you can lazyload those images by using included [lazysizes](https://www.npmjs.com/package/lazysizes) script.
| bd0aa382e6f9c22cced2d864b9999134ebaa2a14 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | MarvinxX/portfolio | 2a79a1560ec18fe738ac5825d40cf3bd4b0df1ea | 88daae44bb9ddd0927a658d319593cd03aab4210 |
refs/heads/master | <repo_name>liamyancy/Yancy_L_Wood_J_DynamicTeamPage<file_sep>/README.md
# Dynamic Team Page
This is a dynamic team bio page, designed to be in the context of a larger studio site with our own style. You will be able to select each team member to display a bio about that specific member.
### Getting Started
This is a small HTML / CSS / JavaScript team build.
### Prerequisites
All you need is a text editor.
## Authors
1. <NAME>
2. <NAME>
## Liscence
This project is liscenced under the MIT liscence.
<file_sep>/js/main.js
(() => {
let teamImages = document.querySelectorAll(".imageContainer"),
houseDescription = document.querySelector(".memberBio");
const bioData = [
["john", `My name is <NAME>. I am 20 years old and come from Blue Mountains Ontario Canada. I like playing
soccer, videogames and listening to music. I am currently attending Fanshawe College and am enrolled in
the Interactive Media Design program. After the program ends, I aim to be a web developer as far as employment. `],
["liam", `My name is <NAME>, and I am 18 years old. I am from Ingersoll Ontario and my hobbies include
soccer, hanging out with friends, and playing games such as League of Legends, CS:GO, and Rocket League. I
Currently go to school at Fanshawe College in Downtown London, aspiring to be a Web Developer upon graduation. `]
];
function showBio() {
houseDescription.textContent = `${bioData[this.dataset.offset][1]}`;
classList.add("memberInfo");
}
teamImages.forEach(button => button.addEventListener("click", showBio));
})(); | 4692d01005c7a67ef3699d283a2ff2628900785f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | liamyancy/Yancy_L_Wood_J_DynamicTeamPage | 4e2536071470ad0c913ec30a668c384c34bd61dd | 2f4da9c41bed150afd06a8171c79971bab51b619 |
refs/heads/main | <repo_name>MichaelABartlett/addressBook<file_sep>/README.md
# addressBook
practice fetch and running class 13 address book assignment
<file_sep>/mainWithExtra.js
console.log('Loading main.js');
// making a promise that I will do this when I can
// let fetchPromise = fetch("https://randomuser.me/api/");
// let jsonPromise = fetchPromise.then(function(response){
// // do something with the response
//
// this contains the respones headers
// extract the json from the response, (unpack the response)
// return response.json();
// use .blob() if expecting bianary date
// use .text() if expecting text
// });
// this is the actual response you were expecting
// jsonPromise.then(function(json){
// // do something with the json payload
// })
// shorter version below
// ******************************************************
// this is client side code
// **********************************************************8
fetch("https://randomuser.me/api/?results=3") // ?results=5 - this number represents how many name to process
.then(function(response){
// do something with the result
// extract the json from the response
console.log('response status: ', response.status)
return response.json();
}).then(function(json){
// do something with the json payload
// this is unpacking the json so it can be used
console.log("response payload: ", json)
processJson(json); // passing the (json) to the addToDom function
})
// *******************************************************************************
// if you want to do this in 'node'
// you will need to use axios node library
// put 'axios' in the place of 'fetch'
// *********************************************************************************
// processJson = function(json){
// //console.log(json.results[0].name.first) // prints just one first name
// for(let i = 0; i<json.results.length; i++){
// console.log(json.results[i].name.first);
// }
// }
function handleSubmit() {
//let toggleDisplay = document.getElementsByid("address");
//toggleDisplay.getElementsByClassName.color = red;
var toggleDisplay = document.querySelectorAll(".address");
for(let i = 0; i < toggleDisplay.length; i++){
if (toggleDisplay[i].style.display === "none") {
toggleDisplay[i].style.display = "block";
} else {
toggleDisplay[i].style.display = "none";
}
}
}
// ***************** create new elements *********************
let newLi = document.createElement("li");
let newSpan = document.createElement("span");
let newP = document.createElement("p");
let newDiv = document.createElement("div");
let newImg = document.createElement("Img")
//let addLi = document.getElementById("main-body").getElementsByTagName("ul")[0];
let theUl = document.getElementById("people-list");
const body = document.body
const div = document.createElement('div')
let theName = document.querySelector('#the-name')
let processJson = function(json){
// loop through the results array , and process one contact at a time
for(let i = 0; i<json.results.length; i++){
let contact = json.results[i]; // creates a variable for each individual contact ' person' in this case
processContact(contact);
}
}
// process one contact at a time and update the dom with that contact info
let processContact = function(contact){
let firstName = contact.name.first;
let lastName = contact.name.last;
let email = contact.email;
let city = contact.location.city;
let state = contact.location.state;
//let street = `${contact.location.street.number} ${contact.location.street.name}`;
let street = contact.location.street.number + ' ' + contact.location.street.name;
let picture = contact.picture.thumbnail;
let newLi = document.createElement("li");
let newSpan = document.createElement("span");
let newP = document.createElement("p");
let newA = document.createElement("a");
let newDiv = document.createElement("div");
let newImg = document.createElement("img")
let theUl = document.getElementById("people-list");
let newHr = document.createElement("hr");
theUl.appendChild(newLi);
newLi.appendChild(newSpan)
newSpan.append(firstName,' ',lastName,);
newLi.appendChild(newDiv)
newDiv.appendChild(newImg)
newImg.src = picture
newImg.append(picture)
newLi.appendChild(newP)
newP.append('Email: ', email)
newLi.appendChild(newA);
newA.append("Address: ",street ,' , ',city, ' , ',state)
//newA.classList.add("address")
newA.setAttribute('class','address')
newLi.appendChild(newHr);
}
// *************************************************************************
// let newElement = document.createElement('li')
// newElement.textContent = 'here i there'
// let list = document.getElementById('people-list')
// list.appendChild(newElement)
// or
// list.insertBefore(newElement,list.firstElementChild)
// **********************************************************************************
//theName.innerHTML = (firstName + ' ' + lastName) // done with creating a variable and passing it in
//document.querySelector('#e-mail').innerHTML = email // done without creating a variable
//document.querySelector('.little-pic').src = picture
//body.append(firstName,' ',lastName) // append is a little more flexable than appendchild
// make the request and then move on
// if using node you need to use
// axios
// use axios instead of fetch
// assignment
// list of people in address book in the DOM , nimimum info
// make ul and add people to li
// make a hover make other information show up, add event listner to li to show additional info
// look at todo app week 3<file_sep>/main.js
console.log('Loading main.js');
// making a promise that I will do this when I can
// let fetchPromise = fetch("https://randomuser.me/api/");
// let jsonPromise = fetchPromise.then(function(response){
// // do something with the response
//
// this contains the respones headers
// extract the json from the response, (unpack the response)
// return response.json();
// use .blob() if expecting bianary date
// use .text() if expecting text
// });
// this is the actual response you were expecting
// jsonPromise.then(function(json){
// // do something with the json payload
// })
fetch("https://randomuser.me/api/?results=3") // ?results=5 - this number represents how many name to process
.then(function(response){
// do something with the result
// extract the json from the response
console.log('response status: ', response.status)
return response.json();
}).then(function(json){
// do something with the json payload
// this is unpacking the json so it can be used
console.log("response payload: ", json)
processJson(json); // passing the (json) to the addToDom function
})
// below is the function to toggle the display of the 'address' class on and off
function handleSubmit() {
var toggleDisplay = document.querySelectorAll(".address");
console.log(toggleDisplay)
for(let i = 0; i < toggleDisplay.length; i++){ // there must be a for loop to turn each individual 'address'
// in the node list
if (toggleDisplay[i].style.display === "block") {
toggleDisplay[i].style.display = "none";
} else {
toggleDisplay[i].style.display = "block";
}
}
}
// ***************** create new elements *********************
let newLi = document.createElement("li");
let newSpan = document.createElement("span");
let newP = document.createElement("p");
let newDiv = document.createElement("div");
let newImg = document.createElement("Img")
let theUl = document.getElementById("people-list");
const body = document.body
const div = document.createElement('div')
let theName = document.querySelector('#the-name')
let processJson = function(json){
// loop through the results array , and process one contact at a time
for(let i = 0; i<json.results.length; i++){
let contact = json.results[i]; // creates a variable for each individual contact ' person' in this case
processContact(contact);
}
}
// process one contact at a time and update the dom with that contact info
let processContact = function(contact){
let firstName = contact.name.first;
let lastName = contact.name.last;
let email = contact.email;
let city = contact.location.city;
let state = contact.location.state;
//let street = `${contact.location.street.number} ${contact.location.street.name}`;
// this is another way to write the line below
let street = contact.location.street.number + ' ' + contact.location.street.name;
let picture = contact.picture.thumbnail;
let newLi = document.createElement("li");
let newSpan = document.createElement("span");
let newP = document.createElement("p");
let newA = document.createElement("a");
let newDiv = document.createElement("div");
let newImg = document.createElement("img")
let theUl = document.getElementById("people-list");
let newHr = document.createElement("hr");
theUl.appendChild(newLi);
newLi.appendChild(newSpan)
newSpan.append(firstName,' ',lastName,);
newLi.appendChild(newDiv)
newDiv.appendChild(newImg)
newImg.src = picture
newImg.append(picture)
newLi.appendChild(newP)
newP.append('Email: ', email)
newLi.appendChild(newA);
newA.append("Address: ",street ,' , ',city, ' , ',state)
//newA.classList.add("address")
newA.setAttribute('class','address')
newLi.appendChild(newHr);
}
| 97f0647d9f43c672f24027750cbb77627b7d1fe7 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | MichaelABartlett/addressBook | 9175e23b53149a76fc306138b5fd87cfc4b13e60 | bd8059133819451cf022187e162b7d94d93407c8 |
refs/heads/master | <file_sep>using Autofac.Extras.FakeItEasy;
using NUnit.Framework;
using Ploeh.AutoFixture;
namespace Rest.Proxy.UnitTests
{
[TestFixture]
public abstract class BaseAutoFakerTestFixture
{
protected AutoFake Fake;
protected Fixture Fixture;
[SetUp]
public void Setup()
{
Fake = new AutoFake();
Fixture = new Fixture();
}
[TearDown]
public void TearDown()
{
Fake.Dispose();
}
}
}
<file_sep>namespace Rest.Proxy
{
public interface IProxyFactory<out TProxyType> where TProxyType : class
{
TProxyType CreateProxy();
}
}<file_sep>using System;
namespace Rest.Proxy.Attributes
{
public class MethodRouteAttribute : Attribute
{
public HttpMethod Method { get; set; }
public string Template { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using Server.Contracts;
using Server.Contracts.Requests;
using Server.Contracts.Responses;
namespace Server.Nancy.Services
{
public class PortOrderService : IPortOrderService
{
public GetAllResponse GetAll(GetAllRequest request)
{
return new GetAllResponse
{
Msisdns = new List<string>
{
"003517962145891",
"003517962145892",
"003517962145893",
}
};
}
public GetByIdResponse GetById(GetByIdRequest request)
{
return new GetByIdResponse
{
Msisdn = $"0035179621458{request.Id}"
};
}
public CreateNewPortOrderResponse CreateNewPortOrder(CreateNewPortOrderRequest request)
{
return new CreateNewPortOrderResponse
{
Id = request
.Msisdn
.Substring(request.Msisdn.Length - 3, 2)
};
}
public void SchedulePortOrder(SchedulePortOrderRequest request)
{
// do something
}
}
}<file_sep>using System;
namespace Server.Contracts.Requests
{
public class SchedulePortOrderRequest
{
public string Id { get; set; }
public DateTime ToDate { get; set; }
public string RecipientNetworkOperator { get; set; }
public string DonorNetworkOperator { get; set; }
}
}
<file_sep>using System;
using FluentAssertions;
using Jil;
using NUnit.Framework;
namespace CV.Common.Serialization.Json.UnitTests
{
[TestFixture]
public class JsonSerializerTests
{
public class ToSerialize
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? Date { get; set; }
}
private static readonly Options Options = Options.ISO8601IncludeInherited;
private static readonly object[][] SerializationExamples = {
new object[]
{
new ToSerialize { Id = 1, Name = "name1", Date = DateTime.Today },
JSON.Serialize(new ToSerialize { Id = 1, Name = "name1", Date = DateTime.Today }, Options)
},
new object[]
{
new ToSerialize { Id = 2, Name = "name2", Date = null },
JSON.Serialize(new ToSerialize { Id = 2, Name = "name2", Date = null }, Options)
},
new object[]
{
new ToSerialize { Id = 3, Name = null, Date = DateTime.Today },
JSON.Serialize(new ToSerialize { Id = 3, Name = null, Date = DateTime.Today }, Options)
},
new object[]
{
new ToSerialize { Id = 4, Name = null, Date = null },
JSON.Serialize(new ToSerialize { Id = 4, Name = null, Date = null }, Options)
}
};
[TestCaseSource("SerializationExamples")]
public void WeakSerialize_ReturnsCorrectSerialization(object toSerialize, string expectedSerialization)
{
// arrange
var options = Options;
var sut = new JsonSerializer(options);
// act
var actualSerialization = sut.Serialize(toSerialize);
// assert
actualSerialization
.Should()
.Be(expectedSerialization);
}
[TestCaseSource("SerializationExamples")]
public void StronglyTypedSerialize_ReturnsCorrectSerialization(ToSerialize toSerialize, string expectedSerialization)
{
// arrange
var options = Options;
var sut = new JsonSerializer(options);
// act
var actualSerialization = sut.Serialize(toSerialize);
// assert
actualSerialization
.Should()
.Be(expectedSerialization);
}
[TestCaseSource("SerializationExamples")]
public void WeakDeserialize_ReturnsCorrectObject(object expectedObject, string toDeserialize)
{
// arrange
var options = Options;
var typeToDeserialize = expectedObject.GetType();
var sut = new JsonSerializer(options);
// act
var actualObject = sut.Deserialize(typeToDeserialize, toDeserialize);
// assert
actualObject
.ShouldBeEquivalentTo(expectedObject);
}
[TestCaseSource("SerializationExamples")]
public void StronglyTypedDeserialize_ReturnsCorrectObject(ToSerialize expectedObject, string toDeserialize)
{
// arrange
var options = Options;
var sut = new JsonSerializer(options);
// act
var actualObject = sut.Deserialize<ToSerialize>(toDeserialize);
// assert
actualObject
.ShouldBeEquivalentTo(expectedObject);
}
}
}
<file_sep>using System;
namespace Rest.Proxy.Attributes
{
public class ServiceRouteAttribute : Attribute
{
public string SettingBaseUrlName { get; set; }
}
}<file_sep>using Autofac;
using Nancy.Bootstrappers.Autofac;
using Server.Contracts;
using Server.Nancy.Services;
namespace Server.Nancy
{
public class Bootstrapper : AutofacNancyBootstrapper
{
protected override ILifetimeScope GetApplicationContainer()
{
var builder = new ContainerBuilder();
builder
.RegisterType<PortOrderService>()
.As<IPortOrderService>()
.InstancePerLifetimeScope();
return builder.Build();
}
}
}<file_sep>using Rest.Proxy;
using Rest.Proxy.Attributes;
using Server.Contracts.Requests;
using Server.Contracts.Responses;
namespace Server.Contracts
{
[ServiceRoute(SettingBaseUrlName = "ServerEndpoint")]
public interface IPortOrderService
{
[MethodRoute(Method = HttpMethod.Get, Template = "/portOrders")]
GetAllResponse GetAll(GetAllRequest request);
[MethodRoute(Method = HttpMethod.Get, Template = "/portOrder/{Id}")]
GetByIdResponse GetById(GetByIdRequest request);
[MethodRoute(Method = HttpMethod.Post, Template = "/portOrders")]
CreateNewPortOrderResponse CreateNewPortOrder(CreateNewPortOrderRequest request);
[MethodRoute(Method = HttpMethod.Put, Template = "/portOrder/{Id}/")]
void SchedulePortOrder(SchedulePortOrderRequest request);
}
}
<file_sep>using System;
using FakeItEasy;
using FluentAssertions;
using NUnit.Framework;
using Rest.Proxy.UnitTests.Support;
namespace Rest.Proxy.UnitTests
{
public class ProxyFactoryTests : BaseAutoFakerTestFixture
{
[Test]
public void CreateProxy_ThrowsInvalidOperationException_WhenTypeIsNotInterface()
{
// arrange
var restProxy = Fake.Resolve<IRestProxy>();
Action exceptionThrower = () => new ProxyFactory<object>(
restProxy,
proxy => new object());
// act & assert
exceptionThrower
.ShouldThrow<InvalidOperationException>();
}
[Test]
public void CreateProxy_ReturnsProxyObjectForInterface()
{
// arrange
var fakeFunc = A.Fake<Func<IRestProxy, ITest>>();
var expectedProxy = Fake.Resolve<ITest>();
A.CallTo(() => fakeFunc(Fake.Resolve<IRestProxy>()))
.Returns(expectedProxy);
Fake.Provide(fakeFunc);
var sut = Fake.Resolve<ProxyFactory<ITest>>();
// act
var actual = sut.CreateProxy();
// assert
actual
.Should()
.Be(expectedProxy);
}
}
}
<file_sep>using System;
using System.Configuration;
namespace Rest.Proxy.Settings
{
public class AppSettings : ISettings
{
private const string SettingPrefix = "rest.proxy";
public string GetBaseUrl(string settingName)
{
var completeSettingName = $"{SettingPrefix}:{settingName}";
var settingValue = ConfigurationManager
.AppSettings[completeSettingName];
if(string.IsNullOrWhiteSpace(settingValue))
throw new InvalidOperationException(
$"No entry found for setting {completeSettingName}");
return settingValue;
}
}
}
<file_sep>using System;
using System.Linq;
using Castle.Core.Interceptor;
using Rest.Proxy.Attributes;
using System.Reflection;
using Rest.Proxy.Settings;
namespace Rest.Proxy
{
public class ProxyInterceptor : IInterceptor
{
private const string InvalidServiceFormat = "The interface {0} has invalid usage of ServiceRouteAttribute";
private const string InvalidOperationFormat = "The method {0} has invalid usage of MethodRouteAttribute";
private readonly IRestProxy _restProxy;
private readonly ISettings _settings;
public ProxyInterceptor(
IRestProxy restProxy,
ISettings settings)
{
_restProxy = restProxy;
_settings = settings;
}
public void Intercept(IInvocation invocation)
{
var typeAttibutes = invocation
.Method
.DeclaringType
.GetCustomAttributes(typeof(ServiceRouteAttribute), true)
.ToList();
if (!typeAttibutes.Any() || typeAttibutes.Count > 1)
{
throw new InvalidOperationException(
string.Format(
InvalidServiceFormat,
invocation.TargetType.Name));
}
var serviceRoute = typeAttibutes
.Single() as ServiceRouteAttribute;
var methodAttributes = invocation
.Method
.GetCustomAttributes(typeof (MethodRouteAttribute))
.ToList();
if (!methodAttributes.Any() || methodAttributes.Count > 1)
{
throw new InvalidOperationException(
string.Format(
InvalidOperationFormat,
invocation.Method.Name));
}
var methodRoute = methodAttributes
.Single() as MethodRouteAttribute;
var request = invocation
.Arguments
.SingleOrDefault();
var baseUrl = _settings.GetBaseUrl(serviceRoute.SettingBaseUrlName);
var resourceUrl = methodRoute.Template;
switch (methodRoute.Method)
{
case HttpMethod.Get:
invocation.ReturnValue = _restProxy
.Get(baseUrl, resourceUrl, request, invocation.Method.ReturnType);
break;
case HttpMethod.Post:
invocation.ReturnValue = _restProxy
.Post(baseUrl, resourceUrl, request, invocation.Method.ReturnType);
break;
case HttpMethod.Put:
invocation.ReturnValue = _restProxy
.Put(baseUrl, resourceUrl, request, invocation.Method.ReturnType);
break;
case HttpMethod.Delete:
_restProxy
.Delete(baseUrl, resourceUrl, request);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
<file_sep>using System;
namespace Rest.Proxy
{
/// <summary>
/// A proxy object factory, used to create a proxy object to a REST service
/// </summary>
/// <typeparam name="TProxyType">The interface to use when creating the proxy</typeparam>
public class ProxyFactory<TProxyType>
: IProxyFactory<TProxyType> where TProxyType : class
{
private readonly IRestProxy _restProxy;
private readonly Func<IRestProxy, TProxyType> _proxyBuilderFunc;
/// <summary>
/// Creates a factory for proxy objects
/// </summary>
/// <param name="proxyBuilderFunc"></param>
/// <param name="restProxy"></param>
public ProxyFactory(
IRestProxy restProxy,
Func<IRestProxy, TProxyType> proxyBuilderFunc)
{
if (!typeof(TProxyType).IsInterface)
throw new InvalidOperationException("An interface must be provided to create a proxy");
_restProxy = restProxy;
_proxyBuilderFunc = proxyBuilderFunc;
}
/// <summary>
/// The method builds a proxy object that implements the defined interface and uses an interceptor to
/// perform the REST request
/// </summary>
/// <returns>A proxy object that implements the defined interface</returns>
public TProxyType CreateProxy()
{
return _proxyBuilderFunc(_restProxy);
}
}
}
<file_sep>namespace Rest.Proxy.UnitTests.Support.Response
{
public class GetAllResponse
{
}
}
<file_sep>namespace Server.Contracts.Requests
{
public class CreateNewPortOrderRequest
{
public string Msisdn { get; set; }
}
}
<file_sep>using System;
namespace CV.Common.Serialization
{
public interface ISerializer
{
string Serialize(object obj);
string Serialize<TType>(TType obj);
TType Deserialize<TType>(string serialized);
object Deserialize(Type type, string serialized);
}
}
<file_sep>using Nancy;
using Nancy.ModelBinding;
using Nancy.Responses.Negotiation;
using Server.Contracts;
using Server.Contracts.Requests;
namespace Server.Nancy.Modules
{
public class PortOrderModule : NancyModule
{
private readonly IPortOrderService _service;
public PortOrderModule(IPortOrderService service)
{
_service = service;
Get["/portOrders"] = GetAllPortOrders;
Get["/portOrder/{Id}"] = GetPortOrderById;
Post["/portOrders"] = PostPortOrder;
Put["/portOrder/{Id}"] = PutPortOrder;
}
private dynamic GetAllPortOrders(dynamic parameters)
{
var request = this.Bind<GetAllRequest>();
var response = _service.GetAll(request);
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(response)
.WithAllowedMediaRange(new MediaRange("application/json"));
}
private dynamic GetPortOrderById(dynamic parameters)
{
var request = this.Bind<GetByIdRequest>();
var response = _service.GetById(request);
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(response)
.WithAllowedMediaRange(new MediaRange("application/json"));
}
private dynamic PostPortOrder(dynamic parameters)
{
var request = this.Bind<CreateNewPortOrderRequest>(new BindingConfig
{
BodyOnly = true
});
var response = _service.CreateNewPortOrder(request);
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(response)
.WithAllowedMediaRange(new MediaRange("application/json"));
}
private dynamic PutPortOrder(dynamic parameters)
{
var request = this.Bind<SchedulePortOrderRequest>();
_service.SchedulePortOrder(request);
return Negotiate
.WithStatusCode(HttpStatusCode.OK);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rest.Proxy.UnitTests.Support.Requests
{
public class PostRequest
{
}
}
<file_sep>using Rest.Proxy.Attributes;
using Rest.Proxy.UnitTests.Support.Requests;
using Rest.Proxy.UnitTests.Support.Response;
namespace Rest.Proxy.UnitTests.Support
{
[ServiceRoute(SettingBaseUrlName = "SomeUrlSetting")]
public interface ITest
{
[MethodRoute(Method = HttpMethod.Get, Template = "/resource/{Id}")]
GetSingleResponse TestGet(GetSingleRequest request);
[MethodRoute(Method = HttpMethod.Get, Template = "/resources")]
GetAllResponse TestGetAll(GetAllRequest request);
[MethodRoute(Method = HttpMethod.Post, Template = "/resources")]
PostResponse TestPost(PostRequest request);
[MethodRoute(Method = HttpMethod.Put, Template = "/resource/{Id}")]
PutResponse TestPut(PutRequest request);
[MethodRoute(Method = HttpMethod.Delete, Template = "/resource/{Id}")]
void TestDelete(DeleteRequest request);
}
}<file_sep>namespace Rest.Proxy.UnitTests.Support.Requests
{
public class DeleteRequest
{
}
}<file_sep>using System.Collections.Generic;
namespace Server.Contracts.Responses
{
public class GetAllResponse
{
public IEnumerable<string> Msisdns { get; set; }
}
}
<file_sep>namespace Rest.Proxy.UnitTests.Support.Response
{
public class PutResponse
{
}
}
<file_sep>namespace Rest.Proxy.UnitTests.Support.Response
{
public class PostResponse
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rest.Proxy.UnitTests.Support.Requests
{
public class GetAllRequest
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Castle.Core;
using CV.Common.Serialization;
using RestSharp;
namespace Rest.Proxy
{
public class RestProxy : IRestProxy
{
private class UrlSegment
{
public string Name { get; set; }
public string Value { get; set; }
}
private readonly IRestClient _restClient;
private readonly ISerializer _serializer;
private readonly Func<string, Method, IRestRequest> _requestFactoryFunc;
public RestProxy(
IRestClient restClient,
ISerializer serializer,
Func<string, Method, IRestRequest> requestFactoryFunc)
{
_restClient = restClient;
_serializer = serializer;
_requestFactoryFunc = requestFactoryFunc;
}
public object Get(string baseUrl, string resourceUrl, object request, Type responseType)
{
if(string.IsNullOrWhiteSpace(baseUrl))
throw new ArgumentNullException(nameof(baseUrl));
if (string.IsNullOrWhiteSpace(resourceUrl))
throw new ArgumentNullException(nameof(resourceUrl));
if (request == null)
throw new ArgumentNullException(nameof(request));
if (responseType == null)
throw new ArgumentNullException(nameof(responseType));
return ExecuteRequestWithoutBody(
baseUrl,
resourceUrl,
request,
responseType,
Method.GET);
}
public object Post(string baseUrl, string resourceUrl, object request, Type responseType)
{
if (string.IsNullOrWhiteSpace(baseUrl))
throw new ArgumentNullException(nameof(baseUrl));
if (string.IsNullOrWhiteSpace(resourceUrl))
throw new ArgumentNullException(nameof(resourceUrl));
if (request == null)
throw new ArgumentNullException(nameof(request));
if (responseType == null)
throw new ArgumentNullException(nameof(responseType));
return ExecuteRequestWithBody(
baseUrl,
resourceUrl,
request,
responseType,
Method.POST);
}
public object Put(string baseUrl, string resourceUrl, object request, Type responseType)
{
if (string.IsNullOrWhiteSpace(baseUrl))
throw new ArgumentNullException(nameof(baseUrl));
if (string.IsNullOrWhiteSpace(resourceUrl))
throw new ArgumentNullException(nameof(resourceUrl));
if (request == null)
throw new ArgumentNullException(nameof(request));
if (responseType == null)
throw new ArgumentNullException(nameof(responseType));
return ExecuteRequestWithBody(
baseUrl,
resourceUrl,
request,
responseType,
Method.PUT);
}
public void Delete(string baseUrl, string resourceUrl, object request)
{
if (string.IsNullOrWhiteSpace(baseUrl))
throw new ArgumentNullException(nameof(baseUrl));
if (string.IsNullOrWhiteSpace(resourceUrl))
throw new ArgumentNullException(nameof(resourceUrl));
if (request == null)
throw new ArgumentNullException(nameof(request));
// replace everything in URL template
_restClient.BaseUrl = new Uri(baseUrl);
// create a request for the URL
var restRequest = GetRestRequest(resourceUrl, request, Method.DELETE);
// execute the request
ExecuteRequestAndValidateResponse(restRequest);
}
private object ExecuteRequestWithoutBody(
string baseUrl,
string resourceUrl,
object request,
Type responseType,
Method method)
{
// replace everything in URL template
_restClient.BaseUrl = new Uri(baseUrl);
// create a request for the URL
var restRequest = GetRestRequest(resourceUrl, request, method);
// execute the request
var response = ExecuteRequestAndValidateResponse(restRequest);
// deserialize the response body to return
return responseType == typeof(void)
? null
: _serializer.Deserialize(responseType, response.Content);
}
private object ExecuteRequestWithBody(
string baseUrl,
string resourceUrl,
object request,
Type responseType,
Method method)
{
// replace everything in URL template
_restClient.BaseUrl = new Uri(baseUrl);
// create a request for the URL
var restRequest = GetRestRequestWithBody(resourceUrl, request, method);
// execute the request
var response = ExecuteRequestAndValidateResponse(restRequest);
// deserialize the response body to return (if there is return)
return responseType == typeof (void)
? null
: _serializer.Deserialize(responseType, response.Content);
}
private IRestRequest GetRestRequest(string resourceUrl, object request, Method method)
{
var segments = ExtractSegments(resourceUrl, request);
var finalResourceUrl = new StringBuilder(resourceUrl)
.ToString();
segments
.ForEach(segment =>
finalResourceUrl = finalResourceUrl
.Replace($"{{{segment.Name}}}", segment.Value));
return _requestFactoryFunc(finalResourceUrl, method);
}
private IRestRequest GetRestRequestWithBody(string resourceUrl, object request, Method method)
{
var restRequest = GetRestRequest(resourceUrl, request, method);
restRequest.AddJsonBody(request);
return restRequest;
}
private static IEnumerable<UrlSegment> ExtractSegments(string resourceUrl, object request)
{
var segments = new List<UrlSegment>();
var lastIndex = 0;
var openIndex = 0;
var closeIndex = 0;
do
{
openIndex = resourceUrl.IndexOf("{", lastIndex);
if (openIndex != -1)
{
closeIndex = resourceUrl.IndexOf("}", lastIndex);
var segmentName = resourceUrl
.Substring(openIndex + 1, (closeIndex - openIndex) - 1);
var segmentValue = GetPropertyValue(request, segmentName);
if(segmentValue != null)
segments.Add(new UrlSegment
{
Name = segmentName,
Value = segmentValue
});
lastIndex = openIndex + 1;
}
}
while (openIndex != -1);
return segments;
}
private static string GetPropertyValue(object request, string propertyName)
{
var properties = request
.GetType()
.GetProperties();
var property = properties
.SingleOrDefault(p => p.Name.Equals(propertyName));
return property?.GetValue(request)?.ToString();
}
private IRestResponse ExecuteRequestAndValidateResponse(IRestRequest restRequest)
{
var restResponse = _restClient.Execute(restRequest);
if (restResponse.ErrorException != null)
{
throw new HttpException(
$"Server returned error: {restResponse.ErrorMessage}",
restResponse.ErrorException);
}
// TODO: just OK or all the 2xx family????
if (restResponse.StatusCode != HttpStatusCode.OK)
{
throw new HttpException($"Server returned error: {restResponse.StatusDescription}");
}
return restResponse;
}
}
}
<file_sep>namespace Rest.Proxy.UnitTests.Support.Response
{
public class GetSingleResponse
{
}
}
<file_sep># Rest.Proxy
Its a proxy... to a REST service!!!
<file_sep>namespace Rest.Proxy.UnitTests.Support.Requests
{
public class GetSingleRequest
{
public string Id { get; set; }
}
}
<file_sep>namespace Server.Contracts.Requests
{
public class GetByIdRequest
{
public string Id { get; set; }
}
}<file_sep>namespace Server.Contracts.Responses
{
public class GetByIdResponse
{
public string Msisdn { get; set; }
}
}<file_sep>namespace Rest.Proxy.Settings
{
public interface ISettings
{
string GetBaseUrl(string settingName);
}
}
<file_sep>using System;
namespace Rest.Proxy
{
public class HttpException : Exception
{
public HttpException()
: base("Exception occurred when performing an Http request")
{
}
public HttpException(string message)
: base(message)
{
}
public HttpException(string message, Exception inner)
: base(message, inner)
{
}
}
}
<file_sep>using System;
using Jil;
namespace CV.Common.Serialization.Json
{
public class JsonSerializer : ISerializer
{
private readonly Options _options;
public JsonSerializer(Options options)
{
_options = options;
}
public string Serialize(object obj)
{
return JSON.Serialize(obj, _options);
}
public string Serialize<TType>(TType obj)
{
return JSON.Serialize(obj, _options);
}
public TType Deserialize<TType>(string serialized)
{
return JSON.Deserialize<TType>(serialized, _options);
}
public object Deserialize(Type type, string serialized)
{
return JSON.Deserialize(serialized, type, _options);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rest.Proxy.UnitTests.Support.Requests
{
public class PutRequest
{
}
}
<file_sep>using System;
namespace Rest.Proxy
{
public interface IRestProxy
{
object Get(string baseUrl, string resourceUrl, object request, Type responseType);
object Post(string baseUrl, string resourceUrl, object request, Type responseType);
object Put(string baseUrl, string resourceUrl, object request, Type responseType);
void Delete(string baseUrl, string resourceUrl, object request);
}
}<file_sep>using Castle.Core.Interceptor;
using FakeItEasy;
using FluentAssertions;
using NUnit.Framework;
using Ploeh.AutoFixture;
using Rest.Proxy.Settings;
using Rest.Proxy.UnitTests.Support;
namespace Rest.Proxy.UnitTests
{
public class ProxyInterceptorTests : BaseAutoFakerTestFixture
{
[Test]
public void Intercept_InvokesGetWithCorrectValues_WhenMethodIsDefinedAsGet()
{
// arrange
const string baseUrlSettingName = "SomeUrlSetting"; // As defined on ITest interface
const string resourceUrl = "/resource/{Id}"; // As defined on ITest interface
var baseUrl = Fixture.Create<string>();
var invocation = Fake.Resolve<IInvocation>();
var request = Fixture.Create<object>();
var methodInfo = typeof (ITest)
.GetMethod("TestGet");
A.CallTo(() => invocation
.Method)
.Returns(methodInfo);
A.CallTo(() => invocation
.Arguments)
.Returns(new[] { request });
A.CallTo(() => Fake.Resolve<ISettings>()
.GetBaseUrl(baseUrlSettingName))
.Returns(baseUrl);
var sut = Fake.Resolve<ProxyInterceptor>();
// act
sut.Intercept(invocation);
// assert
A.CallTo(() => Fake.Resolve<IRestProxy>()
.Get(baseUrl, resourceUrl, request, methodInfo.ReturnType))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Test]
public void Intercept_SetsReturnValueWithGetResponse_WhenMethodIsDefinedAsGet()
{
// arrange
const string baseUrlSettingName = "SomeUrlSetting"; // As defined on ITest interface
const string resourceUrl = "/resource/{Id}"; // As defined on ITest interface
var baseUrl = Fixture.Create<string>();
var invocation = Fake.Resolve<IInvocation>();
var request = Fixture.Create<object>();
var response = Fixture.Create<object>();
var methodInfo = typeof(ITest)
.GetMethod("TestGet");
A.CallTo(() => invocation
.Method)
.Returns(methodInfo);
A.CallTo(() => invocation
.Arguments)
.Returns(new[] { request });
A.CallTo(() => Fake.Resolve<ISettings>()
.GetBaseUrl(baseUrlSettingName))
.Returns(baseUrl);
A.CallTo(() => Fake.Resolve<IRestProxy>()
.Get(baseUrl, resourceUrl, request, methodInfo.ReturnType))
.Returns(response);
var sut = Fake.Resolve<ProxyInterceptor>();
// act
sut.Intercept(invocation);
// assert
invocation
.ReturnValue
.Should()
.Be(response);
}
[Test]
public void Intercept_InvokesPostWithCorrectValues_WhenMethodIsDefinedAsPost()
{
// arrange
const string baseUrlSettingName = "SomeUrlSetting"; // As defined on ITest interface
const string resourceUrl = "/resources"; // As defined on ITest interface
var baseUrl = Fixture.Create<string>();
var invocation = Fake.Resolve<IInvocation>();
var request = Fixture.Create<object>();
var methodInfo = typeof(ITest)
.GetMethod("TestPost");
A.CallTo(() => invocation
.Method)
.Returns(methodInfo);
A.CallTo(() => invocation
.Arguments)
.Returns(new[] { request });
A.CallTo(() => Fake.Resolve<ISettings>()
.GetBaseUrl(baseUrlSettingName))
.Returns(baseUrl);
var sut = Fake.Resolve<ProxyInterceptor>();
// act
sut.Intercept(invocation);
// assert
A.CallTo(() => Fake.Resolve<IRestProxy>()
.Post(baseUrl, resourceUrl, request, methodInfo.ReturnType))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Test]
public void Intercept_SetsReturnValueWithPostResponse_WhenMethodIsDefinedAsPost()
{
// arrange
const string baseUrlSettingName = "SomeUrlSetting"; // As defined on ITest interface
const string resourceUrl = "/resources"; // As defined on ITest interface
var baseUrl = Fixture.Create<string>();
var invocation = Fake.Resolve<IInvocation>();
var request = Fixture.Create<object>();
var response = Fixture.Create<object>();
var methodInfo = typeof(ITest)
.GetMethod("TestPost");
A.CallTo(() => invocation
.Method)
.Returns(methodInfo);
A.CallTo(() => invocation
.Arguments)
.Returns(new[] { request });
A.CallTo(() => Fake.Resolve<ISettings>()
.GetBaseUrl(baseUrlSettingName))
.Returns(baseUrl);
A.CallTo(() => Fake.Resolve<IRestProxy>()
.Post(baseUrl, resourceUrl, request, methodInfo.ReturnType))
.Returns(response);
var sut = Fake.Resolve<ProxyInterceptor>();
// act
sut.Intercept(invocation);
// assert
invocation
.ReturnValue
.Should()
.Be(response);
}
}
}
<file_sep>using System;
using Autofac;
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
using CV.Common.Serialization;
using CV.Common.Serialization.Json;
using Jil;
using Rest.Proxy;
using Rest.Proxy.Settings;
using RestSharp;
using Server.Contracts;
using Server.Contracts.Requests;
namespace Client
{
public class Program
{
public static void Main(string[] args)
{
var containerBuilder = new ContainerBuilder();
containerBuilder
.RegisterType<AppSettings>()
.As<ISettings>()
.InstancePerLifetimeScope();
containerBuilder
.RegisterType<ProxyInterceptor>()
.As<IInterceptor>()
.InstancePerLifetimeScope();
containerBuilder
.Register<Func<string, Method, IRestRequest>>(ctx =>
{
return (resourceUrl, method) => new RestRequest(resourceUrl, method);
});
containerBuilder
.Register<Func<IRestProxy, IPortOrderService>>(ctx =>
{
return p =>
{
var gen = new ProxyGenerator();
var interceptor = ctx
.Resolve<IInterceptor>(
new TypedParameter(typeof (IRestProxy), p));
return gen
.CreateInterfaceProxyWithoutTarget<IPortOrderService>(interceptor);
};
});
containerBuilder
.RegisterType<RestClient>()
.As<IRestClient>()
.InstancePerLifetimeScope();
containerBuilder
.Register(ctx => new JsonSerializer(Options.ISO8601IncludeInherited))
.As<ISerializer>()
.InstancePerLifetimeScope();
containerBuilder
.RegisterType<RestProxy>()
.As<IRestProxy>()
.InstancePerLifetimeScope();
containerBuilder
.RegisterType<ProxyFactory<IPortOrderService>>()
.As<IProxyFactory<IPortOrderService>>()
.InstancePerLifetimeScope();
containerBuilder
.Register(ctx => ctx
.Resolve<IProxyFactory<IPortOrderService>>()
.CreateProxy())
.As<IPortOrderService>()
.InstancePerLifetimeScope();
var container = containerBuilder.Build();
// Testing
var serviceProxy = container.Resolve<IPortOrderService>();
var getAllResponse = serviceProxy.GetAll(new GetAllRequest());
Console.WriteLine("GetAllRequest");
Console.WriteLine(JSON.Serialize(getAllResponse));
var getByIdResponse = serviceProxy.GetById(new GetByIdRequest
{
Id = "23"
});
Console.WriteLine("GetByIdRequest");
Console.WriteLine(JSON.Serialize(getByIdResponse));
var createNewPortResponse = serviceProxy.CreateNewPortOrder(new CreateNewPortOrderRequest
{
Msisdn = "0035198789654"
});
Console.WriteLine("CreateNewPortOrder");
Console.WriteLine(JSON.Serialize(createNewPortResponse));
serviceProxy.SchedulePortOrder(new SchedulePortOrderRequest
{
Id = "23",
ToDate = DateTime.Today.AddDays(2),
DonorNetworkOperator = "Vodafone",
RecipientNetworkOperator = "Meo"
});
Console.WriteLine("SchedulePortOrder");
Console.WriteLine("No response");
Console.ReadKey();
}
}
}
<file_sep>namespace Server.Contracts.Requests
{
public class GetAllRequest
{
}
}
<file_sep>namespace Server.Contracts.Responses
{
public class CreateNewPortOrderResponse
{
public string Id { get; set; }
}
}
<file_sep>using System;
using System.Net;
using CV.Common.Serialization;
using FakeItEasy;
using FluentAssertions;
using NUnit.Framework;
using Ploeh.AutoFixture;
using RestSharp;
namespace Rest.Proxy.UnitTests
{
public class RestProxyTests : BaseAutoFakerTestFixture
{
public class Request
{
public string Id { get; set; }
}
public class Response
{
public string Id { get; set; }
public string Result { get; set; }
}
[Test]
public void Get_UsesWithCorrectUrl_WhenSendsHttpGetRequest()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.GET))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(null);
A.CallTo(() => response.StatusCode)
.Returns(HttpStatusCode.OK);
var sut = Fake.Resolve<RestProxy>();
// act
sut.Get(baseUrl, resourceUrl, request, typeof(Response));
// assert
A.CallTo(() => restClient
.Execute(restRequest))
.MustHaveHappened(Repeated.Exactly.Once);
restClient
.BaseUrl
.Should()
.Be(baseUrl);
}
[Test]
public void Get_ReturnsResponse_WhenSendsHttpGetRequest()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var restResponse = Fake.Resolve<IRestResponse>();
var serializer = Fake.Resolve<ISerializer>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var expectedResponse = Fixture.Create<Response>();
var expectedResponseSerialized = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.GET))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(restResponse);
A.CallTo(() => restResponse.ErrorException)
.Returns(null);
A.CallTo(() => restResponse.StatusCode)
.Returns(HttpStatusCode.OK);
A.CallTo(() => restResponse.Content)
.Returns(expectedResponseSerialized);
A.CallTo(() => serializer
.Deserialize(typeof(Response), expectedResponseSerialized))
.Returns(expectedResponse);
var sut = Fake.Resolve<RestProxy>();
// act
var actualResponse = sut.Get(baseUrl, resourceUrl, request, typeof(Response));
// assert
actualResponse
.ShouldBeEquivalentTo(expectedResponse);
}
[Test]
public void Get_ThrowsException_WhenBaseUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Get(
null,
Fixture.Create<string>(),
Fixture.Create<object>(),
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("baseUrl");
}
[Test]
public void Get_ThrowsException_WhenResourceUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Get(
Fixture.Create<string>(),
null,
Fixture.Create<object>(),
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("resourceUrl");
}
[Test]
public void Get_ThrowsException_WhenRequestIsNull()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Get(
Fixture.Create<string>(),
Fixture.Create<string>(),
null,
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("request");
}
[Test]
public void Get_ThrowsException_WhenResponseTypeIsNull()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Get(
Fixture.Create<string>(),
Fixture.Create<string>(),
Fixture.Create<object>(),
null);
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("responseType");
}
[Test]
public void Get_ThrowsException_WhenServerReturnsErrorHttpCode()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var restResponse = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.GET))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(restResponse);
A.CallTo(() => restResponse.ErrorException)
.Returns(null);
A.CallTo(() => restResponse.StatusCode)
.Returns(HttpStatusCode.BadRequest);
A.CallTo(() => restResponse.StatusDescription)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Get(
baseUrl,
resourceUrl,
request,
typeof(Response));
// act/assert
throwable
.ShouldThrow<HttpException>()
.And
.Message
.Should()
.Contain(description);
}
[Test]
public void Get_ThrowsException_WhenHttpRequestFailsOverTCPErrors()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var restResponse = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
var exception = new Exception("BOOM!!");
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.GET))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(restResponse);
A.CallTo(() => restResponse.ErrorException)
.Returns(exception);
A.CallTo(() => restResponse.ErrorMessage)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Get(
baseUrl,
resourceUrl,
request,
typeof(Response));
// act/assert
var exceptionThrown = throwable
.ShouldThrow<HttpException>();
exceptionThrown
.And
.Message
.Should()
.Contain(description);
exceptionThrown
.And
.InnerException
.Should()
.Be(exception);
}
[Test]
public void Post_UsesWithCorrectUrl_WhenSendsHttpPostRequest()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.POST))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(null);
A.CallTo(() => response.StatusCode)
.Returns(HttpStatusCode.OK);
var sut = Fake.Resolve<RestProxy>();
// act
sut.Post(baseUrl, resourceUrl, request, typeof(Response));
// assert
A.CallTo(() => restRequest
.AddJsonBody(request))
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => restClient
.Execute(restRequest))
.MustHaveHappened(Repeated.Exactly.Once);
restClient
.BaseUrl
.Should()
.Be(baseUrl);
}
[Test]
public void Post_ReturnsResponse_WhenSendsHttpGetRequest()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var restResponse = Fake.Resolve<IRestResponse>();
var serializer = Fake.Resolve<ISerializer>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var expectedResponse = Fixture.Create<Response>();
var expectedResponseSerialized = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.POST))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(restResponse);
A.CallTo(() => restResponse.ErrorException)
.Returns(null);
A.CallTo(() => restResponse.StatusCode)
.Returns(HttpStatusCode.OK);
A.CallTo(() => restResponse.Content)
.Returns(expectedResponseSerialized);
A.CallTo(() => serializer
.Deserialize(typeof(Response), expectedResponseSerialized))
.Returns(expectedResponse);
var sut = Fake.Resolve<RestProxy>();
// act
var actualResponse = sut.Post(baseUrl, resourceUrl, request, typeof(Response));
// assert
actualResponse
.ShouldBeEquivalentTo(expectedResponse);
}
[Test]
public void Post_ThrowsException_WhenBaseUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Post(
null,
Fixture.Create<string>(),
Fixture.Create<object>(),
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("baseUrl");
}
[Test]
public void Post_ThrowsException_WhenResourceUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Post(
Fixture.Create<string>(),
null,
Fixture.Create<object>(),
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("resourceUrl");
}
[Test]
public void Post_ThrowsException_WhenRequestIsNull()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Post(
Fixture.Create<string>(),
Fixture.Create<string>(),
null,
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("request");
}
[Test]
public void Post_ThrowsException_WhenResponseTypeIsNull()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Post(
Fixture.Create<string>(),
Fixture.Create<string>(),
Fixture.Create<object>(),
null);
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("responseType");
}
[Test]
public void Post_ThrowsException_WhenServerReturnsErrorHttpCode()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.POST))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(null);
A.CallTo(() => response.StatusCode)
.Returns(HttpStatusCode.BadRequest);
A.CallTo(() => response.StatusDescription)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Post(
baseUrl,
resourceUrl,
request,
typeof(Response));
// act/assert
throwable
.ShouldThrow<HttpException>()
.And
.Message
.Should()
.Contain(description);
}
[Test]
public void Post_ThrowsException_WhenHttpRequestFailsOverTCPErrors()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
var exception = new Exception("BOOM!!");
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.POST))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(exception);
A.CallTo(() => response.ErrorMessage)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Post(
baseUrl,
resourceUrl,
request,
typeof(Response));
// act/assert
var exceptionThrown = throwable
.ShouldThrow<HttpException>();
exceptionThrown
.And
.Message
.Should()
.Contain(description);
exceptionThrown
.And
.InnerException
.Should()
.Be(exception);
}
[Test]
public void Put_UsesWithCorrectUrl_WhenSendsHttpPostRequest()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.PUT))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(null);
A.CallTo(() => response.StatusCode)
.Returns(HttpStatusCode.OK);
var sut = Fake.Resolve<RestProxy>();
// act
sut.Put(baseUrl, resourceUrl, request, typeof(Response));
// assert
A.CallTo(() => restRequest
.AddJsonBody(request))
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => restClient
.Execute(restRequest))
.MustHaveHappened(Repeated.Exactly.Once);
restClient
.BaseUrl
.Should()
.Be(baseUrl);
}
[Test]
public void Put_ReturnsResponse_WhenSendsHttpGetRequest()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var restResponse = Fake.Resolve<IRestResponse>();
var serializer = Fake.Resolve<ISerializer>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var expectedResponse = Fixture.Create<Response>();
var expectedResponseSerialized = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.PUT))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(restResponse);
A.CallTo(() => restResponse.ErrorException)
.Returns(null);
A.CallTo(() => restResponse.StatusCode)
.Returns(HttpStatusCode.OK);
A.CallTo(() => restResponse.Content)
.Returns(expectedResponseSerialized);
A.CallTo(() => serializer
.Deserialize(typeof(Response), expectedResponseSerialized))
.Returns(expectedResponse);
var sut = Fake.Resolve<RestProxy>();
// act
var actualResponse = sut.Put(baseUrl, resourceUrl, request, typeof(Response));
// assert
actualResponse
.ShouldBeEquivalentTo(expectedResponse);
}
[Test]
public void Put_ThrowsException_WhenBaseUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Put(
null,
Fixture.Create<string>(),
Fixture.Create<object>(),
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("baseUrl");
}
[Test]
public void Put_ThrowsException_WhenResourceUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Put(
Fixture.Create<string>(),
null,
Fixture.Create<object>(),
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("resourceUrl");
}
[Test]
public void Put_ThrowsException_WhenRequestIsNull()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Put(
Fixture.Create<string>(),
Fixture.Create<string>(),
null,
Fixture.Create<Type>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("request");
}
[Test]
public void Put_ThrowsException_WhenResponseTypeIsNull()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Put(
Fixture.Create<string>(),
Fixture.Create<string>(),
Fixture.Create<object>(),
null);
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("responseType");
}
[Test]
public void Put_ThrowsException_WhenServerReturnsErrorHttpCode()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.PUT))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(null);
A.CallTo(() => response.StatusCode)
.Returns(HttpStatusCode.BadRequest);
A.CallTo(() => response.StatusDescription)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Put(
baseUrl,
resourceUrl,
request,
typeof(Response));
// act/assert
throwable
.ShouldThrow<HttpException>()
.And
.Message
.Should()
.Contain(description);
}
[Test]
public void Put_ThrowsException_WhenHttpRequestFailsOverTCPErrors()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
var exception = new Exception("BOOM!!");
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.PUT))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(exception);
A.CallTo(() => response.ErrorMessage)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Put(
baseUrl,
resourceUrl,
request,
typeof(Response));
// act/assert
var exceptionThrown = throwable
.ShouldThrow<HttpException>();
exceptionThrown
.And
.Message
.Should()
.Contain(description);
exceptionThrown
.And
.InnerException
.Should()
.Be(exception);
}
[Test]
public void Delete_UsesWithCorrectUrl_WhenSendsHttpGetRequest()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var response = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.DELETE))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(response);
A.CallTo(() => response.ErrorException)
.Returns(null);
A.CallTo(() => response.StatusCode)
.Returns(HttpStatusCode.OK);
var sut = Fake.Resolve<RestProxy>();
// act
sut.Delete(baseUrl, resourceUrl, request);
// assert
A.CallTo(() => restClient
.Execute(restRequest))
.MustHaveHappened(Repeated.Exactly.Once);
restClient
.BaseUrl
.Should()
.Be(baseUrl);
}
[Test]
public void Delete_ThrowsException_WhenBaseUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Delete(
null,
Fixture.Create<string>(),
Fixture.Create<object>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("baseUrl");
}
[Test]
public void Delete_ThrowsException_WhenResourceUrlIsNullOrWhitespace()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Delete(
Fixture.Create<string>(),
null,
Fixture.Create<object>());
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("resourceUrl");
}
[Test]
public void Delete_ThrowsException_WhenRequestIsNull()
{
// arrange
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Delete(
Fixture.Create<string>(),
Fixture.Create<string>(),
null);
// act/assert
throwable
.ShouldThrow<ArgumentNullException>()
.And
.ParamName
.Should()
.Be("request");
}
[Test]
public void Delete_ThrowsException_WhenServerReturnsErrorHttpCode()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var restResponse = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.DELETE))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(restResponse);
A.CallTo(() => restResponse.ErrorException)
.Returns(null);
A.CallTo(() => restResponse.StatusCode)
.Returns(HttpStatusCode.BadRequest);
A.CallTo(() => restResponse.StatusDescription)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Delete(
baseUrl,
resourceUrl,
request);
// act/assert
throwable
.ShouldThrow<HttpException>()
.And
.Message
.Should()
.Contain(description);
}
[Test]
public void Delete_ThrowsException_WhenHttpRequestFailsOverTCPErrors()
{
// arrange
const string baseUrl = "http://localhost";
const string resourceUrl = "/resource/{Id}";
var restClient = Fake.Resolve<IRestClient>();
var restResponse = Fake.Resolve<IRestResponse>();
var fakeRequestFactoryFunc = A.Fake<Func<string, Method, IRestRequest>>();
var restRequest = Fake.Resolve<IRestRequest>();
var request = Fixture.Create<Request>();
var description = Fixture.Create<string>();
var expectedUrl = $"/resource/{request.Id}";
var exception = new Exception("BOOM!!");
A.CallTo(() => fakeRequestFactoryFunc(expectedUrl, Method.DELETE))
.Returns(restRequest);
A.CallTo(() => restClient
.Execute(restRequest))
.Returns(restResponse);
A.CallTo(() => restResponse.ErrorException)
.Returns(exception);
A.CallTo(() => restResponse.ErrorMessage)
.Returns(description);
var sut = Fake.Resolve<RestProxy>();
Action throwable = () => sut.Delete(
baseUrl,
resourceUrl,
request);
// act/assert
var exceptionThrown = throwable
.ShouldThrow<HttpException>();
exceptionThrown
.And
.Message
.Should()
.Contain(description);
exceptionThrown
.And
.InnerException
.Should()
.Be(exception);
}
}
}
| 2bcc4c6a8dac31542e5d4f6e161f51614ace4529 | [
"Markdown",
"C#"
] | 40 | C# | carlos-vicente/Rest.Proxy | 21d08add67a828faf85a8853f5e65f76f46ce5b9 | 0268c54cd1fca7249dd4cf33fc24d4f04f0b27c7 |
refs/heads/master | <file_sep>cmake_minimum_required(VERSION 2.8)
project(SSESwizzle)
set(SOURCES
SSESwizzle.cpp)
set(HEADERS)
add_executable(SSESwizzle
${SOURCES}
${HEADERS})
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS)
endif()
target_link_libraries(SSESwizzle
${PLATFORM_LIBS})<file_sep>cmake_minimum_required(VERSION 2.8)
project(InvSqrtSingle)
set(SOURCES
InvSqrt_Single.cpp)
set(HEADERS)
add_executable(InvSqrtSingle
${SOURCES}
${HEADERS})
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS
winmm)
endif()
target_link_libraries(InvSqrtSingle
${PLATFORM_LIBS})<file_sep>/*
Sample for DataPath
Copyright (C) 2019 <NAME> <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "measurer.hpp"
#include <iterator>
measurer::instance::instance(measurer* parent) : parent(parent), start(std::chrono::high_resolution_clock::now()) {}
measurer::instance::~instance()
{
auto end = std::chrono::high_resolution_clock::now();
auto dur = end - this->start;
if (this->parent) {
this->parent->track(dur);
}
}
void measurer::instance::cancel()
{
this->parent = nullptr;
}
measurer::measurer() {}
measurer::~measurer() {}
std::shared_ptr<measurer::instance> measurer::track()
{
return std::make_shared<measurer::instance>(this);
}
void measurer::track(std::chrono::nanoseconds duration)
{
std::unique_lock<std::mutex> ul(this->lock);
auto itr = timings.find(duration);
if (itr == timings.end()) {
timings.insert({duration, 1});
} else {
itr->second++;
}
}
uint64_t measurer::count()
{
uint64_t count = 0;
std::map<std::chrono::nanoseconds, size_t> copy_timings;
{
std::unique_lock<std::mutex> ul(this->lock);
std::copy(this->timings.begin(), this->timings.end(), std::inserter(copy_timings, copy_timings.end()));
}
for (auto kv : copy_timings) {
count += kv.second;
}
return count;
}
std::chrono::nanoseconds measurer::total_duration()
{
std::chrono::nanoseconds duration;
std::map<std::chrono::nanoseconds, size_t> copy_timings;
{
std::unique_lock<std::mutex> ul(this->lock);
std::copy(this->timings.begin(), this->timings.end(), std::inserter(copy_timings, copy_timings.end()));
}
for (auto kv : copy_timings) {
duration += kv.first * kv.second;
}
return duration;
}
double_t measurer::average_duration()
{
std::chrono::nanoseconds duration = std::chrono::nanoseconds(0);
uint64_t count = 0;
std::map<std::chrono::nanoseconds, size_t> copy_timings;
{
std::unique_lock<std::mutex> ul(this->lock);
std::copy(this->timings.begin(), this->timings.end(), std::inserter(copy_timings, copy_timings.end()));
}
for (auto kv : copy_timings) {
duration = std::chrono::nanoseconds(duration.count() + kv.first.count() * kv.second);
count += kv.second;
}
return double_t(duration.count()) / double_t(count);
}
template<typename T>
inline bool is_equal(T a, T b, T c)
{
return (a == b) || ((a >= (b - c)) && (a <= (b + c)));
}
std::chrono::nanoseconds measurer::percentile(double_t percentile, bool by_time)
{
uint64_t calls = count();
std::map<std::chrono::nanoseconds, size_t> copy_timings;
{
std::unique_lock<std::mutex> ul(this->lock);
std::copy(this->timings.begin(), this->timings.end(), std::inserter(copy_timings, copy_timings.end()));
}
if (by_time) { // Return by time percentile.
// Find largest and smallest time.
std::chrono::nanoseconds smallest = copy_timings.begin()->first;
std::chrono::nanoseconds largest = copy_timings.rbegin()->first;
std::chrono::nanoseconds variance = largest - smallest;
std::chrono::nanoseconds threshold =
std::chrono::nanoseconds(smallest.count() + int64_t(variance.count() * percentile));
for (auto kv : copy_timings) {
double_t kv_pct = double_t((kv.first - smallest).count()) / double_t(variance.count());
if (is_equal(kv_pct, percentile, 0.00005) || (kv_pct > percentile)) {
return std::chrono::nanoseconds(kv.first);
}
}
} else { // Return by call percentile.
if (percentile == 0.0) {
return copy_timings.begin()->first;
}
uint64_t accu_calls_now = 0;
for (auto kv : copy_timings) {
uint64_t accu_calls_last = accu_calls_now;
accu_calls_now += kv.second;
double_t percentile_last = double_t(accu_calls_last) / double_t(calls);
double_t percentile_now = double_t(accu_calls_now) / double_t(calls);
if (is_equal(percentile, percentile_now, 0.0005)
|| ((percentile_last < percentile) && (percentile_now > percentile))) {
return std::chrono::nanoseconds(kv.first);
}
}
}
return std::chrono::nanoseconds(-1);
}
<file_sep># Sandbox-Cpp
C++ Testing Grounds
<file_sep>#include "memcpy_adv.h"
#include "os.hpp"
#include <array>
#include <iostream>
#include <queue>
#include <vector>
#ifdef _WIN32
#include "windows.h"
#endif
#include "intrin.h"
//#define BLOCK_BASED
#define BLOCK_SIZE 256 * 1024
#undef min
#undef max
#define min(v, low) ((v < low) ? v : low)
#define max(v, high) ((v > high) ? v : high)
void* memcpy_movsb(unsigned char* to, unsigned char* from, size_t size)
{
__movsb(to, from, size);
return to;
}
struct memcpy_task {
void* from = nullptr;
void* to = nullptr;
size_t size = 0;
os::Semaphore* semaphore = nullptr;
size_t index = 0;
size_t block_size = 0;
#ifndef BLOCK_BASED
size_t block_size_rem = 0;
#endif
};
struct memcpy_env {
void* (*copyfnc)(void*, void*, size_t);
os::Semaphore semaphore;
std::mutex queue_mutex;
std::queue<memcpy_task> task_queue;
size_t block_size = BLOCK_SIZE;
bool exit_threads = false;
std::vector<std::thread> threads;
};
// ToDo: Make thread-local
memcpy_env* memcpy_active_env = nullptr;
static void* (*memcpy_fnc)(void*, const void*, size_t) = &memcpy;
static void memcpy_thread_main(memcpy_env* env)
{
os::Semaphore* semaphore;
void * from, *to;
size_t size;
do {
env->semaphore.wait();
{
std::unique_lock<std::mutex> lock(env->queue_mutex);
if (env->task_queue.empty())
continue;
// Dequeue
memcpy_task& task = env->task_queue.front();
from = task.from;
to = task.to;
#ifdef BLOCK_BASED
size = (task.size > task.block_size ? task.block_size : task.size);
#else
size = task.block_size + task.block_size_rem;
#endif
semaphore = task.semaphore;
// Update
if (task.size > size) {
task.from = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(task.from) + size);
task.to = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(task.to) + size);
task.size -= size;
task.index++;
} else {
env->task_queue.pop();
}
}
memcpy_fnc((unsigned char*)to, (unsigned char*)from, size);
semaphore->notify();
} while (!env->exit_threads);
}
void* memcpy_thread_initialize(size_t threads)
{
memcpy_env* env = new memcpy_env();
env->threads.resize(threads);
DWORD mask = 1;
for (std::thread& threads : env->threads) {
threads = std::thread(memcpy_thread_main, env);
#ifdef _WIN32
//SetThreadAffinityMask(threads.native_handle(), mask);
#else
// Linux/MacOSX?
#endif
mask <<= 1;
}
return env;
}
void memcpy_thread_set_memcpy(void* (*memcpy)(void*, const void*, size_t))
{
memcpy_fnc = memcpy;
}
void memcpy_thread_env(void* env)
{
memcpy_env* renv = (memcpy_env*)env;
memcpy_active_env = renv;
}
void* memcpy_thread(void* to, void* from, size_t size)
{
os::Semaphore semaphore;
memcpy_task task;
task.from = from;
task.to = to;
task.size = size;
task.semaphore = &semaphore;
#ifdef BLOCK_BASED
size_t blocks_complete = size / memcpy_active_env->block_size;
size_t blocks_incomplete = size % memcpy_active_env->block_size;
size_t blocks = blocks_complete + (blocks_incomplete > 0 ? 1 : 0);
task.block_size = memcpy_active_env->block_size;
#else
size_t blocks = min(max(size, memcpy_active_env->block_size) / memcpy_active_env->block_size,
memcpy_active_env->threads.size());
task.block_size = size / blocks;
task.block_size_rem = size - (task.block_size * blocks);
#endif
{
std::unique_lock<std::mutex> lock(memcpy_active_env->queue_mutex);
memcpy_active_env->task_queue.push(task);
memcpy_active_env->semaphore.notify(blocks);
}
semaphore.wait(blocks);
return to;
}
void memcpy_thread_finalize(void* env)
{
if (env == nullptr)
return;
memcpy_env* renv = (memcpy_env*)env;
renv->exit_threads = true;
renv->semaphore.notify(INT_MAX);
{
std::unique_lock<std::mutex> lock(renv->queue_mutex);
if (renv->task_queue.size() > 0) {
for (size_t n = 0; n < renv->task_queue.size(); n++) {
memcpy_task task = renv->task_queue.front();
task.semaphore->notify(INT_MAX);
}
}
}
for (std::thread& thd : renv->threads) {
thd.join();
}
renv->threads.clear();
// ToDo: Release any waiting memcpy_thread calls.
delete renv;
}
<file_sep>#include <inttypes.h>
#include <vector>
#include <iostream>
#include <ostream>
#include <iomanip>
int main(int argc, char* argv[]) {
std::vector<char> buf(255);
for (size_t idx = 0; idx < buf.size(); idx++) {
std::cout << std::setw(sizeof(uint8_t) * 2) << std::setfill('0') << std::hex << int(0xFF & buf[idx]) << " ";
}
std::cout << std::endl;
uint8_t* data = reinterpret_cast<uint8_t*>(buf.data());
*data = 11; data++;
*reinterpret_cast<uint32_t*>(data) = 0xADADADul; data += 4;
*data = 11; data++;
*reinterpret_cast<uint32_t*>(data) = 0xADADADul; data += 4;
*data = 11; data++;
*reinterpret_cast<uint32_t*>(data) = 0xADADADul; data += 4;
*data = 11; data++;
*reinterpret_cast<uint32_t*>(data) = 0xADADADul; data += 4;
for (size_t idx = 0; idx < buf.size(); idx++) {
std::cout << std::setw(sizeof(uint8_t) * 2) << std::setfill('0') << std::hex << int(0xFF & buf[idx]) << " ";
}
std::cout << std::endl;
std::cin.get();
return 0;
}<file_sep>#include <stdio.h>
#include <tmmintrin.h>
int main() {
__m128i a, mask;
a.m128i_i8[0] = 255;
a.m128i_i8[1] = 138;
a.m128i_i8[2] = 88;
a.m128i_i8[3] = 42;
a.m128i_i8[4] = 93;
a.m128i_i8[5] = 232;
a.m128i_i8[6] = 99;
a.m128i_i8[7] = 78;
a.m128i_i8[8] = -1;
a.m128i_i8[9] = -2;
a.m128i_i8[10] = -4;
a.m128i_i8[11] = -8;
a.m128i_i8[12] = -16;
a.m128i_i8[13] = -32;
a.m128i_i8[14] = -64;
a.m128i_i8[15] = -128;
mask.m128i_u8[0] = 0x0;
mask.m128i_u8[1] = 0x01;
mask.m128i_u8[2] = 0x02;
mask.m128i_u8[3] = 0x03;
mask.m128i_u8[4] = 0x04;
mask.m128i_u8[5] = 0x05;
mask.m128i_u8[6] = 0x06;
mask.m128i_u8[7] = 0x07;
mask.m128i_u8[8] = 0x00;
mask.m128i_u8[9] = 0x11;
mask.m128i_u8[10] = 0x22;
mask.m128i_u8[11] = 0x33;
mask.m128i_u8[12] = 0x44;
mask.m128i_u8[13] = 0x55;
mask.m128i_u8[14] = 0x66;
mask.m128i_u8[15] = 0x77;
__m128i res = _mm_shuffle_epi8(a, mask);
printf_s("Result res:\t%2d\t%2d\t%2d\t%2d\n\t\t%2d\t%2d\t%2d\t%2d\n",
res.m128i_i8[0], res.m128i_i8[1], res.m128i_i8[2],
res.m128i_i8[3], res.m128i_i8[4], res.m128i_i8[5],
res.m128i_i8[6], res.m128i_i8[7]);
printf_s("\t\t%2d\t%2d\t%2d\t%2d\n\t\t%2d\t%2d\t%2d\t%2d\n",
res.m128i_i8[8], res.m128i_i8[9], res.m128i_i8[10],
res.m128i_i8[11], res.m128i_i8[12], res.m128i_i8[13],
res.m128i_i8[14], res.m128i_i8[15]);
return 0;
}<file_sep>#include <inttypes.h>
#include <math.h>
#include <iostream>
#include <chrono>
#include <intrin.h>
#ifdef _WIN32
#include <windows.h>
#endif
inline uint64_t BSRFPOT(uint64_t size) {
unsigned long index;
_BitScanReverse64(&index, size);
/*size &= ~(1 << index);
if (size > 0)
index++;*/
return 1ull << index;
}
inline uint64_t LoopBasedFPOT(uint64_t size) {
uint8_t shift = 0;
while (size > 1) {
size >>= 1;
shift++;
}
return 1ull << shift;
}
inline uint64_t Log10BasedFPOT(uint64_t size) {
return 1ull << uint64_t(log10(double(size)) / log10(2.0));
}
inline uint64_t PowLog10BasedFPOT(uint64_t size) {
return uint64_t(pow(2, uint64_t(log10(double(size)) / log10(2.0))));
}
int main(int argc, char* argv[]) {
const uint64_t loops = 1000000;
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::time_point end;
std::chrono::high_resolution_clock::duration timeTaken;
#ifdef _WIN32
timeBeginPeriod(1);
//SetThreadAffinityMask(GetCurrentThread(), 0x1);
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
#else
#endif
uint64_t totalBSR, totalLoop, totalLog10, totalPow;
uint64_t totalBSR2, totalLoop2, totalLog102, totalPow2;
uint64_t valueBSR, valueLoop, valueLog10, valuePow;
uint64_t cnt = 0;
totalLoop2 = totalLog102 = totalPow2 = totalBSR2 = 0;
for (uint64_t s = 2; s < 256000; s += s >> 1) {
totalLoop = totalLog10 = totalPow = totalBSR = 0;
valueBSR = valueLoop = valueLog10 = valuePow = 0;
start = std::chrono::high_resolution_clock::now();
#pragma unroll
#pragma loop(ivdep)
for (uint64_t n = 0; n < loops; n++) {
valueBSR += BSRFPOT(s);
}
end = std::chrono::high_resolution_clock::now();
timeTaken = end - start;
totalBSR += timeTaken.count();
start = std::chrono::high_resolution_clock::now();
#pragma unroll
#pragma loop(ivdep)
for (uint64_t n = 0; n < loops; n++) {
valueLoop += LoopBasedFPOT(s);
}
end = std::chrono::high_resolution_clock::now();
timeTaken = end - start;
totalLoop += timeTaken.count();
start = std::chrono::high_resolution_clock::now();
#pragma unroll
#pragma loop(ivdep)
for (uint64_t n = 0; n < loops; n++) {
valueLog10 += Log10BasedFPOT(s);
}
end = std::chrono::high_resolution_clock::now();
timeTaken = end - start;
totalLog10 += timeTaken.count();
start = std::chrono::high_resolution_clock::now();
#pragma unroll
#pragma loop(ivdep)
for (uint64_t n = 0; n < loops; n++) {
valuePow += PowLog10BasedFPOT(s);
}
end = std::chrono::high_resolution_clock::now();
timeTaken = end - start;
totalPow += timeTaken.count();
printf("Size %ld\n", s);
printf("BSR | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalBSR, double(totalBSR) / loops, uint64_t(double(valueBSR) / loops));
printf("Loop | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalLoop, double(totalLoop) / loops, uint64_t(double(valueLoop) / loops));
printf("Log10 | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalLog10, double(totalLog10) / loops, uint64_t(double(valueLog10) / loops));
printf("Pow | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalPow, double(totalPow) / loops, uint64_t(double(valuePow) / loops));
totalBSR2 += totalBSR;
totalLoop2 += totalLoop;
totalLog102 += totalLog10;
totalPow2 += totalPow;
cnt++;
}
printf("Overall\n");
printf("BSR | Total: %16lld | Average: %8.8lf\n", totalBSR2, double(totalBSR2) / loops / cnt);
printf("Loop | Total: %16lld | Average: %8.8lf\n", totalLoop2, double(totalLoop2) / loops / cnt);
printf("Log10 | Total: %16lld | Average: %8.8lf\n", totalLog102, double(totalLog102) / loops / cnt);
printf("Pow | Total: %16lld | Average: %8.8lf\n", totalPow2, double(totalPow2) / loops / cnt);
std::cin.get();
return 0;
}<file_sep>cmake_minimum_required(VERSION 2.8)
project(InvSqrtDouble)
set(SOURCES
InvSqrt_Double.cpp)
set(HEADERS)
add_executable(InvSqrtDouble
${SOURCES}
${HEADERS})
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS
winmm)
endif()
target_link_libraries(InvSqrtDouble
${PLATFORM_LIBS})<file_sep>#pragma once
#include <windows.h>
void* memcpy_thread_initialize(size_t threads);
void memcpy_thread_set_memcpy(void* (*memcpy)(void*, const void*, size_t));
void memcpy_thread_env(void* env);
void* memcpy_thread(void* to, void* from, size_t size);
void memcpy_thread_finalize(void* env);
static inline void* memcpy_movsq(void* to, void* from, size_t size)
{
if (size % 8 == 0) {
__movsq(reinterpret_cast<unsigned long long*>(to), reinterpret_cast<unsigned long long*>(from),
size / 8);
} else if (size % 4 == 0) {
__movsd(reinterpret_cast<unsigned long*>(to), reinterpret_cast<unsigned long*>(from), size / 4);
} else if (size % 2 == 0) {
__movsw(reinterpret_cast<unsigned short*>(to), reinterpret_cast<unsigned short*>(from), size / 2);
} else {
__movsb(reinterpret_cast<unsigned char*>(to), reinterpret_cast<unsigned char*>(from), size);
}
return to;
};
static inline void* memcpy_movsd(void* to, void* from, size_t size)
{
if (size % 4 == 0) {
__movsd(reinterpret_cast<unsigned long*>(to), reinterpret_cast<unsigned long*>(from), size / 4);
} else if (size % 2 == 0) {
__movsw(reinterpret_cast<unsigned short*>(to), reinterpret_cast<unsigned short*>(from), size / 2);
} else {
__movsb(reinterpret_cast<unsigned char*>(to), reinterpret_cast<unsigned char*>(from), size);
}
return to;
};
static inline void* memcpy_movsw(void* to, void* from, size_t size)
{
if (size % 2 == 0) {
__movsw(reinterpret_cast<unsigned short*>(to), reinterpret_cast<unsigned short*>(from), size / 2);
} else {
__movsb(reinterpret_cast<unsigned char*>(to), reinterpret_cast<unsigned char*>(from), size);
}
return to;
};
static inline void* memcpy_movsb(void* to, void* from, size_t size)
{
__movsb(reinterpret_cast<unsigned char*>(to), reinterpret_cast<unsigned char*>(from), size);
return to;
};
<file_sep>#include <stdio.h>
#include <thread>
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <windows.h>
#define WM_HOTKEY_REGISTER WM_USER + 0x0001
#define WM_HOTKEY_UNREGISTER WM_USER + 0x0002
struct Hotkey {
std::string name;
UINT modifiers;
UINT vk;
int id;
};
std::queue<int> pressedhotkeys;
std::map<int, Hotkey> hotkeys;
bool thread_ready;
std::mutex thread_ready_mutex;
std::condition_variable thread_ready_cv;
uint16_t currentHotkeyId = 1;
std::queue<uint16_t> freeHotkeyIds;
int threadmain() {
MSG message;
BOOL breet;
PeekMessage(&message, (HWND)-1, 0, 0, PM_NOREMOVE);
if (!thread_ready) {
std::unique_lock<std::mutex> thread_ready_mutex;
thread_ready = true;
thread_ready_cv.notify_all();
}
while ((breet = GetMessage(&message, (HWND)-1, 0, 0)) != 0) {
//TranslateMessage(&message);
switch (message.message) {
case WM_HOTKEY:
{
SHORT state = GetAsyncKeyState(message.lParam >> 16);
std::cout << state << std::endl;
break;
}
case WM_HOTKEY_REGISTER:
{
Hotkey* hk = reinterpret_cast<Hotkey*>(message.lParam);
if (freeHotkeyIds.size() > 0) {
hk->id = freeHotkeyIds.front();
freeHotkeyIds.pop();
} else {
hk->id = currentHotkeyId++;
}
BOOL rhk_ret;
if ((rhk_ret = RegisterHotKey(0, hk->id, hk->modifiers, hk->vk)) != 0) {
hotkeys.insert(std::make_pair((hk->modifiers) | (hk->vk << 8), *hk));
} else {
DWORD error = GetLastError();
std::cout << "error while register hotkey" << error << '\n';
}
break;
}
case WM_HOTKEY_UNREGISTER:
{
Hotkey* hk = reinterpret_cast<Hotkey*>(message.lParam);
UnregisterHotKey(0, hk->id);
freeHotkeyIds.push(hk->id);
break;
}
default:
std::cout << "Unknown message." << std::endl;
break;
}
if (!WaitMessage())
break;
}
return 0;
}
std::thread thatthread;
int main() {
std::unique_lock<std::mutex> ulock(thread_ready_mutex);
thatthread = std::thread(threadmain);
PostThreadMessage(GetThreadId(thatthread.native_handle()),
WM_APP, 0, 0);
do {
thread_ready_cv.wait(ulock, [] {return thread_ready; });
std::cout << "mainloop woken" << '\n';
} while (!thread_ready);
Hotkey myhotkey;
myhotkey.modifiers = MOD_ALT;
myhotkey.vk = 0x41;
myhotkey.name = "Alt+A";
PostThreadMessage(GetThreadId(thatthread.native_handle()),
WM_HOTKEY_REGISTER, 0, reinterpret_cast<LPARAM>(&myhotkey));
thatthread.join();
return 0;
}<file_sep>#pragma once
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <queue>
namespace os {
class Semaphore {
public:
Semaphore(size_t count = 0);
~Semaphore();
void notify(size_t count = 1);
void wait(size_t count = 1);
bool try_wait(size_t count = 1);
private:
size_t m_Count;
std::mutex m_Mutex;
std::condition_variable m_CondVar;
};
struct ThreadTask {
bool completed;
bool failed;
ThreadTask() { completed = false; failed = false; }
virtual ~ThreadTask() {};
virtual bool work();
};
struct ThreadPoolWorker {
ThreadPoolWorker();
ThreadPoolWorker(const ThreadPoolWorker &) = delete;
std::thread thread;
bool isRunning;
bool doStop;
ThreadTask* currentTask;
};
class ThreadPool {
public:
ThreadPool(size_t threads);
~ThreadPool();
void PostTask(ThreadTask *task);
void PostTasks(ThreadTask *task[], size_t count);
ThreadTask* WaitTask();
static int ThreadMain(ThreadPoolWorker* worker, ThreadPool* pool);
private:
std::vector<ThreadPoolWorker*> m_Threads;
struct {
Semaphore semaphore;
std::queue<ThreadTask*> queue;
std::mutex mutex;
} m_Tasks;
};
}<file_sep>cmake_minimum_required(VERSION 3.2)
project(advmemcpy VERSION 1.0.0.0)
add_subdirectory(asmlib)
find_package (Threads)
set(HEADERS
"os.hpp"
"memcpy_adv.h"
)
set(SOURCES
"main.cpp"
"os.cpp"
"memcpy_thread.cpp"
"measurer.hpp"
"measurer.cpp"
"apex_memmove.h"
"apex_memmove.c"
"apex_memmove.cpp"
)
add_executable(advmemcpy
${SOURCES}
${HEADERS}
)
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS
winmm)
endif()
target_link_libraries(advmemcpy
${CMAKE_THREAD_LIBS_INIT}
${PLATFORM_LIBS}
asmlib
)
<file_sep>// InvSqrt_Double.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <random>
#include <chrono>
#include <thread>
#include <fstream>
#include <vector>
#include <tuple>
//#include <emmintrin.h>
//#include <ymmintrin.h>
#include <xmmintrin.h>
#include <intrin.h>
#ifdef _WIN32
#include <windows.h>
#endif
// Math
double invsqrt(double v) {
return 1.0 / sqrt(v);
}
void invsqrt2(double* v) {
v[0] = invsqrt(v[0]);
v[1] = invsqrt(v[1]);
}
void invsqrt4(double* v) {
invsqrt2(v);
invsqrt2(v + 2);
}
void invsqrt8(double* v) {
invsqrt4(v);
invsqrt4(v + 4);
}
void invsqrt16(double* v) {
invsqrt8(v);
invsqrt8(v + 8);
}
void invsqrt32(double* v) {
invsqrt16(v);
invsqrt16(v + 16);
}
void invsqrt64(double* v) {
invsqrt32(v);
invsqrt32(v + 32);
}
void invsqrt128(double* v) {
invsqrt64(v);
invsqrt64(v + 64);
}
void invsqrt256(double* v) {
invsqrt128(v);
invsqrt128(v + 128);
}
void invsqrt512(double* v) {
invsqrt256(v);
invsqrt256(v + 256);
}
// SSE Math
double invsqrt_sse(double v) {
const __m128d divisor = _mm_set_pd(1.0, 0);
__m128d value = _mm_set_pd(v, 0);
value = _mm_sqrt_pd(value);
value = _mm_div_pd(divisor, value);
double res;
_mm_storel_pd(&res, value);
return res;
}
void invsqrt_sse2(double* v) {
const __m128d divisor = _mm_set_pd(1.0, 1.0);
__m128d value = _mm_set_pd(v[0], v[1]);
value = _mm_sqrt_pd(value);
value = _mm_div_pd(divisor, value);
_mm_storeu_pd(v, value);
}
void invsqrt_sse4(double* v) {
invsqrt_sse2(v);
invsqrt_sse2(v + 2);
}
void invsqrt_sse8(double* v) {
invsqrt_sse4(v);
invsqrt_sse4(v + 4);
}
void invsqrt_sse16(double* v) {
invsqrt_sse8(v);
invsqrt_sse8(v + 8);
}
void invsqrt_sse32(double* v) {
invsqrt_sse16(v);
invsqrt_sse16(v + 16);
}
void invsqrt_sse64(double* v) {
invsqrt_sse32(v);
invsqrt_sse32(v + 32);
}
void invsqrt_sse128(double* v) {
invsqrt_sse64(v);
invsqrt_sse64(v + 64);
}
void invsqrt_sse256(double* v) {
invsqrt_sse128(v);
invsqrt_sse128(v + 128);
}
void invsqrt_sse512(double* v) {
invsqrt_sse256(v);
invsqrt_sse256(v + 256);
}
// Quake III
#define Q3_INVSQRT_CONSTANT 0x5fe6eb50c7b537a9ll
double invsqrt_q3(double v) {
union {
double f;
long long u;
} y = { v };
double x2 = y.f * 0.5;
y.u = Q3_INVSQRT_CONSTANT - (y.u >> 1);
y.f = 1.5 * (x2 * y.f * y.f);
return y.f;
}
void invsqrt_q32(double* v) {
v[0] = invsqrt_q3(v[0]);
v[1] = invsqrt_q3(v[1]);
}
void invsqrt_q34(double* v) {
invsqrt_q32(v);
invsqrt_q32(v + 2);
}
void invsqrt_q38(double* v) {
invsqrt_q34(v);
invsqrt_q34(v + 4);
}
void invsqrt_q316(double* v) {
invsqrt_q38(v);
invsqrt_q38(v + 8);
}
void invsqrt_q332(double* v) {
invsqrt_q316(v);
invsqrt_q316(v + 16);
}
void invsqrt_q364(double* v) {
invsqrt_q332(v);
invsqrt_q332(v + 32);
}
void invsqrt_q3128(double* v) {
invsqrt_q364(v);
invsqrt_q364(v + 64);
}
void invsqrt_q3256(double* v) {
invsqrt_q3128(v);
invsqrt_q3128(v + 128);
}
void invsqrt_q3512(double* v) {
invsqrt_q3256(v);
invsqrt_q3256(v + 256);
}
// Quake III SSE
double invsqrt_q3_sse(double v) {
const __m128i magic_constant = _mm_set_epi64x(Q3_INVSQRT_CONSTANT, 0);
const __m128d zero_point_five = _mm_set_pd(0.5, 0);
const __m128d one_point_five = _mm_set_pd(1.5, 0);
__m128d value = _mm_set_pd(v, 0);
__m128d halfvalue = _mm_mul_pd(value, one_point_five);
__m128i ivalue = _mm_castpd_si128(value);
//__m128i ivalue2 = _mm_srli_epi64(ivalue, 1);
ivalue.m128i_i64[0] = ivalue.m128i_i64[0] >> 1; // No Arithmethic shift right available for 64-bit int.
_mm_sub_epi64(magic_constant, ivalue);
value = _mm_castsi128_pd(ivalue);
// y.f = 1.5f - (x2 * y.f * y.f) part
value = _mm_mul_pd(value, value); // y.f * y.f
value = _mm_mul_pd(value, halfvalue); // x2 * y.f * y.f
value = _mm_sub_pd(one_point_five, value); // 1.5f - (x2 * y.f * y.f)
double res;
_mm_storel_pd(&res, value);
return res;
}
void invsqrt_q3_sse2(double* v) {
const __m128i magic_constant = _mm_set_epi64x(Q3_INVSQRT_CONSTANT, Q3_INVSQRT_CONSTANT);
const __m128d zero_point_five = _mm_set_pd(0.5, 0.5);
const __m128d one_point_five = _mm_set_pd(1.5, 1.5);
__m128d value = _mm_set_pd(v[0], v[1]);
__m128d halfvalue = _mm_mul_pd(value, one_point_five);
__m128i ivalue = _mm_castpd_si128(value);
//__m128i ivalue2 = _mm_srli_epi64(ivalue, 1);
ivalue.m128i_i64[0] = ivalue.m128i_i64[0] >> 1; // No Arithmetic shift right available for 64-bit int.
ivalue.m128i_i64[1] = ivalue.m128i_i64[1] >> 1; // No Arithmetic shift right available for 64-bit int.
_mm_sub_epi64(magic_constant, ivalue);
value = _mm_castsi128_pd(ivalue);
// y.f = 1.5f - (x2 * y.f * y.f) part
value = _mm_mul_pd(value, value); // y.f * y.f
value = _mm_mul_pd(value, halfvalue); // x2 * y.f * y.f
value = _mm_sub_pd(one_point_five, value); // 1.5f - (x2 * y.f * y.f)
_mm_storeu_pd(v, value);
}
void invsqrt_q3_sse4(double* v) {
invsqrt_q3_sse2(v);
invsqrt_q3_sse2(v + 2);
}
void invsqrt_q3_sse8(double* v) {
invsqrt_q3_sse4(v);
invsqrt_q3_sse4(v + 4);
}
void invsqrt_q3_sse16(double* v) {
invsqrt_q3_sse8(v);
invsqrt_q3_sse8(v + 8);
}
void invsqrt_q3_sse32(double* v) {
invsqrt_q3_sse16(v);
invsqrt_q3_sse16(v + 16);
}
void invsqrt_q3_sse64(double* v) {
invsqrt_q3_sse32(v);
invsqrt_q3_sse32(v + 32);
}
void invsqrt_q3_sse128(double* v) {
invsqrt_q3_sse64(v);
invsqrt_q3_sse64(v + 64);
}
void invsqrt_q3_sse256(double* v) {
invsqrt_q3_sse128(v);
invsqrt_q3_sse128(v + 128);
}
void invsqrt_q3_sse512(double* v) {
invsqrt_q3_sse256(v);
invsqrt_q3_sse256(v + 256);
}
typedef std::tuple<std::chrono::high_resolution_clock::duration, double, double> test_data;
typedef double(*sqrt_func_t)(double);
test_data test(double testValue, uint64_t testSize, sqrt_func_t func) {
double x = 0;
std::chrono::high_resolution_clock::duration t_total = std::chrono::nanoseconds(0);
for (uint64_t run = 0; run < testSize; run++) {
auto t_start = std::chrono::high_resolution_clock::now();
double y = func(testValue);
auto t_time = std::chrono::high_resolution_clock::now() - t_start;
x += y;
t_total += t_time;
}
return std::make_tuple(t_total, testValue, x);
}
typedef void(*sqrt_func_sse_t)(double*);
test_data test_sse_var(double testValue, uint64_t testSize, size_t comboSize, sqrt_func_sse_t func) {
// Version for testing SSE on four doubles at once.
double x = 0;
std::vector<double> y(comboSize);
uint64_t tmpTestSizeLoop = testSize / comboSize; // Divide by 4.
uint64_t tmpTestSizeRem = testSize % comboSize; // Remaining parts.
std::chrono::high_resolution_clock::duration t_total = std::chrono::nanoseconds(0);
for (uint64_t run = 0; run < tmpTestSizeLoop; run++) {
for (size_t vi = 0; vi < comboSize; vi++)
y[vi] = testValue + (double)vi;
auto t_start = std::chrono::high_resolution_clock::now();
func(y.data());
auto t_time = std::chrono::high_resolution_clock::now() - t_start;
for (size_t vi = 0; vi < comboSize; vi++)
x += y[vi];
t_total += t_time;
}
for (size_t vi = 0; vi < comboSize; vi++)
y[vi] = testValue + (double)vi;
auto t_start = std::chrono::high_resolution_clock::now();
func(y.data());
auto t_time = std::chrono::high_resolution_clock::now() - t_start;
for (size_t run = 0; run < tmpTestSizeRem; run++) {
x += y[run];
}
t_total += t_time;
return std::make_tuple(t_total, testValue, x);
}
void printLog(const char* format, ...) {
va_list args;
va_start(args, format);
std::vector<char> buf(_vscprintf(format, args)+1);
vsnprintf(buf.data(), buf.size(), format, args);
va_end(args);
std::cout << buf.data() << std::endl;
}
void printScore(const char* name, uint64_t timeNanoSeconds, uint64_t testSize, std::ofstream& csvfile) {
uint64_t time_ns = timeNanoSeconds % 1000000000;
uint64_t time_s = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::nanoseconds(timeNanoSeconds)).count() % 60;
uint64_t time_m = std::chrono::duration_cast<std::chrono::minutes>(std::chrono::nanoseconds(timeNanoSeconds)).count() % 60;
uint64_t time_h = std::chrono::duration_cast<std::chrono::hours>(std::chrono::nanoseconds(timeNanoSeconds)).count();
double time_single = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::nanoseconds(timeNanoSeconds)).count() / (double)testSize;
uint64_t pffloatfix = (uint64_t)round(time_single * 1000000);
printLog("| %-30s | %2llu:%02llu:%02llu.%09llu | %3lld.%06lld ns | %14llu |",
name,
time_h, time_m, time_s, time_ns,
pffloatfix / 1000000, pffloatfix % 1000000, // Because fuck you %3.6f, you broken piece of shit.
(uint64_t)floor(1000000.0 / time_single)
);
if (csvfile.good()) {
csvfile
<< '"' << name << '"' << ','
<< timeNanoSeconds << ','
<< time_single << ','
<< (uint64_t)floor(1000000.0 / time_single)
<< std::endl;
}
}
int main(int argc, const char** argv) {
double testValue = 1234.56789;
size_t testSize = 100000000;
#ifdef _WIN32
timeBeginPeriod(1);
#endif
std::vector<char> buf(1024);
sprintf_s(buf.data(), 1024, "%.*s.csv", (int)strlen(argv[0]) - 4, argv[0]);
std::ofstream csvfile(buf.data(), std::ofstream::out);
if (csvfile.good()) {
printLog("CSV file is written to %s.", buf.data());
}
if (csvfile.bad() | csvfile.fail())
printLog("CSV file can't be written to %s.", buf.data());
std::cout << "InvSqrt Double Test" << std::endl;
std::cout << " - Iterations: " << testSize << std::endl;
std::cout << " - Tested Value: " << testValue << std::endl;
csvfile << "\"Test\",\"Time (Total)\",\"Time (Single)\",\"Score (ops/msec)\"" << std::endl;
printLog( "| Test Name | Time (Total) | Time (Single) | Score (ops/ms) |");
printLog( "|:-------------------------------|-------------------:|--------------:|---------------:|");
//printLog("| Test Name | Time (Total) | Time (Single) | Score (ops/ms) |");
//printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
//printLog("| InvSqrt | 00:00:00.000000000 | 0000.00000 ns | 0000 000 000 0 |");
//printLog("| Quake III SSE InvSqrt (2 Ops) | ... | ... | ...");
#define TEST(name, function) \
{ \
std::this_thread::sleep_for(std::chrono::milliseconds(1)); \
auto tv = test(testValue, testSize, function); \
auto tvc = std::get<0>(tv); \
printScore(name, std::chrono::duration_cast<std::chrono::nanoseconds>(tvc).count(), testSize, csvfile); \
}
#define TESTMULTI(name, function, size) \
{ \
std::this_thread::sleep_for(std::chrono::milliseconds(1)); \
auto tv = test_sse_var(testValue, testSize, size, function); \
auto tvc = std::get<0>(tv); \
printScore(name, std::chrono::duration_cast<std::chrono::nanoseconds>(tvc).count(), testSize, csvfile); \
}
TEST("InvSqrt", invsqrt);
TESTMULTI("InvSqrt (2 Ops)", invsqrt2, 2);
TESTMULTI("InvSqrt (4 Ops)", invsqrt4, 4);
TESTMULTI("InvSqrt (8 Ops)", invsqrt8, 8);
TESTMULTI("InvSqrt (16 Ops)", invsqrt16, 16);
TESTMULTI("InvSqrt (32 Ops)", invsqrt32, 32);
TESTMULTI("InvSqrt (64 Ops)", invsqrt64, 64);
TESTMULTI("InvSqrt (128 Ops)", invsqrt128, 128);
TESTMULTI("InvSqrt (256 Ops)", invsqrt256, 256);
TESTMULTI("InvSqrt (512 Ops)", invsqrt512, 512);
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
TEST("InvSqrt SSE", invsqrt_sse);
TESTMULTI("InvSqrt SSE (2 Ops)", invsqrt_sse2, 2);
TESTMULTI("InvSqrt SSE (4 Ops)", invsqrt_sse4, 4);
TESTMULTI("InvSqrt SSE (8 Ops)", invsqrt_sse8, 8);
TESTMULTI("InvSqrt SSE (16 Ops)", invsqrt_sse16, 16);
TESTMULTI("InvSqrt SSE (32 Ops)", invsqrt_sse32, 32);
TESTMULTI("InvSqrt SSE (64 Ops)", invsqrt_sse64, 64);
TESTMULTI("InvSqrt SSE (128 Ops)", invsqrt_sse128, 128);
TESTMULTI("InvSqrt SSE (266 Ops)", invsqrt_sse256, 256);
TESTMULTI("InvSqrt SSE (512 Ops)", invsqrt_sse512, 512);
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
TEST("Q3 InvSqrt", invsqrt_q3);
TESTMULTI("Q3 InvSqrt (2 Ops)", invsqrt_q32, 2);
TESTMULTI("Q3 InvSqrt (4 Ops)", invsqrt_q34, 4);
TESTMULTI("Q3 InvSqrt (8 Ops)", invsqrt_q38, 8);
TESTMULTI("Q3 InvSqrt (16 Ops)", invsqrt_q316, 16);
TESTMULTI("Q3 InvSqrt (32 Ops)", invsqrt_q332, 32);
TESTMULTI("Q3 InvSqrt (64 Ops)", invsqrt_q364, 64);
TESTMULTI("Q3 InvSqrt (128 Ops)", invsqrt_q3128, 128);
TESTMULTI("Q3 InvSqrt (256 Ops)", invsqrt_q3256, 256);
TESTMULTI("Q3 InvSqrt (512 Ops)", invsqrt_q3512, 512);
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
TEST("Q3 InvSqrt SSE", invsqrt_q3_sse);
TESTMULTI("Q3 InvSqrt SSE (2 Ops)", invsqrt_q3_sse2, 2);
TESTMULTI("Q3 InvSqrt SSE (4 Ops)", invsqrt_q3_sse4, 4);
TESTMULTI("Q3 InvSqrt SSE (8 Ops)", invsqrt_q3_sse8, 8);
TESTMULTI("Q3 InvSqrt SSE (16 Ops)", invsqrt_q3_sse16, 16);
TESTMULTI("Q3 InvSqrt SSE (32 Ops)", invsqrt_q3_sse32, 32);
TESTMULTI("Q3 InvSqrt SSE (64 Ops)", invsqrt_q3_sse64, 64);
TESTMULTI("Q3 InvSqrt SSE (128 Ops)", invsqrt_q3_sse128, 128);
TESTMULTI("Q3 InvSqrt SSE (256 Ops)", invsqrt_q3_sse256, 256);
TESTMULTI("Q3 InvSqrt SSE (512 Ops)", invsqrt_q3_sse512, 512);
csvfile.close();
#ifdef _WIN32
timeEndPeriod(1);
#endif
getchar();
return 0;
}
<file_sep>// This test aims to check for incompatibilities with earlier versions of Visual Studio 2017.
// Primary goal here is to check std::align, as this currently breaks another project incorrectly.
//
#include <xmmintrin.h>
#include <vector>
#include <memory>
struct vec4 {
union {
struct { float x, y, z, w; };
float ptr[4];
__m128 m;
};
};
struct vec3 : vec4 {};
struct matrix4 {
struct vec4 x, y, z, t;
};
struct quat : vec4 {};
struct Part {
// Uncomment any of the following lines to get an error.
//vec3 position, scale, rotation;
//quat qrotation;
//matrix4 local, global;
bool localdirty;
bool dirty;
bool isquat;
};
int main(int argc, char const* argv[]) {
std::shared_ptr<Part> pt = std::make_shared<Part>();
return 0;
}<file_sep>#include <cinttypes>
#include <string>
#include <iostream>
// Constants
#define PI 3.1415926535897932384626433832795
#define PI2 6.283185307179586476925286766559
#define PI2_SQROOT 2.506628274631000502415765284811
inline double_t Gaussian1D(double_t x, double_t o) {
double_t c = (x / o);
double_t b = exp(-0.5 * c * c);
double_t a = (1.0 / (o * PI2_SQROOT));
return a * b;
}
int main(int argc, char* argv[]) {
double matrix[2];
matrix[0] = Gaussian1D(1.0, 1.0);
matrix[1] = Gaussian1D(0.0, 1.0);
double fullmatrix[3][3];
fullmatrix[0][0] = fullmatrix[0][2] = fullmatrix[2][0] = fullmatrix[2][2] = matrix[0] * matrix[0];
fullmatrix[1][0] = fullmatrix[1][2] = fullmatrix[0][1] = fullmatrix[2][1] = matrix[1] * matrix[0];
fullmatrix[1][1] = matrix[1];
double adjmatrix[3][3];
double avg = 0.0;
for (size_t x = 0; x <= 2; x++) {
for (size_t y = 0; y <= 2; y++) {
avg += fullmatrix[x][y];
}
}
double rv = 1.0 / avg;
for (size_t x = 0; x <= 2; x++) {
for (size_t y = 0; y <= 2; y++) {
adjmatrix[x][y] = fullmatrix[x][y] * rv;
}
}
std::cout << "Full Matrix" << '\n';
for (size_t y = 0; y <= 2; y++) {
std::cout << fullmatrix[0][y] << "; " << fullmatrix[1][y] << "; " << fullmatrix[2][y] << '\n';
}
std::cout << "Total: " << avg << '\n';
std::cout << "Inverse: " << rv << '\n';
std::cout << "Adjusted Matrix" << '\n';
for (size_t y = 0; y <= 2; y++) {
std::cout << adjmatrix[0][y] << "; " << adjmatrix[1][y] << "; " << adjmatrix[2][y] << '\n';
}
std::cout << std::endl;
std::cin.get();
return 0;
}<file_sep>cmake_minimum_required(VERSION 2.8)
project(is_power_of_two)
set(SOURCES
main.cpp)
set(HEADERS)
add_executable(${PROJECT_NAME}
${SOURCES}
${HEADERS})
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS winmm)
endif()
target_link_libraries(${PROJECT_NAME}
${PLATFORM_LIBS})<file_sep>#include <inttypes.h>
#include <math.h>
#include <iostream>
#include <chrono>
#include <intrin.h>
#ifdef _WIN32
#include <windows.h>
#endif
inline bool ispot_bitscan(uint64_t size) {
unsigned long index, index2;
_BitScanReverse64(&index, size);
_BitScanForward64(&index2, size);
return index == index2;
}
inline bool ispot_loop(uint64_t size) {
//bool have_bit = false;
//for (size_t index = 0; index < 64; index++) {
// bool cur = (size & (1ull << index)) != 0;
// if (have_bit && cur)
// return false;
// if (cur)
// have_bit = true;
//}
//return true;
bool have_bit = false;
for (size_t index = 63; index >= 0; index--) {
bool cur = (size & (1ull << index)) != 0;
if (cur) {
if (have_bit)
return false;
have_bit = true;
}
}
return true;
}
inline bool ispot_log10(uint64_t size) {
return (1ull << uint64_t(log10(double(size)) / log10(2.0))) == size;
}
int main(int argc, char* argv[]) {
const uint64_t loops = 10000000;
std::chrono::high_resolution_clock::time_point start;
std::chrono::high_resolution_clock::time_point end;
std::chrono::high_resolution_clock::duration timeTaken;
#ifdef _WIN32
timeBeginPeriod(1);
//SetThreadAffinityMask(GetCurrentThread(), 0x1);
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
#else
#endif
uint64_t totalBitScan, totalLoop, totalLog10, totalPow;
uint64_t overallBitScan, overallLoop, overallLog10, totalPow2;
uint64_t valueBitScan, valueLoop, valueLog10, valuePow;
uint64_t cnt = 0;
overallLoop = overallLog10 = totalPow2 = overallBitScan = 0;
for (uint64_t s = 2; s < 16384; s += 16) {
totalLoop = totalLog10 = totalPow = totalBitScan = 0;
valueBitScan = valueLoop = valueLog10 = valuePow = 0;
start = std::chrono::high_resolution_clock::now();
#pragma unroll
#pragma loop(ivdep)
for (uint64_t n = 0; n < loops; n++) {
valueBitScan += ispot_bitscan(s) ? 1 : 0;
}
end = std::chrono::high_resolution_clock::now();
timeTaken = end - start;
totalBitScan += timeTaken.count();
start = std::chrono::high_resolution_clock::now();
#pragma unroll
#pragma loop(ivdep)
for (uint64_t n = 0; n < loops; n++) {
valueLoop += ispot_loop(s) ? 1 : 0;
}
end = std::chrono::high_resolution_clock::now();
timeTaken = end - start;
totalLoop += timeTaken.count();
start = std::chrono::high_resolution_clock::now();
#pragma unroll
#pragma loop(ivdep)
for (uint64_t n = 0; n < loops; n++) {
valueLog10 += ispot_log10(s) ? 1 : 0;
}
end = std::chrono::high_resolution_clock::now();
timeTaken = end - start;
totalLog10 += timeTaken.count();
//printf("Size %ld\n", s);
//printf("BScan | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalBitScan, double(totalBitScan) / loops, uint64_t(double(valueBitScan) / loops));
//printf("Loop | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalLoop, double(totalLoop) / loops, uint64_t(double(valueLoop) / loops));
//printf("Log10 | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalLog10, double(totalLog10) / loops, uint64_t(double(valueLog10) / loops));
//printf("Pow | Total: %16lld | Average: %8.8lf | Value %16lld\n", totalPow, double(totalPow) / loops, uint64_t(double(valuePow) / loops));
overallBitScan += totalBitScan;
overallLoop += totalLoop;
overallLog10 += totalLog10;
totalPow2 += totalPow;
cnt++;
}
printf("Overall\n");
printf("BScan | Total: %16lld | Average: %8.8lf\n", overallBitScan, double(overallBitScan) / loops / cnt);
printf("Loop | Total: %16lld | Average: %8.8lf\n", overallLoop, double(overallLoop) / loops / cnt);
printf("Log10 | Total: %16lld | Average: %8.8lf\n", overallLog10, double(overallLog10) / loops / cnt);
printf("Pow | Total: %16lld | Average: %8.8lf\n", totalPow2, double(totalPow2) / loops / cnt);
std::cin.get();
return 0;
}<file_sep>cmake_minimum_required(VERSION 3.5.0)
project(sandbox VERSION 0.0.0.0)
# Sub-Projects
add_subdirectory(advmemcpy)
#add_subdirectory(InvSqrt_Single)
#add_subdirectory(InvSqrt_Double)
#add_subdirectory(SSESwizzle)
#add_subdirectory(FindPowerOfTwo)
#add_subdirectory(RegisterHotkey)
#add_subdirectory(Vulkan01)
#add_subdirectory(vs2017)
#add_subdirectory(GaussianMatrix)
#add_subdirectory(is_power_of_two)<file_sep>// FloatMathSpeedTest.cpp : Defines the entry point for the console application.
//
#include <chrono>
#include <vector>
#include <tuple>
#include <xmmintrin.h>
#include <iostream>
#include <fstream>
//#include <ofstream>
#include <thread>
#include <random>
#ifdef _WIN32
#include <windows.h>
#endif
// Standard Math
float invsqrt(float v) {
return 1.0f / sqrtf(v);
}
void invsqrt2(float* v) {
v[0] = invsqrt(v[0]);
v[1] = invsqrt(v[1]);
}
void invsqrt4(float* v) {
invsqrt2(v);
invsqrt2(v + 2);
}
void invsqrt8(float* v) {
invsqrt4(v);
invsqrt4(v + 4);
}
void invsqrt16(float* v) {
invsqrt8(v);
invsqrt8(v + 8);
}
void invsqrt32(float* v) {
invsqrt16(v);
invsqrt16(v + 16);
}
void invsqrt64(float* v) {
invsqrt32(v);
invsqrt32(v + 32);
}
void invsqrt128(float* v) {
invsqrt64(v);
invsqrt64(v + 64);
}
void invsqrt256(float* v) {
invsqrt128(v);
invsqrt128(v + 128);
}
void invsqrt512(float* v) {
invsqrt256(v);
invsqrt256(v + 256);
}
// SSE Math
float invsqrt_sse(float v) {
__m128 mv = _mm_set_ps(v, 0, 0, 0);
const __m128 dv = _mm_set_ps(1.0f, 0, 0, 0);
auto sv = _mm_sqrt_ps(mv);
sv = _mm_div_ps(dv, sv);
float result;
_mm_store1_ps(&result, sv);
return result;
}
void invsqrt_sse2(float* v) {
const __m128 dv = _mm_set_ps(1.0f, 1.0f, 1.0f, 1.0f);
__m128 mv = _mm_set_ps(v[0], v[1], 0, 0);
mv = _mm_sqrt_ps(mv);
mv = _mm_div_ps(dv, mv);
float result[4];
_mm_storeu_ps(result, mv);
v[0] = result[0];
v[1] = result[1];
}
void invsqrt_sse4(float* v) {
const __m128 dv = _mm_set_ps(1.0f, 1.0f, 1.0f, 1.0f);
__m128 mv = _mm_set_ps(v[0], v[1], v[2], v[3]);
mv = _mm_sqrt_ps(mv);
mv = _mm_div_ps(dv, mv);
_mm_storeu_ps(v, mv);
}
void invsqrt_sse8(float* v) {
invsqrt_sse4(v);
invsqrt_sse4(v + 4);
}
void invsqrt_sse16(float* v) {
invsqrt_sse8(v);
invsqrt_sse8(v + 8);
}
void invsqrt_sse32(float* v) {
invsqrt_sse16(v);
invsqrt_sse16(v + 16);
}
void invsqrt_sse64(float* v) {
invsqrt_sse32(v);
invsqrt_sse32(v + 32);
}
void invsqrt_sse128(float* v) {
invsqrt_sse64(v);
invsqrt_sse64(v + 64);
}
void invsqrt_sse256(float* v) {
invsqrt_sse128(v);
invsqrt_sse128(v + 128);
}
void invsqrt_sse512(float* v) {
invsqrt_sse256(v);
invsqrt_sse256(v + 256);
}
#define USE_LOMONT_CONSTANT
#ifndef USE_LOMONT_CONSTANT
#define FASTINVSQRT 0x5F3759DF // Carmack
#else
#define FASTINVSQRT 0x5F375A86 // <NAME>
#endif
// Quake III
float invsqrt_q3(float v) {
union {
float f;
long u;
} y = { v };
float x2 = v * 0.5f;
y.u = FASTINVSQRT - (y.u >> 1);
y.f = (1.5f - (x2 * y.f * y.f));
return y.f;
}
void invsqrt_q32(float* v) {
v[0] = invsqrt_q3(v[0]);
v[1] = invsqrt_q3(v[1]);
}
void invsqrt_q34(float* v) {
invsqrt_q32(v);
invsqrt_q32(v + 2);
}
void invsqrt_q38(float* v) {
invsqrt_q34(v);
invsqrt_q34(v + 4);
}
void invsqrt_q316(float* v) {
invsqrt_q38(v);
invsqrt_q38(v + 8);
}
void invsqrt_q332(float* v) {
invsqrt_q316(v);
invsqrt_q316(v + 16);
}
void invsqrt_q364(float* v) {
invsqrt_q332(v);
invsqrt_q332(v + 32);
}
void invsqrt_q3128(float* v) {
invsqrt_q364(v);
invsqrt_q364(v + 64);
}
void invsqrt_q3256(float* v) {
invsqrt_q3128(v);
invsqrt_q3128(v + 128);
}
void invsqrt_q3512(float* v) {
invsqrt_q3256(v);
invsqrt_q3256(v + 256);
}
float invsqrt_q3_sse(float v) {
const __m128i magic_constant = _mm_set_epi32(FASTINVSQRT, 0, 0, 0);
const __m128 zero_point_five = _mm_set_ps(0.5f, 0, 0, 0);
const __m128 one_point_five = _mm_set_ps(1.5f, 0, 0, 0);
__m128 value = _mm_set_ps(v, 0, 0, 0); // y.f = v
__m128 halfvalue = _mm_mul_ps(value, zero_point_five); // x2 = v * 0.5f
__m128i ivalue = _mm_castps_si128(value); // y.u (union) y.f
ivalue = _mm_srai_epi32(ivalue, 1); // y.u >> 1
ivalue = _mm_sub_epi32(magic_constant, ivalue); // FASTINVSQRT - (y.u >> 1)
value = _mm_castsi128_ps(ivalue); // y.f (union) y.u
// y.f = 1.5f - (x2 * y.f * y.f) part
value = _mm_mul_ps(value, value); // y.f * y.f
value = _mm_mul_ps(value, halfvalue); // x2 * y.f * y.f
value = _mm_sub_ps(one_point_five, value); // 1.5f - (x2 * y.f * y.f)
float result;
_mm_store1_ps(&result, value);
return result;
}
void invsqrt_q3_sse2(float* v) {
const __m128i magic_constant = _mm_set_epi32(FASTINVSQRT, FASTINVSQRT, 0, 0);
const __m128 zero_point_five = _mm_set_ps(0.5f, 0.5f, 0, 0);
const __m128 one_point_five = _mm_set_ps(1.5f, 1.5f, 0, 0);
__m128 value = _mm_set_ps(v[0], v[1], 0, 0); // y.f = v
__m128 halfvalue = _mm_mul_ps(value, zero_point_five); // x2 = v * 0.5f
__m128i ivalue = _mm_castps_si128(value); // y.u (union) y.f
ivalue = _mm_srai_epi32(ivalue, 1); // y.u >> 1
ivalue = _mm_sub_epi32(magic_constant, ivalue); // FASTINVSQRT - (y.u >> 1)
value = _mm_castsi128_ps(ivalue); // y.f (union) y.u
// y.f = 1.5f - (x2 * y.f * y.f) part
value = _mm_mul_ps(value, value); // y.f * y.f
value = _mm_mul_ps(value, halfvalue); // x2 * y.f * y.f
value = _mm_sub_ps(one_point_five, value); // 1.5f - (x2 * y.f * y.f)
// result
float result[4];
_mm_storeu_ps(v, value);
v[0] = result[0];
v[1] = result[1];
}
void invsqrt_q3_sse4(float* v) {
const __m128i magic_constant = _mm_set_epi32(FASTINVSQRT, FASTINVSQRT, FASTINVSQRT, FASTINVSQRT);
const __m128 zero_point_five = _mm_set_ps(0.5f, 0.5f, 0.5f, 0.5f);
const __m128 one_point_five = _mm_set_ps(1.5f, 1.5f, 1.5f, 1.5f);
__m128 value = _mm_set_ps(v[0], v[1], v[2], v[3]); // y.f = v
__m128 halfvalue = _mm_mul_ps(value, zero_point_five); // x2 = v * 0.5f
__m128i ivalue = _mm_castps_si128(value); // y.u (union) y.f
ivalue = _mm_srai_epi32(ivalue, 1); // y.u >> 1
ivalue = _mm_sub_epi32(magic_constant, ivalue); // FASTINVSQRT - (y.u >> 1)
value = _mm_castsi128_ps(ivalue); // y.f (union) y.u
// y.f = 1.5f - (x2 * y.f * y.f) part
value = _mm_mul_ps(value, value); // y.f * y.f
value = _mm_mul_ps(value, halfvalue); // x2 * y.f * y.f
value = _mm_sub_ps(one_point_five, value); // 1.5f - (x2 * y.f * y.f)
// result
_mm_storeu_ps(v, value);
}
void invsqrt_q3_sse8(float* v) {
invsqrt_q3_sse4(v);
invsqrt_q3_sse4(v + 4);
}
void invsqrt_q3_sse16(float* v) {
invsqrt_q3_sse8(v);
invsqrt_q3_sse8(v + 8);
}
void invsqrt_q3_sse32(float* v) {
invsqrt_q3_sse16(v);
invsqrt_q3_sse16(v + 16);
}
void invsqrt_q3_sse64(float* v) {
invsqrt_q3_sse32(v);
invsqrt_q3_sse32(v + 32);
}
void invsqrt_q3_sse128(float* v) {
invsqrt_q3_sse64(v);
invsqrt_q3_sse64(v + 64);
}
void invsqrt_q3_sse256(float* v) {
invsqrt_q3_sse128(v);
invsqrt_q3_sse128(v + 128);
}
void invsqrt_q3_sse512(float* v) {
invsqrt_q3_sse256(v);
invsqrt_q3_sse256(v + 256);
}
typedef std::tuple<std::chrono::high_resolution_clock::duration, float, float> test_data;
typedef float(*sqrt_func_t)(float);
test_data test(float testValue, uint64_t testSize, sqrt_func_t func) {
float x = 0;
std::chrono::high_resolution_clock::duration t_total = std::chrono::nanoseconds(0);
for (uint64_t run = 0; run < testSize; run++) {
auto t_start = std::chrono::high_resolution_clock::now();
float y = func(testValue);
auto t_time = std::chrono::high_resolution_clock::now() - t_start;
x += y;
t_total += t_time;
}
return std::make_tuple(t_total, testValue, x);
}
typedef void(*sqrt_func_sse_t)(float*);
test_data test_sse_var(float testValue, uint64_t testSize, size_t comboSize, sqrt_func_sse_t func) {
// Version for testing SSE on four floats at once.
float x = 0;
std::vector<float> y(comboSize);
uint64_t tmpTestSizeLoop = testSize / comboSize; // Divide by 4.
uint64_t tmpTestSizeRem = testSize % comboSize; // Remaining parts.
std::chrono::high_resolution_clock::duration t_total = std::chrono::nanoseconds(0);
for (uint64_t run = 0; run < tmpTestSizeLoop; run++) {
for (size_t vi = 0; vi < comboSize; vi++)
y[vi] = testValue + (float)vi;
auto t_start = std::chrono::high_resolution_clock::now();
func(y.data());
auto t_time = std::chrono::high_resolution_clock::now() - t_start;
for (size_t vi = 0; vi < comboSize; vi++)
x += y[vi];
t_total += t_time;
}
for (size_t vi = 0; vi < comboSize; vi++)
y[vi] = testValue + (float)vi;
auto t_start = std::chrono::high_resolution_clock::now();
func(y.data());
auto t_time = std::chrono::high_resolution_clock::now() - t_start;
for (size_t run = 0; run < tmpTestSizeRem; run++) {
x += y[run];
}
t_total += t_time;
return std::make_tuple(t_total, testValue, x);
}
void printLog(const char* format, ...) {
va_list args;
va_start(args, format);
std::vector<char> buf(_vscprintf(format, args) + 1);
vsnprintf(buf.data(), buf.size(), format, args);
va_end(args);
std::cout << buf.data() << std::endl;
}
void printScore(const char* name, uint64_t timeNanoSeconds, uint64_t testSize, std::ofstream& csvfile) {
uint64_t time_ns = timeNanoSeconds % 1000000000;
uint64_t time_s = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::nanoseconds(timeNanoSeconds)).count() % 60;
uint64_t time_m = std::chrono::duration_cast<std::chrono::minutes>(std::chrono::nanoseconds(timeNanoSeconds)).count() % 60;
uint64_t time_h = std::chrono::duration_cast<std::chrono::hours>(std::chrono::nanoseconds(timeNanoSeconds)).count();
double time_single = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::nanoseconds(timeNanoSeconds)).count() / (double)testSize;
uint64_t pffloatfix = (uint64_t)round(time_single * 1000000);
printLog("| %-30s | %2llu:%02llu:%02llu.%09llu | %3lld.%06lld ns | %14llu |",
name,
time_h, time_m, time_s, time_ns,
pffloatfix / 1000000, pffloatfix % 1000000, // Because fuck you %3.6f, you broken piece of shit.
(uint64_t)floor(1000000.0 / time_single)
);
if (csvfile.good()) {
csvfile
<< '"' << name << '"' << ','
<< timeNanoSeconds << ','
<< time_single << ','
<< (uint64_t)floor(1000000.0 / time_single)
<< std::endl;
}
}
int main(int argc, const char** argv) {
float testValue = 1234.56789f;
size_t testSize = 100000000;
#ifdef _WIN32
timeBeginPeriod(1);
#endif
std::vector<char> buf(1024);
sprintf_s(buf.data(), 1024, "%.*s.csv", strlen(argv[0]) - 4, argv[0]);
std::ofstream csvfile(buf.data(), std::ofstream::out);
if (csvfile.good()) {
printLog("CSV file is written to %s.", buf.data());
}
if (csvfile.bad() | csvfile.fail())
printLog("CSV file can't be written to %s.", buf.data());
std::cout << "InvSqrt Single Test" << std::endl;
std::cout << " - Iterations: " << testSize << std::endl;
std::cout << " - Tested Value: " << testValue << std::endl;
csvfile << "\"Test\",\"Time (Total)\",\"Time (Single)\",\"Score (ops/msec)\"" << std::endl;
printLog("| Test Name | Time (Total) | Time (Single) | Score (ops/ms) |");
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
//printLog("| Test Name | Time (Total) | Time (Single) | Score (ops/ms) |");
//printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
//printLog("| InvSqrt | 00:00:00.000000000 | 0000.00000 ns | 0000 000 000 0 |");
//printLog("| Quake III SSE InvSqrt (2 Ops) | ... | ... | ...");
#define TEST(name, function) \
{ \
std::this_thread::sleep_for(std::chrono::milliseconds(1)); \
auto tv = test(testValue, testSize, function); \
auto tvc = std::get<0>(tv); \
printScore(name, std::chrono::duration_cast<std::chrono::nanoseconds>(tvc).count(), testSize, csvfile); \
}
#define TESTMULTI(name, function, size) \
{ \
std::this_thread::sleep_for(std::chrono::milliseconds(1)); \
auto tv = test_sse_var(testValue, testSize, size, function); \
auto tvc = std::get<0>(tv); \
printScore(name, std::chrono::duration_cast<std::chrono::nanoseconds>(tvc).count(), testSize, csvfile); \
}
TEST("InvSqrt", invsqrt);
TESTMULTI("InvSqrt (2 Ops)", invsqrt2, 2);
TESTMULTI("InvSqrt (4 Ops)", invsqrt4, 4);
TESTMULTI("InvSqrt (8 Ops)", invsqrt8, 8);
TESTMULTI("InvSqrt (16 Ops)", invsqrt16, 16);
TESTMULTI("InvSqrt (32 Ops)", invsqrt32, 32);
TESTMULTI("InvSqrt (64 Ops)", invsqrt64, 64);
TESTMULTI("InvSqrt (128 Ops)", invsqrt128, 128);
TESTMULTI("InvSqrt (256 Ops)", invsqrt256, 256);
TESTMULTI("InvSqrt (512 Ops)", invsqrt512, 512);
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
TEST("InvSqrt SSE", invsqrt_sse);
TESTMULTI("InvSqrt SSE (2 Ops)", invsqrt_sse2, 2);
TESTMULTI("InvSqrt SSE (4 Ops)", invsqrt_sse4, 4);
TESTMULTI("InvSqrt SSE (8 Ops)", invsqrt_sse8, 8);
TESTMULTI("InvSqrt SSE (16 Ops)", invsqrt_sse16, 16);
TESTMULTI("InvSqrt SSE (32 Ops)", invsqrt_sse32, 32);
TESTMULTI("InvSqrt SSE (64 Ops)", invsqrt_sse64, 64);
TESTMULTI("InvSqrt SSE (128 Ops)", invsqrt_sse128, 128);
TESTMULTI("InvSqrt SSE (266 Ops)", invsqrt_sse256, 256);
TESTMULTI("InvSqrt SSE (512 Ops)", invsqrt_sse512, 512);
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
TEST("Q3 InvSqrt", invsqrt_q3);
TESTMULTI("Q3 InvSqrt (2 Ops)", invsqrt_q32, 2);
TESTMULTI("Q3 InvSqrt (4 Ops)", invsqrt_q34, 4);
TESTMULTI("Q3 InvSqrt (8 Ops)", invsqrt_q38, 8);
TESTMULTI("Q3 InvSqrt (16 Ops)", invsqrt_q316, 16);
TESTMULTI("Q3 InvSqrt (32 Ops)", invsqrt_q332, 32);
TESTMULTI("Q3 InvSqrt (64 Ops)", invsqrt_q364, 64);
TESTMULTI("Q3 InvSqrt (128 Ops)", invsqrt_q3128, 128);
TESTMULTI("Q3 InvSqrt (256 Ops)", invsqrt_q3256, 256);
TESTMULTI("Q3 InvSqrt (512 Ops)", invsqrt_q3512, 512);
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
TEST("Q3 InvSqrt SSE", invsqrt_q3_sse);
TESTMULTI("Q3 InvSqrt SSE (2 Ops)", invsqrt_q3_sse2, 2);
TESTMULTI("Q3 InvSqrt SSE (4 Ops)", invsqrt_q3_sse4, 4);
TESTMULTI("Q3 InvSqrt SSE (8 Ops)", invsqrt_q3_sse8, 8);
TESTMULTI("Q3 InvSqrt SSE (16 Ops)", invsqrt_q3_sse16, 16);
TESTMULTI("Q3 InvSqrt SSE (32 Ops)", invsqrt_q3_sse32, 32);
TESTMULTI("Q3 InvSqrt SSE (64 Ops)", invsqrt_q3_sse64, 64);
TESTMULTI("Q3 InvSqrt SSE (128 Ops)", invsqrt_q3_sse128, 128);
TESTMULTI("Q3 InvSqrt SSE (256 Ops)", invsqrt_q3_sse256, 256);
TESTMULTI("Q3 InvSqrt SSE (512 Ops)", invsqrt_q3_sse512, 512);
printLog("|:-------------------------------|-------------------:|--------------:|---------------:|");
csvfile.close();
#ifdef _WIN32
timeEndPeriod(1);
#endif
getchar();
return 0;
}
<file_sep>/*
Sample for DataPath
Copyright (C) 2019 <NAME> <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <chrono>
#include <map>
#include <memory>
#include <mutex>
class measurer : std::enable_shared_from_this<measurer> {
std::map<std::chrono::nanoseconds, size_t> timings;
std::mutex lock;
public:
class instance {
measurer* parent;
std::chrono::high_resolution_clock::time_point start;
public:
instance(measurer* parent);
~instance();
void cancel();
};
public:
measurer();
~measurer();
std::shared_ptr<measurer::instance> track();
void track(std::chrono::nanoseconds duration);
uint64_t count();
std::chrono::nanoseconds total_duration();
double_t average_duration();
std::chrono::nanoseconds percentile(double_t percentile, bool by_time = false);
};
<file_sep>cmake_minimum_required(VERSION 2.8)
project(Vulkan01)
set(SOURCES
main.cpp)
set(HEADERS)
add_executable(Vulkan01
${SOURCES}
${HEADERS})
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS)
endif()
target_link_libraries(Vulkan01
${PLATFORM_LIBS})<file_sep>cmake_minimum_required(VERSION 2.8)
project(vs2017_aligned-storage)
set(SOURCES
main.cpp)
set(HEADERS)
add_executable(${PROJECT_NAME}
${SOURCES}
${HEADERS})
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS)
endif()
target_link_libraries(${PROJECT_NAME}
${PLATFORM_LIBS})<file_sep>// advmemcpy.cpp : Defines the entry point for the console application.
//
#include <asmlib.h>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
#include <intrin.h>
#include "apex_memmove.h"
#include "measurer.hpp"
#include "memcpy_adv.h"
#undef max
#define MEASURE_TEST_CYCLES 1000
#define SIZE(W, H, C, N) \
{ \
W *H *C, N \
}
using namespace std;
/**
* Allocator for aligned data.
*
* Modified from the Mallocator from <NAME>.
* <http://blogs.msdn.com/b/vcblog/archive/2008/08/28/the-mallocator.aspx>
*/
template<typename T, std::size_t Alignment>
class aligned_allocator {
public:
// The following will be the same for virtually all allocators.
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
typedef std::size_t size_type;
typedef ptrdiff_t difference_type;
T* address(T& r) const
{
return &r;
}
const T* address(const T& s) const
{
return &s;
}
std::size_t max_size() const
{
// The following has been carefully written to be independent of
// the definition of size_t and to avoid signed/unsigned warnings.
return (static_cast<std::size_t>(0) - static_cast<std::size_t>(1)) / sizeof(T);
}
// The following must be the same for all allocators.
template<typename U>
struct rebind {
typedef aligned_allocator<U, Alignment> other;
};
bool operator!=(const aligned_allocator& other) const
{
return !(*this == other);
}
void construct(T* const p, const T& t) const
{
void* const pv = static_cast<void*>(p);
new (pv) T(t);
}
void destroy(T* const p) const
{
p->~T();
}
// Returns true if and only if storage allocated from *this
// can be deallocated from other, and vice versa.
// Always returns true for stateless allocators.
bool operator==(const aligned_allocator& other) const
{
return true;
}
// Default constructor, copy constructor, rebinding constructor, and destructor.
// Empty for stateless allocators.
aligned_allocator() {}
aligned_allocator(const aligned_allocator&) {}
template<typename U>
aligned_allocator(const aligned_allocator<U, Alignment>&)
{}
~aligned_allocator() {}
// The following will be different for each allocator.
T* allocate(const std::size_t n) const
{
// The return value of allocate(0) is unspecified.
// Mallocator returns NULL in order to avoid depending
// on malloc(0)'s implementation-defined behavior
// (the implementation can define malloc(0) to return NULL,
// in which case the bad_alloc check below would fire).
// All allocators can return NULL in this case.
if (n == 0) {
return NULL;
}
// All allocators should contain an integer overflow check.
// The Standardization Committee recommends that std::length_error
// be thrown in the case of integer overflow.
if (n > max_size()) {
throw std::length_error("aligned_allocator<T>::allocate() - Integer overflow.");
}
// Mallocator wraps malloc().
void* const pv = _mm_malloc(n * sizeof(T), Alignment);
// Allocators should throw std::bad_alloc in the case of memory allocation failure.
if (pv == NULL) {
throw std::bad_alloc();
}
return static_cast<T*>(pv);
}
void deallocate(T* const p, const std::size_t n) const
{
_mm_free(p);
}
// The following will be the same for all allocators that ignore hints.
template<typename U>
T* allocate(const std::size_t n, const U* /* const hint */) const
{
return allocate(n);
}
// Allocators are not required to be assignable, so
// all allocators should have a private unimplemented
// assignment operator. Note that this will trigger the
// off-by-default (enabled under /Wall) warning C4626
// "assignment operator could not be generated because a
// base class assignment operator is inaccessible" within
// the STL headers, but that warning is useless.
private:
aligned_allocator& operator=(const aligned_allocator&) = delete;
};
std::map<size_t, std::string> test_sizes{
//SIZE(1, 1, 1024, "1KB"),
//SIZE(1, 2, 1024, "2KB"),
//SIZE(1, 4, 1024, "4KB"),
//SIZE(1, 8, 1024, "8KB"),
//SIZE(1, 16, 1024, "16KB"),
//SIZE(1, 32, 1024, "32KB"),
//SIZE(1, 64, 1024, "64KB"),
//SIZE(1, 128, 1024, "128KB"),
//SIZE(1, 256, 1024, "256KB"),
//SIZE(1, 512, 1024, "512KB"),
//SIZE(1, 1024, 1024, "1MB"), SIZE(2, 1024, 1024, "2MB"), SIZE(3, 1024, 1024, "2MB"),
//SIZE(4, 1024, 1024, "4MB"), SIZE(5, 1024, 1024, "8MB"), SIZE(6, 1024, 1024, "8MB"),
//SIZE(7, 1024, 1024, "8MB"), SIZE(8, 1024, 1024, "8MB"), SIZE(16, 1024, 1024, "16MB"),
//SIZE(32, 1024, 1024, "32MB"), SIZE(64, 1024, 1024, "64MB"),
SIZE(1280, 720, 2, "1280x720 NV12"),
SIZE(1980, 1080, 2, "1920x1080 NV12"),
SIZE(2560, 1440, 2, "2560x1440 NV12"),
SIZE(3840, 2160, 2, "3840x2160 NV12"),
};
std::map<std::string, std::function<void*(void* to, void* from, size_t size)>> functions{
{"A_memcpy", A_memcpy},
{"memcpy", &std::memcpy},
//{ "movsb", &memcpy_movsb },
//{ "movsw", &memcpy_movsw },
//{ "movsd", &memcpy_movsd },
//{ "movsq", &memcpy_movsq },
{"apex_memcpy", [](void* t, void* f, size_t s) { return apex::memcpy(t, f, s); }},
//{ "advmemcpy", &memcpy_thread },
//{ "advmemcpy_apex", &memcpy_thread },
};
std::map<std::string, std::function<void()>> initializers{
{"apex_memcpy", []() { apex::memcpy(0, 0, 0); }},
{"A_memcpy", []() {}},
};
int32_t main(int32_t argc, const char* argv[])
{
int64_t rw1, rw2, rw3, rw4, rw5, rw6, rw7, rw8;
std::vector<uint8_t, aligned_allocator<uint8_t, 32>> buf_from, buf_to, cache_kill;
size_t largest_size = 0;
for (auto test : test_sizes) {
if (test.first > largest_size)
largest_size = test.first;
}
buf_from.resize(largest_size * 4);
buf_to.resize(largest_size * 4);
cache_kill.resize(64 * 1024 * 1024);
srand(static_cast<uint32_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count()
% 0xFFFFFFFFull));
measurer fence, fenc2, flush;
std::cin.get();
for (auto test : test_sizes) {
std::cout << "Testing '" << test.second << "' ( " << (test.first) << " B )..." << std::endl;
std::cout << "Name | Avg. MB/s | 95.0% MB/s | 99.0% MB/s | 99.9% MB/s " << std::endl
<< "----------------+------------+------------+------------+------------" << std::endl;
size_t size = test.first;
for (auto func : functions) {
measurer measure;
auto inits = initializers.find(func.first);
if (inits != initializers.end()) {
inits->second();
}
std::cout << setw(16) << setiosflags(ios::left) << func.first;
std::cout << setw(0) << resetiosflags(ios::left) << "|" << std::flush;
for (size_t idx = 0; idx < MEASURE_TEST_CYCLES; idx++) {
// Get a random address to work from, but don't drop the 32-byte alignment.
uint8_t* from = buf_from.data() + ((rand() % largest_size * 3) & ~0b011111);
uint8_t* to = buf_to.data() + ((rand() % largest_size * 3) & ~0b011111);
// Make sure the entire address space is invalidated and flushed from cache.
{
auto tracker = flush.track();
for (size_t sz = 0; sz < size; sz++) {
_mm_clflush(from + sz);
cache_kill.at(rand() % cache_kill.size()) =
rand() % std::numeric_limits<uint8_t>::max();
}
}
// Fence to avoid any incorrect late load/stores that can affect timings.
{
auto tracker = fence.track();
_mm_mfence();
}
{
auto tracker = measure.track();
func.second(to, from, size);
}
// Fence to avoid any incorrect late load/stores that can affect timings.
{
auto tracker = fenc2.track();
_mm_mfence();
}
// Fence to avoid any incorrect late load/stores that can affect timings.
// ToDo: Should this actually be in the loop?
//_mm_mfence();
// Clear Insutruction Caches and likely have an impact on branch caches.
for (size_t idx2 = 0; idx < 100; idx++) {
rw1 += rw2;
rw2 -= rw3 * rw7;
rw8 = rw2 - rw1;
rw6 = rw3 + rw8;
rw5 = rw4 / rw3;
rw2 *= rw8;
rw3++;
if (rw1 == rw2) {
rw2 = rw3;
} else {
rw1 = rw2;
}
if (rw2)
rw2 = rw6;
else
rw6 = rw2;
}
}
double_t size_kb = (static_cast<double_t>(test.first) / 1024 / 1024);
auto time_avg = measure.average_duration();
auto time_950 = measure.percentile(0.95);
auto time_990 = measure.percentile(0.99);
auto time_999 = measure.percentile(0.999);
double_t kbyte_avg = size_kb / (static_cast<double_t>(time_avg) / 1000000000);
double_t kbyte_950 = size_kb / (static_cast<double_t>(time_950.count()) / 1000000000);
double_t kbyte_990 = size_kb / (static_cast<double_t>(time_990.count()) / 1000000000);
double_t kbyte_999 = size_kb / (static_cast<double_t>(time_999.count()) / 1000000000);
std::cout << setw(11) << setprecision(2) << setiosflags(ios::right) << std::fixed << kbyte_avg
<< setw(0) << resetiosflags(ios::right) << " |" << std::flush;
std::cout << setw(11) << setprecision(2) << setiosflags(ios::right) << std::fixed << kbyte_950
<< setw(0) << resetiosflags(ios::right) << " |" << std::flush;
std::cout << setw(11) << setprecision(2) << setiosflags(ios::right) << std::fixed << kbyte_990
<< setw(0) << resetiosflags(ios::right) << " |" << std::flush;
std::cout << setw(11) << setprecision(2) << setiosflags(ios::right) << std::fixed << kbyte_999
<< setw(0) << resetiosflags(ios::right);
std::cout << std::defaultfloat << std::endl;
}
// Split results
std::cout << std::endl << std::endl;
}
std::cout << "Name | Avg. Ás | 95.0% Ás | 99.0% Ás | 99.9% Ás \n"
<< "----------------+------------+------------+------------+------------\n";
std::cout << setw(16) << setiosflags(ios::left) << "_mm_clflush" << setw(0) << resetiosflags(ios::left) << "|"
<< setw(11) << setprecision(3) << setiosflags(ios::right) << std::fixed
<< flush.average_duration() / 1000 << setw(0) << resetiosflags(ios::right) << " |" << setw(11)
<< setprecision(3) << setiosflags(ios::right) << std::fixed << flush.percentile(0.95).count() / 1000.0
<< setw(0) << resetiosflags(ios::right) << " |" << setw(11) << setprecision(3)
<< setiosflags(ios::right) << std::fixed << flush.percentile(0.99).count() / 1000.0 << setw(0)
<< resetiosflags(ios::right) << " |" << setw(11) << setprecision(3) << setiosflags(ios::right)
<< std::fixed << flush.percentile(0.999).count() / 1000.0 << setw(0) << resetiosflags(ios::right)
<< '\n';
std::cout << setw(16) << setiosflags(ios::left) << "_mm_mfence1" << setw(0) << resetiosflags(ios::left) << "|"
<< setw(11) << setprecision(3) << setiosflags(ios::right) << std::fixed
<< fence.average_duration() / 1000 << setw(0) << resetiosflags(ios::right) << " |" << setw(11)
<< setprecision(3) << setiosflags(ios::right) << std::fixed << fence.percentile(0.95).count() / 1000.0
<< setw(0) << resetiosflags(ios::right) << " |" << setw(11) << setprecision(3)
<< setiosflags(ios::right) << std::fixed << fence.percentile(0.99).count() / 1000.0 << setw(0)
<< resetiosflags(ios::right) << " |" << setw(11) << setprecision(3) << setiosflags(ios::right)
<< std::fixed << fence.percentile(0.999).count() / 1000.0 << setw(0) << resetiosflags(ios::right)
<< '\n';
std::cout << setw(16) << setiosflags(ios::left) << "_mm_mfence2" << setw(0) << resetiosflags(ios::left) << "|"
<< setw(11) << setprecision(3) << setiosflags(ios::right) << std::fixed
<< fenc2.average_duration() / 1000 << setw(0) << resetiosflags(ios::right) << " |" << setw(11)
<< setprecision(3) << setiosflags(ios::right) << std::fixed << fenc2.percentile(0.95).count() / 1000.0
<< setw(0) << resetiosflags(ios::right) << " |" << setw(11) << setprecision(3)
<< setiosflags(ios::right) << std::fixed << fenc2.percentile(0.99).count() / 1000.0 << setw(0)
<< resetiosflags(ios::right) << " |" << setw(11) << setprecision(3) << setiosflags(ios::right)
<< std::fixed << fenc2.percentile(0.999).count() / 1000.0 << setw(0) << resetiosflags(ios::right)
<< '\n';
std::cout << std::flush << std::endl;
std::cin.get();
return 0;
}
<file_sep>#include "os.hpp"
#include <iostream>
#define THREAD_START_TIME 10
#define THREAD_STOP_TIME 100
os::Semaphore::Semaphore(size_t count) {
m_Count = count;
}
os::Semaphore::~Semaphore() {
}
void os::Semaphore::notify(size_t count) {
std::unique_lock<std::mutex> lock(m_Mutex);
m_Count += count;
if (count == 1)
m_CondVar.notify_one();
else {
m_CondVar.notify_all();
}
}
void os::Semaphore::wait(size_t count) {
std::unique_lock<std::mutex> lock(m_Mutex);
do {
if (m_Count > 0) { // Another thread may have been faster.
m_Count--;
count--;
if (count == 0)
return; // Jumps straight back to the old code
}
m_CondVar.wait(lock, [this] {
return (m_Count > 0);
});
} while (true); // This should produce a cond-less jmp or reloc operation
}
bool os::Semaphore::try_wait(size_t count) {
std::unique_lock<std::mutex> lock(m_Mutex);
if (m_Count >= count) {
m_Count -= count;
return true;
}
return false;
}
bool os::ThreadTask::work() {
return true;
}
os::ThreadPool::ThreadPool(size_t threads) {
m_Threads.resize(threads);
for (size_t n = 0; n < threads; n++) {
ThreadPoolWorker* worker = new ThreadPoolWorker();
worker->isRunning = false;
worker->doStop = false;
worker->currentTask = nullptr;
worker->thread = std::thread(ThreadMain, worker, this);
// Timed Wait
for (size_t w = 0; w <= THREAD_START_TIME; w++) {
if (worker->isRunning)
break;
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
/// We failed to start the thread, do error stuff.
if (!worker->isRunning)
throw std::runtime_error("Failed to start ThreadPool worker thread.");
m_Threads[n] = worker;
}
}
os::ThreadPool::~ThreadPool() {
for (ThreadPoolWorker* worker : m_Threads) {
worker->doStop = true;
PostTask(nullptr);
}
for (ThreadPoolWorker* worker : m_Threads) {
if (worker->isRunning) {
// Timed Wait for thread stop.
for (size_t w = 0; w <= THREAD_STOP_TIME; w++) {
if (!worker->isRunning)
break;
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
}
delete worker;
}
}
void os::ThreadPool::PostTask(ThreadTask *task) {
std::unique_lock<std::mutex> lock(m_Tasks.mutex);
m_Tasks.queue.push(task);
m_Tasks.semaphore.notify();
}
void os::ThreadPool::PostTasks(ThreadTask *task[], size_t count) {
std::unique_lock<std::mutex> lock(m_Tasks.mutex);
for (size_t n = 0; n < count; n++)
m_Tasks.queue.push(task[n]);
m_Tasks.semaphore.notify(count);
}
os::ThreadTask* os::ThreadPool::WaitTask() {
m_Tasks.semaphore.wait();
std::unique_lock<std::mutex> lock(m_Tasks.mutex);
os::ThreadTask* task = m_Tasks.queue.front();
m_Tasks.queue.pop();
return task;
}
int os::ThreadPool::ThreadMain(ThreadPoolWorker* worker, ThreadPool* pool) {
worker->isRunning = true;
while (!worker->doStop) {
if (worker->currentTask != nullptr) {
worker->currentTask->failed = !worker->currentTask->work();
worker->currentTask->completed = true;
worker->currentTask = nullptr;
}
worker->currentTask = pool->WaitTask();
}
worker->isRunning = false;
return 0;
}
os::ThreadPoolWorker::ThreadPoolWorker() {
isRunning = false;
doStop = false;
currentTask = nullptr;
}
<file_sep>cmake_minimum_required(VERSION 2.8)
project(FindPowerOfTwo)
set(SOURCES
main.cpp)
set(HEADERS)
add_executable(FindPowerOfTwo
${SOURCES}
${HEADERS})
SET(PLATFORM_LIBS)
if(WIN32)
SET(PLATFORM_LIBS winmm)
endif()
target_link_libraries(FindPowerOfTwo
${PLATFORM_LIBS}) | 1ccb450a146dfee179d652aeef8b5e408daa419a | [
"Markdown",
"C",
"CMake",
"C++"
] | 26 | CMake | Xaymar/Sandbox-Cpp | 0e8f4c7190aaf284d4c90da1061577d32b3ab667 | bdd50b390b75d0ae7257974fdc31e08feb0c8d84 |
refs/heads/master | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>DataVerwerkingsSysteem_Dev_B</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>javadoc</groupId>
<artifactId>javadoc</artifactId>
<version>1.3</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.hudsonci.plugins</groupId>
<artifactId>findbugs</artifactId>
<version>4.48-h-1</version>
</dependency>
<dependency>
<groupId>org.hudsonci.plugins</groupId>
<artifactId>token-macro</artifactId>
<version>1.8.1-h-1</version>
</dependency>
</dependencies>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.5.2</version>
<configuration>
<!--
Enables analysis which takes more memory but finds more bugs.
If you run out of memory, changes the value of the effort element
to 'low'.
-->
<effort>Max</effort>
<!-- Reports all bugs (other values are medium and max) -->
<threshold>Low</threshold>
<!-- Produces XML report -->
<xmlOutput>true</xmlOutput>
</configuration>
</plugin>
</plugins>
</reporting>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project><file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Readers;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
/**
*
* @author Jehizkia
*/
public class ConnectionsCSVReaderThreadTest {
public ConnectionsCSVReaderThreadTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of run method, of class ConnectionsCSVReaderThread.
*/
@Ignore
public void testRun() {
System.out.println("run");
ConnectionsCSVReaderThread instance = null;
instance.run();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getUserPath method, of class ConnectionsCSVReaderThread.
*/
@Ignore
public void testGetUserPath() {
System.out.println("getUserPath");
ConnectionsCSVReaderThread instance = null;
String expResult = "";
String result = instance.getUserPath();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setUserPath method, of class ConnectionsCSVReaderThread.
*/
@Test
public void testSetUserPath() {
System.out.println("setUserPath");
// String userPath = "C:\\Users\\Jehizkia\\Documents\\informatica";
String userPath = "";
String expResult = "C:\\Users\\Jehizkia\\Documents\\informatica";
ConnectionsCSVReaderThread instance = new ConnectionsCSVReaderThread(userPath);
instance.setUserPath("C:\\Users\\Jehizkia\\Documents\\informatica");
String result = instance.getUserPath();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
}
/**
* Test of readAndInsertConnectionsCSV method, of class ConnectionsCSVReaderThread.
*/
@Ignore
public void testReadAndInsertConnectionsCSV() {
System.out.println("readAndInsertConnectionsCSV");
ConnectionsCSVReaderThread instance = null;
instance.readAndInsertConnectionsCSV();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Server_Manager;
import DatabaseClasses.Car;
import DatabaseClasses.Database_Manager;
import DatabaseClasses.EntityClass;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.StreamCorruptedException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Elize
*/
public class HTTPReciever extends Thread {
public HTTPReciever() {
this.start();
}
@Override
public void run() {
while(true){
recieveAndInsertObject();
}
}
//Method to recieve all messages from outside clients.
private void recieveAndInsertObject(){
int port = 8000;
InputStream is = null;
Socket s = null;
ServerSocket ss = null;
try {
InetAddress address = InetAddress.getByName("localhost");
System.out.println("Reading...");
ss = new ServerSocket(port, 50, address);
System.out.println("Reciever:" + ss.getInetAddress().getHostAddress() + " " + ss.getLocalPort());
s = ss.accept();
is = s.getInputStream();
//Just read the plain text in the inputstream
String readString = "";
int readChar = 0;
while((readChar = is.read()) != -1){
readString += (char) readChar;
}
System.out.println("String:" + readString);
//Read the objects in the inputstream, I don't think we are going to use this.
//Maybe for inserting live data?
// ObjectInputStream objectInput = new ObjectInputStream(is);
// String message1 = (String) objectInput.readObject();
// Car message2 = (Car) objectInput.readObject();
// System.out.println(message1 + "/n" + message2.toString());
}catch(Exception e){System.out.println(e);}
finally{
try {
is.close();
s.close();
ss.close();
} catch (IOException ex) {
Logger.getLogger(HTTPReciever.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Just a test method, we are going to use php/angularJS for this
public static void sentSignal(){
try{
Socket socket = new Socket("localhost", 8000);
System.out.println("Client:" + socket.getInetAddress().getHostAddress() + " " + socket.getPort());
OutputStream dataOutputStream = socket.getOutputStream();
dataOutputStream.write("Hello".getBytes());
// ObjectOutputStream objectOutput = new ObjectOutputStream(dataOutputStream);
//objectOutput.writeObject(new String("Insert"));
//objectOutput.writeObject(new Car("124536"));
dataOutputStream.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
<file_sep># dev-6b
| b86fef28126316c7d1ccde19c7659cc99d057136 | [
"Markdown",
"Java",
"Maven POM"
] | 4 | Maven POM | Jehizkia/dev-6_opdracht_B | 27dd5a2dc36118bca237170bdccea35c39819563 | d1659fe8959fb7fa0c803cd23396a30916261ad2 |
refs/heads/master | <repo_name>0123yash/TestProject<file_sep>/src/main/java/main/BackupMyTimesFuncs.java
package main;
public class BackupMyTimesFuncs {
/***
*
@RequestMapping(value = "/edit/comment/", method = RequestMethod.GET)
public @ResponseBody DBObject editComment(HttpServletRequest request,@RequestParam( value = "commentId", required = true) Long commentId,
@RequestParam(value = "ssoid", required = true) String ssoid,
@RequestParam(value = "cText", required = true) String cText) throws Exception {
User user = new User();
DBObject returnObj = new BasicDBObject();
DBObject activityObj = new BasicDBObject();
long actorID = 0;
try{
String uid = ControllerUtils.getValidUUIDFromSSO(request);
user.setID(ControllerUtils.getLoggedinUsersCookie(request));
if(cText == null){
return null;
}
if(commentId != null){
activityObj = activityMongoDataRepo.getActivityByID(commentId);
actorID = (Long) activityObj.get(BaseActivity.ACTOR_ID);
}
if(uid == null || (ssoid != null && !uid.equals(ssoid))){
returnObj.put("msg", "Permission denied!");
return returnObj;
}
if(actorID != user.getID()){
returnObj.put("msg", "Permission denied!");
return returnObj;
}
if(cText != null && cText.trim().length() > 0){
activityMongoDataRepo.editComment(cText.trim(), commentId, null,null);
returnObj.put("msg", "Success");
}
return returnObj;
}
catch(Exception e){
logger.error("getting exception in /edit/comment/",e);
}
return null;
}
@RequestMapping(value = "/delete/comment/", method = RequestMethod.GET)
public @ResponseBody DBObject markDeleteComment(HttpServletRequest request,@RequestParam( value = "commentId", required = true) Long commentId,
@RequestParam(value = "ssoid", required = true) String ssoid) throws Exception {
User user = new User();
DBObject returnObj = new BasicDBObject();
DBObject activityObj = new BasicDBObject();
long actorID = 0;
int childs = 0;
String msid = null;
String activityType = null;
long parentID = 0;
String appKey = null;
try{
user.setID(ControllerUtils.getLoggedinUsersCookie(request));
return inactiveComment(request, commentId, ssoid, user, returnObj,
actorID, childs, msid, activityType, parentID, appKey);
}
catch(Exception e){
logger.error("getting exception in /delete/comment/",e);
}
return null;
}
*
**/
}
<file_sep>/src/main/java/main/DupComments.java
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.til.moderation.features.Abusive;
import com.til.moderation.features.AbusiveListsCreation;
public class DupComments {
static List<String> outputStrList = new ArrayList<String>();
static List<String> redStrList = new ArrayList<String>();
public static void main(String[] args) throws JSONException, IOException {
String BASE_URL = "http://myt.indiatimes.com/mytimes/getFeed/Activity?curpg=1&appkey=TOI&sortcriteria=CreationDate&order=asc&size=1000&pagenum=1&withReward=true&msid=";
String URL ;
List<String> msidList = Abusive.readFromTextFile("/Users/yash.dalmia/listMsids");
for(String msid:msidList){
URL = BASE_URL + msid;
getDupComments(URL);
}
System.out.println("Length : " + outputStrList.size());
AbusiveListsCreation.writeToFile(outputStrList, "/Users/yash.dalmia/listDupComments");
AbusiveListsCreation.writeToFile(redStrList, "/Users/yash.dalmia/listRedComments");
}
public static void getDupComments(String URL) throws JSONException, IOException{
JSONArray cmtObjs;
cmtObjs = readJsonArrayFromUrl(URL);
JSONObject obj;
int isSpamDup, isSpamRed;
String stringCmt, stringId;
for(int i=1; i<cmtObjs.length(); i++){
obj = cmtObjs.getJSONObject(i);
// System.out.println(obj);
if(!obj.has("D_U_P") || !obj.getJSONObject("D_U_P").getJSONObject("DUPLICATE").has("isSpam")){
continue;
}
JSONObject jsonObj = (obj.getJSONObject("D_U_P")).getJSONObject("DUPLICATE");
isSpamDup = (Integer)jsonObj.get("isSpam");
System.out.println(isSpamDup);
jsonObj = (obj.getJSONObject("D_U_P")).getJSONObject("redundant").getJSONObject("REDUNDANCY");
isSpamRed = (Integer)jsonObj.get("isSpam");
System.out.println(isSpamDup);
if(isSpamDup == 1){
stringId = obj.get("_id").toString();
stringCmt = obj.get("C_T").toString();
String outputStr = (stringId + " : " + obj.get("msid").toString() + " : " + stringCmt);
System.out.println(outputStr);
outputStrList.add(outputStr);
}
if(isSpamRed == 1){
String outputStr = (obj.get("_id").toString() + " : " + obj.get("msid").toString() + " : " + obj.get("C_T").toString());
System.out.println(outputStr);
redStrList.add(outputStr);
}
}
}
public static JSONArray readJsonArrayFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONArray arr = new JSONArray(jsonText);
return arr;
} finally {
is.close();
}
}
// the two below functions are for the function postCallMovie
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
//System.out.println("response...."+sb.toString());
return sb.toString();
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>TestProject</groupId>
<artifactId>TestProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>TestProject</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>libs-release-local</id>
<url>http://maven.indiatimes.com/repository/libs-release-local/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.til.moderation</groupId>
<artifactId>moderation-layer</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.datumbox</groupId>
<artifactId>datumbox-framework-lib</artifactId>
<version>0.8.0</version>
</dependency>
<dependency>
<groupId>com.optimaize.languagedetector</groupId>
<artifactId>language-detector</artifactId>
<version>0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
<dependency>
<groupId>info.debatty</groupId>
<artifactId>java-string-similarity</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
</dependencies>
</project><file_sep>/src/main/java/main/CleanSpeakScrapeRead.java
package main;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class CleanSpeakScrapeRead {
String[] tagList = {"Account",
"Alcohol-Drug",
"AsciiArt",
"Bigotry-Racism",
"Bullying",
"Grooming",
"Harm-Abuse",
"PII",
"Sexual",
"Spam",
"Threats",
"Vulgarity",
"Weapons"};
String[] extrasList = {"Adjective",
"Adverb",
"Noun",
"Verb",
"Collapse Doubles (bb, dd, etc. - no vowels)",
"Replace Phonetics (ph=f, ck=kc, etc.)"};
public static void main(String[] args) throws IOException {
String fileLocation = "/Users/yash.dalmia/TIL/Profanity_Filter/CleanSpeak_Dump/cleanSpeakDump.txt";
JSONArray jsonArr = readJsonFromFile(fileLocation);
List<String> textArr = new ArrayList<String>();
JSONObject jsonObj;
for(int i=0; i<jsonArr.length();i++){
jsonObj = jsonArr.getJSONObject(i);
String text = (String) jsonObj.get("Text");
textArr.add(text);
}
writeToFile(textArr, "/Users/yash.dalmia/TIL/Profanity_Filter/CleanSpeak_Dump/AbusiveWordList.txt");
}
static void writeJsonToFile(JSONArray jsonArr, String fileLocation) throws IOException{
FileWriter file = new FileWriter(fileLocation);
try{
file.write(jsonArr.toString());
}catch (Exception e){
e.printStackTrace();
}finally{
file.flush();
file.close();
}
}
static JSONArray readJsonFromFile(String fileLocation) throws IOException{
byte[] encoded = Files.readAllBytes(Paths.get(fileLocation));
return new JSONArray(new String(encoded, StandardCharsets.UTF_8));
}
static Document getDoc(String URL, String sessionId) throws IOException{
Document document = Jsoup
.connect(URL)
.cookie("JSESSIONID", sessionId)
.get();
return document;
}
public static void writeToFile(List<String> list, String fileLocation) throws IOException{
FileWriter writer = new FileWriter(fileLocation);
for(String str: list) {
writer.write(str+"\n");
}
writer.close();
}
static JSONObject detailJson(Document document){
String title = document.title();
System.out.println("Title : " + title);
String text = document.select("#entry_text").val();
String severity = document.select("#entry_severity option[selected='selected']").val();
String variations = document.select("#variations option").html();
String ignores = document.select("#ignore-list option").html();
String definition = document.select("entry_definition").html();
String tags = document.select("#tag-list div input[checked='checked']+label").html();
// System.out.println(tags.split("\n")[1]);
//picking the 2nd div with the given properties as the first one is 'tags'
String extras = document.select(".checkbox-list.no-scroll").get(2).select("div input[checked='checked']+label").html();
String filterMode = document.select("#entry_filterMode option[selected='selected']").val();
JSONObject jsonObj = new JSONObject();
jsonObj.put("Text", text);
jsonObj.put("Severity", severity);
jsonObj.put("Variations", variations);
jsonObj.put("Ignores", ignores);
jsonObj.put("Filter Mode", filterMode);
jsonObj.put("Definition", definition);
jsonObj.put("Tags", tags);
jsonObj.put("Extras", extras);
System.out.println(jsonObj);
System.out.println("\n\n");
return jsonObj;
}
}<file_sep>/src/main/java/main/RejectAllComments.java
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import com.til.moderation.features.Abusive;
public class RejectAllComments {
public static void main(String[] args) throws Exception {
List<String> listIDs = Abusive.readFromTextFile("/Users/yash.dalmia/listIds");
rejectAllCmts(listIDs);
}
//
static void rejectAllCmts(List<String> listIds) throws Exception{
String BASE_URL = "http://myt.indiatimes.com/mytimes/comment/rejected?editorId=yash&commentActivityId=";
String URL;
for(String id:listIds){
System.out.println(id);
getHTML(BASE_URL + id);
}
}
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
}
<file_sep>/src/main/java/main/RejectAllComments2.java
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class RejectAllComments2 {
public static void main(String[] args) throws Exception {
// List<String> listIDs = HelpingImpFunc.readFromTextFile("/Users/yash.dalmia/listIds");
// rejectAllCmts(listIDs);
// List<String> listUserIDs = HelpingImpFunc.readFromTextFile("/Users/yash.dalmia/usersToFlag");
//
// for (String userId : listUserIDs){
// rejectWrapper(userId);
// }
String A_IDs = "445000279,411440766,457756023,459445502";
for (String A_ID : A_IDs.split(",")) {
System.out.println("Actor Id : " + A_ID);
rejectWrapper(A_ID);
}
}
static void rejectWrapper(String A_ID) throws Exception{
int totalRejectedCount = 0;
String BASE_URL = "http://myt.indiatimes.com/mytimes/topUserCommentFeed/?toShowDeleted=false&top=1999&userId=" ;
String url = BASE_URL + A_ID;
JSONArray arr = HelpingImpFunc.readJsonArrayFromUrl(url);
List<String> idList = getListCommentFromJsonArr(arr);
System.out.println(idList);
totalRejectedCount = totalRejectedCount + idList.size();
System.out.println("count : " + idList.size());
rejectAllCmts(idList);
System.out.println("total rejected count : " + totalRejectedCount);
}
static void rejectAllCmts(List<String> listIds) throws Exception{
String BASE_URL = "http://myt.indiatimes.com/mytimes/comment/rejected?editorId=yash&commentActivityId=";
// String BASE_URL = "http://myt.indiatimes.com/mytimes/activityApprove?commentActivityId=";
for(String id:listIds){
getHTML(BASE_URL + id);
System.out.println("rejected : " + id);
}
System.out.println("total rejected : " + listIds.size());
}
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static List<String> getListCommentFromJsonArr(JSONArray arr){
List<String> oldCmtsList = new ArrayList<String>();
for(int i = 0 ; i< arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
// System.out.println(obj);
if(obj.has("_id")){
oldCmtsList.add(obj.get("_id").toString());
}
}
return oldCmtsList;
}
}
<file_sep>/src/main/java/main/EhCacheTest.java
package main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class EhCacheTest {
static String BASE_URL = "http://172.29.16.132:8080/ecacheServer/rest/";
public static void main(String[] args) throws Exception {
String cName = "3";
String key = "aa";
DBObject obj = new BasicDBObject();
obj.put("yes", 34233534L);
// DBObject obj = new BasicDBObject();
//// JSONObject obj = new JSONObject();
// obj.put("asfd", "sdfsdfdsfds");
//
// System.out.println(obj);
//
// List<DBObject> list = new ArrayList<DBObject>();
// list.add(obj);
//
// System.out.println(list);
//
writeToCache(cName, key, obj);
Object readObject = readObjectFromCache(cName, key);
Long aa = (Long)((DBObject)readObject).get("yes");
System.out.println("aa" + aa);
try{
System.out.println("dbObj : " + readObject);
System.out.println("aa : " + aa);
}catch(Exception e){
System.out.println("Exception in readFromCache, " + e);
}
}
/**
* returns null if unable to read due to any reason - key not exist or unable to make connection
* @param cName
* @param key
* @return
* @throws JSONException
* @throws IOException
*/
private static DBObject readDBObjectFromCache(String cName, String key){
DBObject dbObj = null;
Object obj = readObjectFromCache(cName, key);
try{
if(obj != null){
dbObj = (DBObject) obj;
}
}catch(Exception e){
System.out.println("not of format dbObject, " + e);
}
return dbObj;
}
/**
* returns null if unable to read due to any reason - key not exist or unable to make connection
* @param cName
* @param key
* @return
*/
private static Object readObjectFromCache(String cName, String key){
Object o = null;
try{
// String readStr = HelpingImpFunc.readStringFromUrl(createKey(cName, key));
// o = com.mongodb.util.JSON.parse(readStr);
o = getCallHTML(createKey(cName, key));
}catch(Exception e){
System.err.println("Exception in reading object from cache + " + e);
}
return o;
}
/**
* returns null if unable to read due to any reason - key not exist or unable to make connection
* @param cName
* @param key
* @return
*/
private static List<DBObject> readDBListFromCache(String cName, String key){
List<DBObject> dbObjList = null;
Object obj = readObjectFromCache(cName, key);;
try{
dbObjList = (List<DBObject>) obj;
}catch(Exception e){
System.out.println("not of format list<dbObject>, " + e);
}
return dbObjList;
}
static String createKey(String collectionName, String key){
return (BASE_URL + collectionName + "/" + key);
}
/**
* true if the cache could be successfully written, else false
* @param collectionName
* @param key
* @param bodyToWrite
* @return
*/
static boolean writeToCache(String collectionName, String key, Object objToWrite){
int response = 0;
try{
response = putCallHTML(createKey(collectionName, key), objToWrite);
}catch(Exception e){
System.err.println("Exception in put call cache , " + e);
return false;
}
if(response!=0 && (response==200 || response==201)){
return true;
}
return false;
}
/**
* put call with json header
* @param urlToRead
* @param body
* @return http code of the request
* @throws Exception
*/
public static int putCallHTML(String urlToRead, Object obj) throws Exception {
URL url = new URL(urlToRead);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
ObjectOutputStream osw = new ObjectOutputStream(connection.getOutputStream());
osw.writeObject(obj);
// osw.write(body);
// osw.flush();
osw.close();
return connection.getResponseCode();
}
public static Object getCallHTML(String urlToRead) throws Exception {
URL url2 = new URL(urlToRead);
HttpURLConnection con = (HttpURLConnection) url2.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url2);
System.out.println("Response Code : " + responseCode);
// BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
// String inputLine;
// StringBuffer response = new StringBuffer();
//
// while ((inputLine = in.readLine()) != null) {
// response.append(inputLine);
// }
ObjectInputStream in = new ObjectInputStream(con.getInputStream());
Object e = in.readObject();
in.close();
return e;
}
}
<file_sep>/src/main/java/main/parseAPI.java
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.til.moderation.features.Abusive;
import com.til.moderation.features.AbusiveListsCreation;
public class parseAPI {
static List<String> outputStrList = new ArrayList<String>();
static List<String> redStrList = new ArrayList<String>();
public static void main(String[] args) throws JSONException, IOException {
String BASE_URL = "http://myt.indiatimes.com/mytimes/getFeed/Activity?msid=60475108&curpg=1&appkey=TOI&sortcriteria=CreationDate&order=asc&size=100&pagenum=1&withReward=false";
String URL ;
// List<String> msidList = Abusive.readFromTextFile("/Users/yash.dalmia/listMsids");
// for(String msid:msidList){
// URL = BASE_URL + msid;
// getDupComments(URL);
// }
String userId = "175094723";
URL = BASE_URL + userId;
getDupComments(URL);
// System.out.println("Length : " + outputStrList.size());
// AbusiveListsCreation.writeToFile(outputStrList, "/Users/yash.dalmia/listDupComments");
// AbusiveListsCreation.writeToFile(redStrList, "/Users/yash.dalmia/listRedComments");
}
public static void getDupComments(String URL) throws JSONException, IOException{
JSONArray cmtObjs;
cmtObjs = readJsonArrayFromUrl(URL);
JSONObject obj;
String stringCmt, stringId;
Integer lastCdMinute = 0;
for(int i=1; i<cmtObjs.length(); i++){
obj = cmtObjs.getJSONObject(i);
// if(!obj.has("C_D_Minute")){
// continue;
// }
// Integer cdMinute = (Integer) obj.get("C_D_Minute");
// System.out.println((cdMinute - lastCdMinute));
//
// lastCdMinute = cdMinute;
Long cdMinute = (Long)obj.get("_id");
System.out.println((cdMinute - lastCdMinute));
}
}
public static JSONArray readJsonArrayFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONArray arr = new JSONArray(jsonText);
return arr;
} finally {
is.close();
}
}
// the two below functions are for the function postCallMovie
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
//System.out.println("response...."+sb.toString());
return sb.toString();
}
}
<file_sep>/src/main/java/main/CleanQueryOut.java
package main;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.til.moderation.features.AbusiveListsCreation;
public class CleanQueryOut {
public static void main(String[] args) throws IOException {
String fileLocation = "/Users/yash.dalmia/TIL/QUeryOut2.js";
List<String> msidList= AbusiveListsCreation.readFromTextFile(fileLocation,500000);
List<String> targetMsidList = new ArrayList<String>();
// int count = 0;
System.out.println("Size : " + msidList.size());
String[] splitArr;
for (String cmtText : msidList){
// if(count>=5000){
// break;
// }
splitArr = cmtText.split("_");
if(cmtText.matches("[0-9a-zA-Z_]*") || splitArr.length==2 ){
targetMsidList.add(cmtText);
// count++;
}
}
fileLocation = "/Users/yash.dalmia/TIL/QUeryOutCleaned";
AbusiveListsCreation.writeToFile(targetMsidList, fileLocation);
}
}<file_sep>/src/main/java/main/NonLoggedInWithoutEmail.java
package main;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class NonLoggedInWithoutEmail {
public static void main(String[] args) throws JSONException, IOException{
long top = 2000;
boolean toLimitUpper = false;
int countNon = 0;
// String URL = "http://192.168.42.194/mytimes/topCommentFeed/?toLimitUpper=" + toLimitUpper + "&top=" + top;
String URL = "http://192.168.42.194/mytimes/topUserCommentFeed/?userId=0&top=" + top;
JSONArray jsonArr = HelpingImpFunc.readJsonArrayFromUrl(URL);
System.out.println(jsonArr.length());
for (int i=0;i<jsonArr.length();i++){
JSONObject jsonObj = jsonArr.getJSONObject(i);
// if(!jsonObj.has("F_ADD") || jsonObj.getString("F_ADD")==null || jsonObj.getString("F_ADD").equals("")){
if(!jsonObj.has("F_ADD") || jsonObj.getString("F_ADD")==null){
System.out.println(jsonObj.get("_id") + " : " + jsonObj.get("A_ID"));
}
if(jsonObj.has("A_ID") && jsonObj.getInt("A_ID")==0){
countNon ++;
}
}
System.out.println("countNon : " + countNon);
}
}<file_sep>/src/main/java/main/BlockingListOfUsers.java
package main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONException;
import com.opencsv.CSVReader;
import com.til.moderation.main.SpamLayer;
import com.til.moderation.main.SpamRule;
import info.debatty.java.stringsimilarity.Cosine;
public class BlockingListOfUsers {
public static void main(String args[]) throws JSONException, IOException{
String FILE_LOCATION = "/Users/yash.dalmia/Downloads/Blocked__UserIDCSV.csv";
List<String> listOfEmails = readFromCsv(FILE_LOCATION);
String BASE_URL = "http://myt.indiatimes.com/mytimes/deactivateProfile?ssoid=";
String BASE_URL2 = "http://myt.indiatimes.com/mytimes/getUsersInfo?extraInfo=true&ssoids=";
String URL;
for (String email : listOfEmails){
try{
// URL = BASE_URL + email;
URL = BASE_URL2 + email;
getHTML(URL);
System.out.println(URL);
}catch(Exception e){
System.out.println("Error for : " + email);
}
}
}
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static List<String> readFromCsv(String fileLocation) throws FileNotFoundException, IOException{
int m = 0; //the required column of the csv file (starting with 0)
int skip = 1; //number of starting rows to skip
List<String> abusiveWords2 = new ArrayList<String>();
CSVReader reader = new CSVReader(new FileReader(fileLocation));
String [] nextLine;
for (int i=0;i<skip;i++){
reader.readNext();
}
while ((nextLine = reader.readNext()) != null) {
abusiveWords2.add(nextLine[m]);
}
reader.close();
return abusiveWords2;
}
}
<file_sep>/src/main/java/main/GetSSOIDsOfUsers.java
package main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.opencsv.CSVReader;
import com.til.moderation.main.SpamLayer;
import com.til.moderation.main.SpamRule;
import info.debatty.java.stringsimilarity.Cosine;
public class GetSSOIDsOfUsers {
public static void main(String args[]) throws JSONException, IOException{
String FILE_LOCATION = "/Users/yash.dalmia/";
List<String> listOfEmails = HelpingImpFunc.readFromTextFile(FILE_LOCATION);
// String BASE_URL = "http://myt.indiatimes.com/mytimes/deactivateProfile?ssoid=";
String BASE_URL2 = "http://myt.indiatimes.com/mytimes/getUsersInfo?extraInfo=true&ssoids=";
String URL;
for (String email : listOfEmails){
try{
// URL = BASE_URL + email;
URL = BASE_URL2 + email;
String ssoId = String.valueOf(HelpingImpFunc.readJsonArrayFromUrl(URL).getJSONObject(0).get("uid"));
System.out.println(ssoId);
}catch(Exception e){
System.out.println("Error for : " + email);
}
}
}
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static void getAIDfromSSOid() throws JSONException, IOException{
String fileLocation = "/Users/yash.dalmia/usersToFlag2";
List<String> list = HelpingImpFunc.readFromTextFile(fileLocation);
List<String> listA_ID = new ArrayList<String>();
for (String str : list){
String URL = "http://myt.indiatimes.com/mytimes/getUsersInfo?ssoids=" + str + "&extraInfo=true";
JSONArray jsonArr = HelpingImpFunc.readJsonArrayFromUrl(URL);
JSONObject jsonObj = jsonArr.getJSONObject(0);
if(jsonObj.has("_id")){
listA_ID.add(String.valueOf((jsonObj).get("_id")));
}
}
String fileLocation2 = "/Users/yash.dalmia/usersToFlag";
HelpingImpFunc.writeToFile(listA_ID, fileLocation2);
}
}
<file_sep>/src/main/java/main/TestTimesPointsAPI.java
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestTimesPointsAPI {
public static void main(String Args[])
{
try
{
String requestUriString="http://rewards.indiatimes.com/bp/api/alog/al";
// String s="pcode=TOI&scode=News&aname=mv_rv&uid=cxjg16z9z2yrk4sims9ea1zma&uemail=<EMAIL>&oid=59591695";
String s="pcode=TOI&scode=News&aname=mv_rv&uid=n6yg14csvyeudad1hqw7t4hz&uemail=<EMAIL>&oid=59458260";
URL obj = new URL(requestUriString);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setConnectTimeout(30000);
con.setReadTimeout(30000);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
con.setRequestProperty("charset","UTF-8");
con.setRequestProperty("Content-Length",Integer.toString(s.getBytes("UTF-8").length));
con.getOutputStream().write(s.getBytes("UTF-8"));
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(responseCode);
// Should update only when response code is 200
// if (responseCode==HttpStatus.OK.value() || responseCode==HttpStatus.ACCEPTED.value() || responseCode==HttpStatus.NO_CONTENT.value())
// {
// System.out.println(response.toString());
// }
}
catch(Exception e)
{
System.err.println(e);
}
}
}<file_sep>/src/main/java/main/FollowerStartup.java
package main;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.til.moderation.resources.LanguageDetect;
public class FollowerStartup {
public static void main(String args[]){
String baseURL = "http://myt.indiatimes.com/mytimes/topicFollower?appKey=MYTIMES&topicId=";
String baseURLGetInfo = "http://myt.indiatimes.com/mytimes/getUsersInfo?extraInfo=true&ssoids=";
String textFileLocation = "/Users/yash.dalmia/listKeywords";
List<String> listKeywords = HelpingImpFunc.readFromTextFile(textFileLocation);
for (String keyword:listKeywords){
try {
JSONArray jsonArr = HelpingImpFunc.readJsonArrayFromUrl(baseURL + keyword);
List<String> listEmail = new ArrayList<String>();
for(int i = 0 ; i< jsonArr.length(); i++){
JSONObject obj = jsonArr.getJSONObject(i);
String uid = String.valueOf(obj.get("uid"));
JSONArray jsonArr2 = HelpingImpFunc.readJsonArrayFromUrl(baseURLGetInfo + uid);
JSONObject jsonObj2 = jsonArr2.getJSONObject(0);
String EMAIL = String.valueOf(jsonObj2.get("EMAIL"));
listEmail.add(EMAIL);
}
System.out.println(keyword);
System.out.println(listEmail);
System.out.println(listEmail.size());
System.out.println("\n");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<file_sep>/src/main/java/main/pastCmtsDuplicate.java
package main;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.til.moderation.features.DuplicateComment;
public class pastCmtsDuplicate {
final static int cmtLimit = 20; //the number of latest comments of the user to be retrieved
final static int countLimit = 10; //the count beyond which the user will be flagged
public static void main(String[] args) throws JSONException, IOException {
String cmt = "We offering a part time home based job for everyone without any investment. Any one can do this job very easily. No qualification is required. Required only good internet knowledge and smart phone with internet. Spend hardly 2-3 hours per day and earn up to 15,000-30,000 per month or more and also earn along with your friends. No work pressure, your efforts and your income. For more information type INFO and what's app on the given number 9917221681";
String A_ID = "175094723";
// String A_ID = "1750947231";
if(flagUser(cmt, A_ID)==true){
System.out.println("flag user");
}else{
System.out.println("don't flag user");
}
}
public static List<String> getListCommentFromJsonArr(JSONArray arr){
List<String> oldCmtsList = new ArrayList<String>();
for(int i = 0 ; i< arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
System.out.println(obj);
if(obj.has("C_T")){
oldCmtsList.add((String)obj.get("C_T"));
}
}
return oldCmtsList;
}
//'true' for yes, 'false' for no
static boolean flagUser(String cmt, String A_ID) throws JSONException, IOException{
String BASE_URL = "http://192.168.27.159/mytimes/topUserCommentFeed/?appkey=TOI&top=" + cmtLimit + "&userId=" ;
// String A_ID = "175094723";
String url = BASE_URL + A_ID;
JSONArray arr = HelpingImpFunc.readJsonArrayFromUrl(url);
List<String> oldCmtsList = getListCommentFromJsonArr(arr);
return flagUser(cmt, oldCmtsList);
}
//'true' for yes, 'false' for no
static boolean flagUser(String cmt, List<String> oldCmtsList){
if(oldCmtsList.size() < countLimit){
return false;
}
int count = dupCount(cmt, oldCmtsList);
if(count >= countLimit){
return true;
}
return false;
}
//returns the number of cmts in the comment list which matches as duplicate with the cmt passed
static int dupCount(String cmt, List<String> oldCmtsList){
int count = 0; //count of duplicate comments
DuplicateComment.setStrictness(8); //9% duplicate check
for (String oldCmt:oldCmtsList){
if(DuplicateComment.isApproxDuplicate(cmt, oldCmt)==1){
count++;
}
}
System.out.println("count : " + count);
return count;
}
}
<file_sep>/src/main/java/main/ModerationOfflineTest.java
package main;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mongodb.DBObject;
import com.til.moderation.main.SpamLayer;
import com.til.moderation.main.SpamRule;
public class ModerationOfflineTest {
public static void main(String args[]) throws JSONException, IOException {
String baseFileLocation = "/Users/yash.dalmia/profanityBatchProcess data/EmailUrl/";
String readFileLocation = baseFileLocation + "09-01-2017-09-26-2017-10";
String writeFileLocation = baseFileLocation + "09-01-2017-09-26-2017-10_2";
HelpingImpFunc.writeToFile(getExtractedList(HelpingImpFunc.readFromTextFile(readFileLocation)), writeFileLocation);
}
static List<String> getExtractedList(List<String> list){
List<String> listExtracted = new ArrayList<String> ();
for (String str : list){
// String str = "ಚಿಕೊಳ್ಳಬಹುದು.<br/>Download Now: http s ://g oo.g l/d avg 3 C sdfsd";
// System.out.println(((DBObject)SpamLayer.profanityFilter(str, SpamRule.EMAIL).get("EMAIL")).get("list"));
try {
// SpamRule spamRule = SpamRule.URL;
SpamRule spamRule = SpamRule.URL;
List<String> list2 = (List<String>)(((DBObject)(SpamLayer.profanityFilter(str, spamRule).get(spamRule.toString()))).get("list"));
if(!list2.isEmpty()){
for (String list2elem : list2){
listExtracted.add(list2elem);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return listExtracted;
}
}<file_sep>/src/main/java/main/JsoupTry.java
package main;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsoupTry {
String[] tagList = {"Account",
"Alcohol-Drug",
"AsciiArt",
"Bigotry-Racism",
"Bullying",
"Grooming",
"Harm-Abuse",
"PII",
"Sexual",
"Spam",
"Threats",
"Vulgarity",
"Weapons"};
String[] extrasList = {"Adjective",
"Adverb",
"Noun",
"Verb",
"Collapse Doubles (bb, dd, etc. - no vowels)",
"Replace Phonetics (ph=f, ck=kc, etc.)"};
public static void main(String[] args) throws IOException {
String BASE_URL = "http://www.noswearing.com/dictionary/";
String URL;
JSONArray jsonArr = new JSONArray();
for(char alphabet = 'a'; alphabet <= 'z';alphabet++) {
URL = BASE_URL + String.valueOf(alphabet);
// jsonArr.put(detailJson(getDoc(URL)));
detailJson(getDoc(URL));
}
}
static void writeJsonToFile(JSONArray jsonArr, String fileLocation) throws IOException{
FileWriter file = new FileWriter(fileLocation);
try{
file.write(jsonArr.toString());
}catch (Exception e){
e.printStackTrace();
}finally{
file.flush();
file.close();
}
}
static JSONArray readJsonFromFile(String fileLocation) throws IOException{
byte[] encoded = Files.readAllBytes(Paths.get(fileLocation));
return new JSONArray(new String(encoded, StandardCharsets.UTF_8));
}
static Document getDoc(String URL) throws IOException{
Document document = Jsoup
.connect(URL)
.get();
return document;
}
static JSONObject detailJson(Document document){
String title = document.title();
System.out.println("1");
String text = document.select("div table tr td a").val();
System.out.println(text);
return null;
}
} | 3bb7939d2b60bcb3a8f929f796d787faa1aa1d45 | [
"Java",
"Maven POM"
] | 17 | Java | 0123yash/TestProject | 2762dd0a195c40fd546e49ef264222b05afaabbf | 228faa4e51f809b52d2501f74b3f117d4944fc5f |
refs/heads/master | <file_sep>#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "behacked.h"
int main(int argc, char **argv){
int i,n;
srandom(time(NULL));
initscr(); //initialize ncurses
cbreak(); //suspend line buffering
noecho(); //@echo off
keypad(stdscr,TRUE); //enable arrows
start_color(); //enable color
for(i=1;i<=6;i++) init_pair(i,i,COLOR_BLACK);
mvprintw(4,7,"Behacked");
refresh();
getch();
clear();
fill();
move(5,5);
refresh();
while(rmcombs());
cx = cy = 5;
sx = sy = -1;
while((c = getch()) != 3){
switch(c){
case KEY_LEFT:
case 'h':
if(cx > 0) cx--;
break;
case KEY_RIGHT:
case 'l':
if(cx < WIDTH-1) cx++;
break;
case KEY_UP:
case 'k':
if(cy > 0) cy--;
break;
case KEY_DOWN:
case 'j':
if(cy < HEIGHT-1) cy++;
break;
#ifdef DEBUG
case 'n':
redraw();
clpendsh();
n = 0;
ncomb(cx,cy,&n);
mvprintw(HEIGHT+4,2,"(%d,%d) %d*%d",cx,cy,n,grid[cy][cx]);
refresh();
break;
case 'N':
redraw();
mvprintw(2,WIDTH+5,"%d",ncombs());
refresh();
break;
case 'r':
redraw();
break;
#endif
case ' ':
if(sx == -1){
sx = cx;
sy = cy;
attron(COLOR_PAIR(grid[cy][cx]));
mvaddch(cy,cx,'*'|A_BOLD);
attroff(COLOR_PAIR(grid[cy][cx]));
}else{
redraw(); //gets rid of bold
if((sx-cx == 1 || sx-cx == -1) ^ (sy-cy == 1 || sy-cy == -1)){
int r = grid[sy][sx];
grid[sy][sx] = grid[cy][cx];
grid[cy][cx] = r;
redraw();
msleep(150);
if(rmcombs()){
while(rmcombs());
if(ncombs() == 0){
mvprintw(4,(WIDTH/2)-5,"GAME OVER");
getch();
endwin();
exit(0);
}
}else{
r = grid[sy][sx];
grid[sy][sx] = grid[cy][cx];
grid[cy][cx] = r;
redraw();
}
}
sy = sx = -1;
}
break;
#ifdef DEBUG
default:
mvprintw(HEIGHT+2,5,"%d",c);
#endif
}
move(cy,cx);
refresh();
}
endwin();
return 0;
}
/**Generates a random integer in the interval [0,n)*/
int randn(int n){
int r;
while((r = random()) >= (RAND_MAX/n*n));
return (r%n);
}
/**Sleeps for a given number of milliseconds*/
void msleep(int n){
nanosleep((struct timespec[]){{0,n*1000000}},NULL);
}
/**Fills the grid with random gems*/
void fill(){
int i,r;
for(i=0;i<WIDTH*HEIGHT;i++){
r = randn(6)+1;
grid[i/WIDTH][i%WIDTH] = r;
attron(COLOR_PAIR(r));
mvaddch(i/WIDTH,i%WIDTH,'*');//0x30+r);
attroff(COLOR_PAIR(r));
}
}
void redraw(){
int i;
clear();
for(i=0;i<WIDTH*HEIGHT;i++){
int r = grid[i/WIDTH][i%WIDTH];
if(r != 0){
attron(COLOR_PAIR(r));
mvaddch(i/WIDTH,i%WIDTH,'*');//0x30+r);
attroff(COLOR_PAIR(r));
}
}
mvprintw(4,WIDTH+5,"Score: %d",score);
refresh();
}
/**Clears the shadow grid*/
void clshadow(){
int i;
for(i=0;i<WIDTH*HEIGHT;i++){
shadow[i/WIDTH][i%WIDTH] = 0;
}
}
/**Clears the pending shadow grid*/
void clpendsh(){
int i;
for(i=0;i<WIDTH*HEIGHT;i++){
pendsh[i/WIDTH][i%WIDTH] = 0;
}
}
/**Copies the pending shadow grid to the actual shadow*/
void acceptpendsh(){
int i;
for(i=0;i<WIDTH*HEIGHT;i++){
shadow[i/WIDTH][i%WIDTH] |= pendsh[i/WIDTH][i%WIDTH];
}
}
/**Removes combinations (groups of four) in the grid and refills; returns 1 if any were found.*/
int rmcombs(){
int x,y,hascombs=0;
clshadow();
for(y=0;y<HEIGHT;y++){
for(x=0;x<WIDTH;x++){
int n = 0;
clpendsh();
ncomb(x,y,&n);
if(n >= 4 && grid[y][x] != 0){
score += 10;
hascombs = 1;
acceptpendsh();
}
}
}
breakcombs();
refill();
return hascombs;
}
/**Returns the number of potential combinations.*/
int ncombs(){
int x,y,n = 0;
//test vertical swaps first...
for(x=0;x<WIDTH;x++){
for(y=0;y<HEIGHT-1;y++){
//swap (x,y) and (x,y+1)
int r = grid[y][x],q;
grid[y][x] = grid[y+1][x];
grid[y+1][x] = r;
//count the combinations
clpendsh();
q = 0;
ncomb(x,y,&q);
n += (q >= 4);
clpendsh();
q = 0;
ncomb(x,y+1,&q);
n += (q >= 4);
//swap back
grid[y+1][x] = grid[y][x];
grid[y][x] = r;
}
}
//...and then horizontal
for(x=0;x<WIDTH-1;x++){
for(y=0;y<HEIGHT;y++){
//swap (x,y) and (x+1,y)
int r = grid[y][x],q;
grid[y][x] = grid[y][x+1];
grid[y][x+1] = r;
//count the combinations
clpendsh();
q = 0;
ncomb(x,y,&q);
n += (q >= 4);
clpendsh();
q = 0;
ncomb(x+1,y,&q);
n += (q >= 4);
//swap back
grid[y][x+1] = grid[y][x];
grid[y][x] = r;
}
}
clpendsh();
return n;
}
/**Returns the number of similar gems connected to the specified one (plus one.)*/
void ncomb(int i, int j, int *n){
int q = grid[j][i];
pendsh[j][i] = 1;
if(j-1 >= 0){
if(pendsh[j-1][i] == 0 && grid[j-1][i] == q) ncomb(i,j-1,n);
}if(j+1 < HEIGHT){
if(pendsh[j+1][i] == 0 && grid[j+1][i] == q) ncomb(i,j+1,n);
}if(i-1 >= 0){
if(pendsh[j][i-1] == 0 && grid[j][i-1] == q) ncomb(i-1,j,n);
}if(i+1 < WIDTH){
if(pendsh[j][i+1] == 0 && grid[j][i+1] == q) ncomb(i+1,j,n);
}
++*n;
}
void breakcombs(){
int k;
for(k=0;k<WIDTH*HEIGHT;k++){
if(shadow[k/WIDTH][k%WIDTH] == 1){
attron(COLOR_PAIR(grid[k/WIDTH][k%WIDTH]));
mvaddch(k/WIDTH,k%WIDTH,'o');
}
}
refresh();
msleep(150); //is a nice number
for(k=0;k<WIDTH*HEIGHT;k++){
if(shadow[k/WIDTH][k%WIDTH] == 1){
attron(COLOR_PAIR(grid[k/WIDTH][k%WIDTH]));
mvaddch(k/WIDTH,k%WIDTH,'O');
}
}
refresh();
msleep(150);
for(k=0;k<WIDTH*HEIGHT;k++){
if(shadow[k/WIDTH][k%WIDTH] == 1){
attron(COLOR_PAIR(grid[k/WIDTH][k%WIDTH]));
mvaddch(k/WIDTH,k%WIDTH,' ');
grid[k/WIDTH][k%WIDTH] = 0;
}
}
refresh();
msleep(150);
}
void refill(void){
int hasblank = 0;
int x,y;
do{
hasblank = 0;
for(x=0;x<WIDTH;x++){
for(y=HEIGHT-1;y>=1;y--){
if(grid[y-1][x] != 0 && grid[y][x] == 0){
grid[y][x] = grid[y-1][x];
grid[y-1][x] = 0;
hasblank = 1;
}
}
if(grid[0][x] == 0){
grid[0][x] = randn(6)+1;
hasblank = 1;
}
}
redraw();
msleep(150);
}while(hasblank == 1);
} | 6761f135b0e5ea7e778c006a0bf31bbab3857e9f | [
"C"
] | 1 | C | hubert-farnsworth/Behacked | fbfcc27438d7ff2781b703e271dbf2963d90b0d7 | bd6b35bf250f866c1748ed0e805c8554d6fcca81 |
refs/heads/master | <file_sep>package kr.ac.sungkyul.beautyline.service;
import static java.lang.Math.toIntExact;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kr.ac.sungkyul.beautyline.dao.BoardDao;
import kr.ac.sungkyul.beautyline.vo.BoardVo;
@Service
public class BoardService {
@Autowired
private BoardDao boardDao;
public void list(String kwd, Long pageNo){
List<BoardVo> pageList = boardDao.getAll(kwd);
List<BoardVo> list = boardDao.getList(pageNo, kwd);
int totalPage;
int sPage;
int ePage;
if(pageList.size()% 10 == 0){
totalPage = pageList.size() / 10 ;//
}else{
totalPage = (pageList.size() / 10)+ 1;
}
int pPage = totalPage / 5 ;
int countPage = (toIntExact(pageNo)-1)/5;
boolean prePage = true;
boolean nextPage = true;
//시작페이지 구하기
if(countPage == 0){
sPage = 1;
prePage=false;
}else {
sPage = (countPage*5)+1;
}
//마지막페이지 구하기
if(countPage==pPage){
ePage = totalPage;
nextPage=false;
}else{
ePage = sPage+4;
}
/* request.setAttribute("list", list);// 이름 지정과 객체
request.setAttribute("pageList", pageList);// 이름 지정과 객체
request.setAttribute("sPage", sPage);
request.setAttribute("ePage", ePage);
request.setAttribute("prePage", prePage);
request.setAttribute("nextPage", nextPage);
request.setAttribute("kwd", kwd);
return"/board/list";*/
}
}
<file_sep>package kr.ac.sungkyul.beautyline.vo;
/**
* @author WonHo
*
*/
public class VisitVo {
private long no; // 방문내역 번호
private long userNo; // 회원 번호
private long programNo; // 프로그램 번호
private long iamgeNo; // 이미지 번호
private String memo; // 메모
private String regDate; // 날짜
private long whiteningScore; // 미백 점수
private long whinkleScore; // 주름 점수
private long elasticScore; // 피부탄력 점수
private long moistureScore; // 수분 점수
private long acneScore; // 여드름 점수
private double averageScore; // 평균점수
private String payName; // 결제방법이름;
/* 사용자 측정후 이미지 */
private long fNo; // 1.fno -> 저장시
private String path; // 3.path
private String orgName; // 4.orgName
private String saveName; // 5.saveName
private long fileSize; // 6.filesize
// private String name; // 이름검색을 위해 넣어야할지 말아야할지 모르겠음.
/* getter & setter */
public long getNo() {
return no;
}
public void setNo(long no) {
this.no = no;
}
public long getUserNo() {
return userNo;
}
public void setUserNo(long userNo) {
this.userNo = userNo;
}
public long getProgramNo() {
return programNo;
}
public void setProgramNo(long programNo) {
this.programNo = programNo;
}
public long getIamgeNo() {
return iamgeNo;
}
public void setIamgeNo(long iamgeNo) {
this.iamgeNo = iamgeNo;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getRegDate() {
return regDate;
}
public void setRegDate(String regDate) {
this.regDate = regDate;
}
public long getWhiteningScore() {
return whiteningScore;
}
public void setWhiteningScore(long whiteningScore) {
this.whiteningScore = whiteningScore;
}
public long getWhinkleScore() {
return whinkleScore;
}
public void setWhinkleScore(long whinkleScore) {
this.whinkleScore = whinkleScore;
}
public long getElasticScore() {
return elasticScore;
}
public void setElasticScore(long elasticScore) {
this.elasticScore = elasticScore;
}
public long getMoistureScore() {
return moistureScore;
}
public void setMoistureScore(long moistureScore) {
this.moistureScore = moistureScore;
}
public long getAcneScore() {
return acneScore;
}
public void setAcneScore(long acneScore) {
this.acneScore = acneScore;
}
public double getAverageScore() {
return averageScore;
}
public void setAverageScore(double averageScore) {
this.averageScore = averageScore;
}
public String getPayName() {
return payName;
}
public void setPayName(String payName) {
this.payName = payName;
}
@Override
public String toString() {
return "VisitVo [no=" + no + ", userNo=" + userNo + ", programNo=" + programNo + ", iamgeNo=" + iamgeNo
+ ", memo=" + memo + ", regDate=" + regDate + ", whiteningScore=" + whiteningScore + ", whinkleScore="
+ whinkleScore + ", elasticScore=" + elasticScore + ", moistureScore=" + moistureScore + ", acneScore="
+ acneScore + ", averageScore=" + averageScore + ", payName=" + payName + "]";
}
}
<file_sep>package kr.ac.sungkyul.beautyline.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import kr.ac.sungkyul.beautyline.vo.BoardVo;
@Repository
public class BoardDao {
@Autowired
private SqlSession sqlSession;
public BoardVo get(Long no) {
BoardVo vo = sqlSession.selectOne("board.getNo",no);
return vo;
}
public List<BoardVo> getAll(String kwd) {
List<BoardVo> list = new ArrayList<BoardVo>();
BoardVo vo = null;
Connection connection = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
connection = DriverManager.getConnection(url, "webdb", "webdb");
stmt = connection.createStatement();
String sql ="select a.no, title, b.name, content, reg_date, view_count, b.no as user_no from board a, users b where a.user_no = b.no ";
if(kwd!=null){
sql += " and title like '%"+kwd+"%' and content like '%"+kwd+"%' ";
}
sql += " order by group_no DESC, order_no ASC ";
rs = stmt.executeQuery(sql);
while(rs.next()){
Long no = rs.getLong(1);
vo =new BoardVo();
vo.setNo(no);
list.add(vo);
}
} catch (SQLException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if(rs!=null){
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public void viewcount(BoardVo vo) {
sqlSession.update("board.viewcount", vo);
}
public List<BoardVo> getList(Long pageNo, String kwd) {
List<BoardVo> list = new ArrayList<BoardVo>();
PreparedStatement pstmt = null;
Connection connection = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
connection = DriverManager.getConnection(url, "webdb", "webdb");
//String sql ="select a.no, title, b.name, content, reg_date, view_count, b.no from board a, users b where a.user_no = b.no order by group_no DESC, order_no ASC";
String sql = "select * from (select c.*, rownum as rn from ( select a.no, title, b.name, content, reg_date, view_count, b.no as user_no from board a, users b where a.user_no = b.no ";
if(kwd!=null){
sql += " and title like '%"+ kwd+ "%' and content like '%"+ kwd +"%' ";
}
sql += " order by group_no DESC, order_no ASC ) c) where (?-1)*10 + 1 <= rn and rn <= ?*10";
pstmt = connection.prepareStatement(sql);
pstmt.setLong(1, pageNo);
pstmt.setLong(2, pageNo);
rs = pstmt.executeQuery();
while(rs.next()){
Long no = rs.getLong(1);
String title = rs.getString(2);
String name = rs.getString(3);
String content = rs.getString(4);
String regDate = rs.getString(5);
Long viewNo = rs.getLong(6);
Long userNo = rs.getLong(7);
BoardVo vo = new BoardVo();
vo.setNo(no);
vo.setTitle(title);
vo.setName(name);
vo.setContent(content);
vo.setRegDate(regDate);
vo.setViewNo(viewNo);
vo.setUserNo(userNo);
list.add(vo);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public void delete(BoardVo vo) {
sqlSession.delete("board.delete",vo);
}
public boolean write(BoardVo vo) {
Connection connection = null;
PreparedStatement pstmt = null;
PreparedStatement pstmt2 = null;
int count= 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
connection = DriverManager.getConnection(url, "webdb", "webdb");
if(vo.getGroupNo()!= null){//답글일때
//order_no
String orderSql = "update board set order_no=order_no+1 where group_no = ? and order_no > ?";
pstmt2 = connection.prepareStatement(orderSql);
pstmt2.setLong(1, vo.getGroupNo());
pstmt2.setLong(2, vo.getOrderNo());
pstmt2.executeUpdate();
}
String sql ="insert into board values(seq_board.nextval, ?, ?, sysdate, 0, " ;
if(vo.getGroupNo()!= null){//답글일때
sql += " ?, ?, ?, ?)";
}else{//답글아닐때
sql += " nvl((select max(group_no) from board), 0)+1, 1, 1, ?)";
}
pstmt = connection.prepareStatement(sql);
//no, title, content, reg_date, view_count, group_no, order_no, depth ,user_No
pstmt.setString(1, vo.getTitle());
pstmt.setString(2, vo.getContent());
if(vo.getGroupNo()!= null){
pstmt.setLong(3, vo.getGroupNo());
pstmt.setLong(4, vo.getOrderNo()+1);
pstmt.setLong(5, vo.getDepth()+1);
pstmt.setLong(6, vo.getUserNo());//userno
}
else{
pstmt.setLong(3, vo.getUserNo());//userno
}
count = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return (count==1);
}
public void modify(BoardVo vo) {
sqlSession.update("board.modify",vo);
}
}
| 3483401e186e8d6766bc67cdaf0da032ebee5b81 | [
"Java"
] | 3 | Java | JinhuiKim/beautyline | 5a711db4dd63c08075a1f0db285bee90c076e271 | 8247fec1b836ea1c22589e385fdda3679e858773 |
refs/heads/master | <file_sep>function regex() {
let str = "abcdefghijklmnopqrstuvwxyz";
let str2 = str.search(/s/);
console.log("Urut ke : " + str2)
}
regex(); | 95946c0073aaa1573fa762af00d6d9a2ba2c5eb3 | [
"JavaScript"
] | 1 | JavaScript | fdzrn/tugas_28_javascript | 2da88f18c2e09886a8395a7ab4917671da92edfa | c3bcd51e5720459860be69765d4292026d9a0b3d |
refs/heads/main | <repo_name>qqpwn/Obligatorisk3Sem<file_sep>/Obligatorisk-opgave1/FanOutput.cs
using System;
using System.Dynamic;
using System.Runtime.InteropServices.WindowsRuntime;
namespace Obligatorisk_opgave1
{
public class FanOutput
{
private int _id;
private string _name;
private int _temp;
private int _fugt;
public FanOutput(int id, string name, int temp, int fugt)
{
_id = id;
_name = name;
_temp = temp;
_fugt = fugt;
}
public FanOutput()
{
}
public int Id
{
get { return _id;}
set { _id = value;}
}
public string Name
{
get { return _name;}
set
{
if (value.Length < 2) throw new ArgumentOutOfRangeException("Navn ikke langt nok");
_name = value;
}
}
public int Temp
{
get { return _temp;}
set
{
if(15 < value && value > 25) throw new ArgumentOutOfRangeException("Temp er ikke inden for rammerne");
_temp = value;
}
}
public int Fugt
{
get { return _fugt;}
set
{
if(30 < value && value > 80) throw new ArgumentOutOfRangeException("Fugt er ikke iden for rammerne");
_fugt = value;
}
}
}
}
<file_sep>/RestService/Controllers/FanOutPutController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Obligatorisk_opgave1;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace RestService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class FanOutPutController : ControllerBase
{
private static readonly List<FanOutput> FanoutputItems = new List<FanOutput>()
{
new FanOutput(0,"Output1", 20, 65),
new FanOutput(1,"Output2", 15, 78),
new FanOutput(2,"Output3", 24, 34),
new FanOutput(3,"Output4", 19, 55),
new FanOutput(4,"Output5", 21, 49),
};
// GET: api/<FanOutPutController>
[HttpGet]
public IEnumerable<FanOutput> Get()
{
return FanoutputItems;
}
// GET api/<FanOutPutController>/5
[HttpGet("{id}")]
public FanOutput Get(int id)
{
return FanoutputItems.Find(i => i.Id == id);
}
// POST api/<FanOutPutController>
[HttpPost]
public void Post([FromBody] FanOutput value)
{
FanoutputItems.Add(value);
}
// PUT api/<FanOutPutController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] FanOutput value)
{
FanOutput fanPut = Get(id);
if (fanPut != null)
{
fanPut.Id = value.Id;
fanPut.Name = value.Name;
fanPut.Temp = value.Temp;
fanPut.Fugt = value.Fugt;
}
}
// DELETE api/<FanOutPutController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
FanOutput fanDelete = Get(id);
FanoutputItems.Remove(fanDelete);
}
}
}
<file_sep>/Opgave1-Unittest/FanOutputTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Obligatorisk_opgave1;
namespace Opgave1_Unittest
{
[TestClass]
public class FanOutputTest
{
private FanOutput _asd;
[TestInitialize]
public void Init()
{
_asd = new FanOutput(0, "T", 20, 40);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void NavnTest()
{
FanOutput navnTest = new FanOutput();
navnTest.Name = "T";
Assert.AreEqual("T", navnTest.Name);
}
[TestMethod]
public void NavnTest2()
{
FanOutput navnTest = new FanOutput();
navnTest.Name = "Taa";
Assert.AreEqual("Taa", navnTest.Name);
}
[TestMethod]
public void TempTest()
{
FanOutput tempTest = new FanOutput();
tempTest.Temp = 15;
Assert.AreEqual(15,tempTest.Temp);
}
[TestMethod]
public void TempTest2()
{
FanOutput tempTest = new FanOutput();
tempTest.Temp = 25;
Assert.AreEqual(25, tempTest.Temp);
}
[TestMethod]
public void TempTest3()
{
FanOutput tempTest = new FanOutput();
tempTest.Temp = 20;
Assert.AreEqual(20, tempTest.Temp);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TempTest4()
{
FanOutput tempTest = new FanOutput();
tempTest.Temp = 30;
Assert.AreEqual(30, tempTest.Temp);
}
[TestMethod]
public void FugtTest()
{
FanOutput fugtest = new FanOutput();
fugtest.Fugt = 30;
Assert.AreEqual(30, fugtest.Fugt);
}
[TestMethod]
public void FugtTest2()
{
FanOutput fugtest = new FanOutput();
fugtest.Fugt = 80;
Assert.AreEqual(80, fugtest.Fugt);
}
[TestMethod]
public void FugtTest3()
{
FanOutput fugtest = new FanOutput();
fugtest.Fugt = 60;
Assert.AreEqual(60, fugtest.Fugt);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void FugtTest4()
{
FanOutput fugtest = new FanOutput();
fugtest.Fugt = 100;
Assert.AreEqual(100, fugtest.Fugt);
}
}
}
| d9e58cd836fe2aca9fc2d25fd3ce2f6c3f1254cc | [
"C#"
] | 3 | C# | qqpwn/Obligatorisk3Sem | 7303306d3b313318837cb561d6a930bb3ef459d2 | 14d1cc4a37acd0a650012dcd0bb5faf887161a55 |
refs/heads/master | <file_sep># Survey MSI
App ini dibuat kurang dari 3 jam untuk mengumpulkan data untuk membuat tugas mata kuliah Manajemen Sistem Informasi (MSI). Karena dibuat "yang penting jadi", mungkin masih banyak bug disana sini.
Demo kuisioner: [Demo](https://jurnalmms.web.id/survey-msi)
Report / hasil survey: [Laporan](https://jurnalmms.web.id/survey-msi/index.php/report) (tidak perlu login)
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ajax extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('survey_model');
}
public function validate_npm()
{
if ( ! $this->input->is_ajax_request()) {
return $this->output->set_content_type('application/json')
->set_output(json_encode(array('errors' => TRUE, 'messages' => 'Halaman ini hanya dapat diakses dengan AJAX')));
}
$npm = $this->input->post('npm');
$is_exist = $this->survey_model->validate_npm($npm);
$profile = $this->survey_model->profile($npm);
$response = array(
'success' => TRUE,
'is_exist' => $is_exist,
'message' => ($is_exist) ? $profile->name : 'Mahasiswa tidak ada'
);
return $this->output->set_content_type('application/json')
->set_output(json_encode($response));
}
public function items() {
if ( ! $this->input->is_ajax_request()) {
return $this->output->set_content_type('application/json')
->set_output(json_encode(array('errors' => TRUE, 'messages' => 'Halaman ini hanya dapat diakses dengan AJAX')));
}
$base = $this->input->post('base');
if ( $this->survey_model->is_parent_exist($base)) {
$items = $this->survey_model->get_items($base);
$response = array(
'success' => TRUE,
'items' => $items
);
}
return $this->output->set_content_type('application/json')
->set_output(json_encode($response));
}
public function save_results() {
if ( ! $this->input->is_ajax_request()) {
return $this->output->set_content_type('application/json')
->set_output(json_encode(array('errors' => TRUE, 'messages' => 'Halaman ini hanya dapat diakses dengan AJAX')));
}
$this->load->library('user_agent');
$ua = $this->agent->agent_string();
$date = date('Y-m-d H:i:s');
$npm = $this->input->post('npm');
$items = $this->input->post('items');
if ( ! empty($npm) && (strlen($npm) == 9) && is_array($items) && count($items) > 0) {
$save = array();
$n = 0;
foreach ($items as $item) {
$save[$n]['student'] = strtoupper($npm);
$save[$n]['item_id'] = $item;
$save[$n]['input_time'] = $date;
$save[$n]['input_device'] = $ua;
$n++;
}
$this->survey_model->save_results($save);
$response = array(
'success' => TRUE,
'items' => $save
);
}
else {
$response = array(
'errors' => TRUE,
'message' => 'Harap pilih setidaknya satu'
);
}
return $this->output->set_content_type('application/json')
->set_output(json_encode($response));
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Survey_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_parents()
{
$parents = $this->db->order_by('name', 'ASC')->get('msi_survey_parents')->result();
return $parents;
}
public function profile($npm) {
return $this->db->select('id, name')
->where('npm', $npm)
->get('students')
->row();
}
public function validate_npm($npm)
{
$check = $this->db->where('npm', $npm)
->get('students')
->num_rows();
return ($check > 0) ? TRUE : FALSE;
}
public function is_parent_exist($base) {
$check = $this->db->where('id', $base)
->get('msi_survey_parents')
->num_rows();
return ($check > 0) ? TRUE : FALSE;
}
public function get_items($parent)
{
$get = $this->db->select('id, name')
->where('parent_id', $parent)
->order_by('name', 'ASC')
->get('msi_survey_items')
->result();
return $get;
}
public function save_results($item) {
return $this->db->insert_batch('msi_survey_results', $item);
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Report_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function reports()
{
return $this->db->query("SELECT res.id, st.name, it.name as language, p.name AS parent, res.input_time, res.input_device
FROM msi_survey_results AS res
JOIN students st ON st.npm = res.student
JOIN msi_survey_items it ON it.id = res.item_id
JOIN msi_survey_parents p ON p.id = it.parent_id
ORDER BY res.id ASC")->result();
}
public function total_base()
{
return $this->db->get('msi_survey_parents')->num_rows();
}
public function total_language()
{
return $this->db->get('msi_survey_items')->num_rows();
}
public function total_students()
{
return $this->db->get('students')->num_rows();
}
public function total_votes()
{
return $this->db->get('msi_survey_results')->num_rows();
}
public function base_stats()
{
return $this->db->query("SELECT p.name, COUNT(*) AS jumlah
FROM msi_survey_results AS res
JOIN students st ON st.npm = res.student
JOIN msi_survey_items it ON it.id = res.item_id
JOIN msi_survey_parents p ON p.id = it.parent_id
GROUP BY p.name")->result();
}
public function all_language()
{
return $this->db->query("SELECT p.name AS parent, it.name, COUNT(it.name) AS jumlah
FROM msi_survey_results AS res
JOIN students st ON st.npm = res.student
JOIN msi_survey_items it ON it.id = res.item_id
JOIN msi_survey_parents p ON p.id = it.parent_id
GROUP BY NAME")->result();
}
public function desktop()
{
return $this->db->query("SELECT it.name, COUNT(it.name) AS jumlah
FROM msi_survey_results AS res
JOIN students st ON st.npm = res.student
JOIN msi_survey_items it ON it.id = res.item_id
JOIN msi_survey_parents p ON p.id = it.parent_id
WHERE p.id = '3'
GROUP BY name")->result();
}
public function mobiles()
{
return $this->db->query("SELECT it.name, COUNT(it.name) AS jumlah
FROM msi_survey_results AS res
JOIN students st ON st.npm = res.student
JOIN msi_survey_items it ON it.id = res.item_id
JOIN msi_survey_parents p ON p.id = it.parent_id
WHERE p.id = '2'
GROUP BY name")->result();
}
public function web()
{
return $this->db->query("SELECT it.name, COUNT(it.name) AS jumlah
FROM msi_survey_results AS res
JOIN students st ON st.npm = res.student
JOIN msi_survey_items it ON it.id = res.item_id
JOIN msi_survey_parents p ON p.id = it.parent_id
WHERE p.id = '1'
GROUP BY name")->result();
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Kelola Mata Kuliah</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><?php echo anchor(base_url(), 'Home'); ?></li>
<li class="breadcrumb-item active">Mata Kuliah</li>
</ol>
</div>
</div>
</div>
</section>
<section class="content">
<div class="card card-primary">
<?php if ( count($courses) > 0) : ?>
<div class="table-responsive">
<table class="table table-hover">
<thead class="card-header">
<tr>
<th>Semester</th>
<th>Kode Mata Kuliah</th>
<th>Nama Mata Kuliah</th>
<th>SKS</th>
<th>W/P</th>
<th>Prasyarat</th>
<th></th>
</tr>
</thead>
<tbody class="card-body">
<?php foreach ($courses as $course) : ?>
<tr>
<td><?php echo $course->semester; ?></td>
<td><?php echo $course->code; ?></td>
<td><?php echo $course->name; ?></td>
<td><?php echo ($course->class_sks + $course->practice_sks); ?> (<?php echo $course->class_sks; ?> - <?php echo $course->practice_sks; ?>)</td>
<td><?php echo $course->level; ?></td>
<td>
<pre>
<?php print_r($course); ?>
</pre>
</td>
<td class="text-right">
<a href="<?php echo site_url('courses/edit/'. $course->id); ?>" class="btn btn-success btn-sm"><i class="fa fa-edit"></i></a>
<a href="#" data-toggle="modal" data-target="#deleteModal" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php else : ?>
<div class="alert alert-info">Belum ada data mata kuliah yang ditambahkan. Silahkan menambahkan baru.</div>
<?php endif; ?>
</div>
</section>
</div>
<div class="modal fade" id="deleteModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Hapus Data Surat</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p class="confirmDeleteText">Yakin ingin menghapus data Semester? Tindakan ini tidak dapat dibatalkan.</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<button type="button" class="btn btn-primary confirmDeleteMailBtn">Hapus</button>
</div>
</div>
</div>
</div><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Survey extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('survey_model');
}
public function index() {
$params['parents'] = $this->survey_model->get_parents();
$this->load->view('msi/survey', $params);
}
}<file_sep><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1">
<meta charset="utf-8">
<title>Bahasa Pemrograman Paling Diminati Mahasiswa Informatika Universitas Bengkulu 2019</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="colorlib.com">
<!-- MATERIAL DESIGN ICONIC FONT -->
<link rel="stylesheet" href="<?php echo base_url('assets/msi/fonts/material-design-iconic-font/css/material-design-iconic-font.css'); ?>">
<!-- STYLE CSS -->
<link rel="stylesheet" href="<?php echo base_url('assets/msi/css/style.css'); ?>">
</head>
<body>
<div class="wrapper" style="margin-top: 50px;">
<div class="form-header">
<a href="#">Survey #10</a>
<h3>Terima kasih sudah membantu mengisi kuisioner ini.... Semoga hari mu menyenangkan !!!</h3>
</div>
</div>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Kelola Semester</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><?php echo anchor(base_url(), 'Home'); ?></li>
<li class="breadcrumb-item active">Semester</li>
</ol>
</div>
</div>
</div>
</section>
<section class="content">
<div class="row">
<div class="col-md-8">
<div class="card card-primary">
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover" id="semester">
<thead>
<tr>
<th>#</th>
<th>Semester</th>
<th></th>
</tr>
</thead>
<tbody id="semester_list"></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card card-info">
<div class="card-header">
<h5 class="card-title">Tambah Data</h5>
</div>
<form action="#" method="POST" id="add_semester">
<div class="card-body">
<div class="form-group">
<label>Nama:</label>
<input type="text" name="name" value="" class="form-control">
<div class="error"></div>
</div>
</div>
<div class="card-footer">
<input type="submit" class="btn btn-info" value="Tambah">
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</section>
</div>
<div class="modal fade" id="deleteModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Hapus Data Surat</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p class="confirmDeleteText">Yakin ingin menghapus data Semester? Tindakan ini tidak dapat dibatalkan.</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<button type="button" class="btn btn-primary confirmDeleteMailBtn">Hapus</button>
</div>
</div>
</div>
</div><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Laporan Survey MSI #10</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><?php echo anchor(base_url(), 'Home'); ?></li>
<li class="breadcrumb-item active">Laporan</li>
</ol>
</div>
</div>
</div>
</section>
<section class="content">
<div class="card card-primary">
<?php if ( count($reports) > 0) : ?>
<div class="table-responsive">
<table class="table table-hover">
<thead class="card-header">
<tr>
<th>#</th>
<th>Nama</th>
<th>Bahasa</th>
<th>Waktu</th>
</tr>
</thead>
<tbody class="card-body">
<?php foreach ($reports as $report) : ?>
<tr>
<td><?php echo $report->id; ?></td>
<td><?php echo $report->name; ?></td>
<td><?php echo $report->parent; ?> / <?php echo $report->language; ?></td>
<td><?php echo date('l, d F Y H:i', strtotime($report->input_time)); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php else : ?>
<div class="alert alert-info">Belum ada data.</div>
<?php endif; ?>
</div>
</section>
</div><file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Waktu pembuatan: 10 Feb 2020 pada 10.51
-- Versi server: 10.4.11-MariaDB
-- Versi PHP: 7.4.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `geznine19`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `msi_survey_items`
--
CREATE TABLE `msi_survey_items` (
`id` int(10) NOT NULL,
`parent_id` int(10) NOT NULL,
`name` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `msi_survey_items`
--
INSERT INTO `msi_survey_items` (`id`, `parent_id`, `name`) VALUES
(1, 1, 'PHP'),
(2, 1, 'Microsoft ASPX'),
(3, 1, 'Adobe Cold Fusion'),
(4, 1, 'Ruby on Rails'),
(5, 1, 'Java'),
(6, 1, 'Django (Pyhton)'),
(7, 1, 'Node JS'),
(8, 2, 'Java'),
(9, 2, 'Kotlin'),
(10, 2, 'Swift'),
(11, 2, 'React JS'),
(12, 2, 'Microsoft Xamarin'),
(14, 3, 'Java'),
(15, 3, 'C++'),
(16, 3, 'Pyhton'),
(17, 3, 'Apple Swift'),
(18, 3, 'C#'),
(19, 3, 'Micosoft .NET');
-- --------------------------------------------------------
--
-- Struktur dari tabel `msi_survey_parents`
--
CREATE TABLE `msi_survey_parents` (
`id` int(10) NOT NULL,
`name` varchar(32) NOT NULL,
`description` mediumtext DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `msi_survey_parents`
--
INSERT INTO `msi_survey_parents` (`id`, `name`, `description`) VALUES
(1, 'Web', NULL),
(2, 'Mobile', 'Android, iOS'),
(3, 'Desktop', 'Windows, Mac OS, Linux');
-- --------------------------------------------------------
--
-- Struktur dari tabel `msi_survey_results`
--
CREATE TABLE `msi_survey_results` (
`id` int(10) NOT NULL,
`student` varchar(16) NOT NULL DEFAULT '',
`item_id` int(10) NOT NULL,
`input_time` datetime DEFAULT NULL,
`input_device` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `msi_survey_results`
--
INSERT INTO `msi_survey_results` (`id`, `student`, `item_id`, `input_time`, `input_device`) VALUES
(1, 'G1A019063', 5, '2020-02-04 10:44:31', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'),
(2, 'G1A019075', 8, '2020-02-04 10:47:08', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(3, 'G1A019075', 17, '2020-02-04 10:47:08', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(4, 'G1A019075', 15, '2020-02-04 10:47:08', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(5, 'G1A019075', 14, '2020-02-04 10:47:08', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(6, 'G1A019075', 16, '2020-02-04 10:47:08', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(7, 'G1A019015', 5, '2020-02-04 10:47:53', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1911 Build/PKQ1.190616.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(8, 'G1A019015', 8, '2020-02-04 10:47:53', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1911 Build/PKQ1.190616.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(9, 'G1A019015', 14, '2020-02-04 10:47:53', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1911 Build/PKQ1.190616.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(10, 'G1A019001', 1, '2020-02-04 10:48:44', 'Mozilla/5.0 (Linux; Android 9; ASUS_X01AD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Mobile Safari/537.36'),
(11, 'G1A019049', 5, '2020-02-04 10:49:16', 'Mozilla/5.0 (Linux; Android 9; vivo 1902) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(12, 'G1A019049', 15, '2020-02-04 10:49:16', 'Mozilla/5.0 (Linux; Android 9; vivo 1902) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(13, 'G1A019049', 14, '2020-02-04 10:49:16', 'Mozilla/5.0 (Linux; Android 9; vivo 1902) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(14, 'G1A019049', 8, '2020-02-04 10:49:16', 'Mozilla/5.0 (Linux; Android 9; vivo 1902) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(15, 'G1A019011', 8, '2020-02-04 10:49:37', 'Mozilla/5.0 (Linux; Android 8.1.0; vivo 1724 Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/6.0.0.2'),
(16, 'G1A019081', 5, '2020-02-04 10:49:50', 'Mozilla/5.0 (Linux; U; Android 7.1.1; in-id; CPH1729 Build/N6F26Q) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 OppoBrowser/15.6.2.5'),
(17, 'G1A019085', 8, '2020-02-04 10:50:28', 'Mozilla/5.0 (Linux; Android 7.1.1; ASUS_X00ID) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Mobile Safari/537.36'),
(18, 'G1A019065', 8, '2020-02-04 10:51:33', 'Mozilla/5.0 (Linux; Android 8.1.0; vivo 1724 Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/5.8.0.10'),
(19, 'G1A019021', 3, '2020-02-04 10:53:56', 'Mozilla/5.0 (Linux; Android 9; ASUS_X01AD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Mobile Safari/537.36'),
(20, 'G1A019025', 8, '2020-02-04 10:54:26', 'Mozilla/5.0 (Linux; Android 5.1.1; A37f) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.90 Mobile Safari/537.36'),
(21, 'G1A019033', 14, '2020-02-04 10:57:36', 'Mozilla/5.0 (Linux; Android 8.1.0; vivo 1727 Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/6.0.0.2'),
(22, 'G1A019033', 16, '2020-02-04 10:57:36', 'Mozilla/5.0 (Linux; Android 8.1.0; vivo 1727 Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/6.0.0.2'),
(23, 'G1A019007', 5, '2020-02-04 10:58:22', 'Mozilla/5.0 (Linux; Android 5.1; CPH1605) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(24, 'G1A019001', 17, '2020-02-04 10:59:16', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(25, 'G1A019001', 18, '2020-02-04 10:59:16', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(26, 'G1A019001', 8, '2020-02-04 10:59:16', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(27, 'G1A019001', 9, '2020-02-04 10:59:16', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(28, 'G1A019009', 8, '2020-02-04 11:01:19', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(29, 'G1A019009', 9, '2020-02-04 11:01:19', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(30, 'G1A019009', 12, '2020-02-04 11:01:19', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(31, 'G1A019009', 11, '2020-02-04 11:01:19', 'Mozilla/5.0 (Linux; Android 8.1.0; M5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(32, 'G1A019059', 8, '2020-02-04 11:03:06', 'Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-J720F) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/10.2 Chrome/71.0.3578.99 Mobile Safari/537.36'),
(33, 'G1A019043', 5, '2020-02-04 11:16:00', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(34, 'G1A019077', 14, '2020-02-04 11:25:46', 'Mozilla/5.0 (Linux; Android 6.0.1; vivo 1603) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Mobile Safari/537.36'),
(35, 'G1A019055', 14, '2020-02-04 11:57:44', 'Mozilla/5.0 (Linux; Android 5.1.1; A37f) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(36, 'G1A019093', 8, '2020-02-04 12:05:33', 'Mozilla/5.0 (Linux; Android 7.1.1; CPH1723) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(37, 'G1A019057', 5, '2020-02-04 12:22:26', 'Mozilla/5.0 (Linux; U; Android 9; en-US; SM-G885F Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/13.0.0.1288 Mobile Safari/537.36'),
(38, 'G1A019003', 15, '2020-02-04 13:37:30', 'Mozilla/5.0 (Linux; Android 9; RMX1805) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(39, 'G1A019047', 15, '2020-02-04 13:50:47', 'Mozilla/5.0 (Linux; Android 5.1.1; A37f) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(40, 'G1A019047', 16, '2020-02-04 13:50:47', 'Mozilla/5.0 (Linux; Android 5.1.1; A37f) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(41, 'G1A019009', 8, '2020-02-04 14:10:58', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'),
(42, 'G1A019039', 1, '2020-02-04 14:55:07', 'Mozilla/5.0 (Linux; Android 7.1.2; Redmi 4A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.116 Mobile Safari/537.36'),
(43, 'G1A019091', 19, '2020-02-04 19:41:28', 'Mozilla/5.0 (Linux; Android 10; Nokia 6.1 Plus) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(44, 'G1A019023', 14, '2020-02-04 19:43:19', 'Mozilla/5.0 (Linux; Android 8.1.0; vivo 1724 Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/5.8.0.10'),
(45, 'G1A019023', 8, '2020-02-04 19:43:19', 'Mozilla/5.0 (Linux; Android 8.1.0; vivo 1724 Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/5.8.0.10'),
(46, 'G1A019034', 8, '2020-02-04 19:43:23', 'Mozilla/5.0 (Linux; Android 6.0.1; Redmi 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.111 Mobile Safari/537.36'),
(47, 'G1A019034', 15, '2020-02-04 19:43:23', 'Mozilla/5.0 (Linux; Android 6.0.1; Redmi 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.111 Mobile Safari/537.36'),
(48, 'G1A019046', 5, '2020-02-04 19:43:27', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(49, 'G1A019022', 5, '2020-02-04 19:43:45', 'Mozilla/5.0 (Linux; U; Android 8.1.0; id-id; Redmi 6 Pro Build/OPM1.171019.019) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.4.3-g'),
(50, 'G1A019010', 14, '2020-02-04 19:44:28', 'Mozilla/5.0 (Linux; U; Android 9; en-us; Redmi Note 5 Build/PKQ1.180904.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.3.4-g'),
(51, 'G1A019010', 16, '2020-02-04 19:44:28', 'Mozilla/5.0 (Linux; U; Android 9; en-us; Redmi Note 5 Build/PKQ1.180904.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.3.4-g'),
(52, 'G1A019008', 8, '2020-02-04 19:46:47', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'),
(53, 'G1A019050', 8, '2020-02-04 19:46:55', 'Mozilla/5.0 (Linux; Android 7.1.2; Redmi 4X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(54, 'G1A019064', 8, '2020-02-04 19:46:58', 'Mozilla/5.0 (Linux; Android 8.1.0; ASUS_X00TD Build/OPM1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.126 Mobile Safari/537.36'),
(55, 'G1A019064', 15, '2020-02-04 19:46:58', 'Mozilla/5.0 (Linux; Android 8.1.0; ASUS_X00TD Build/OPM1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.126 Mobile Safari/537.36'),
(56, 'G1A019064', 14, '2020-02-04 19:46:58', 'Mozilla/5.0 (Linux; Android 8.1.0; ASUS_X00TD Build/OPM1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.126 Mobile Safari/537.36'),
(57, 'G1A019064', 16, '2020-02-04 19:46:58', 'Mozilla/5.0 (Linux; Android 8.1.0; ASUS_X00TD Build/OPM1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.126 Mobile Safari/537.36'),
(58, 'G1A019036', 8, '2020-02-04 19:47:00', 'Mozilla/5.0 (Linux; U; Android 9; en-us; CPH1969 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 OppoBrowser/25.6.3.1'),
(59, 'G1A019006', 8, '2020-02-04 19:48:06', 'Mozilla/5.0 (Linux; Android 8.1.0; vivo 1820 Build/O11019; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/6.0.0.2'),
(60, 'G1A019026', 5, '2020-02-04 19:48:40', 'Mozilla/5.0 (Linux; Android 9; Mi A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(61, 'G1A019052', 9, '2020-02-04 19:49:32', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'),
(62, 'G1A019028', 8, '2020-02-04 19:49:47', 'Mozilla/5.0 (Linux; U; Android 9; id-id; Redmi Note 8 Pro Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.4.3-g'),
(63, 'G1A019076', 8, '2020-02-04 19:50:22', 'Mozilla/5.0 (Linux; Android 6.0; Redmi Note 4X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.90 Mobile Safari/537.36'),
(64, 'G1A019086', 5, '2020-02-04 19:51:16', 'Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaN8-00/012.002; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.0 Mobile Safari/533.4 3gpp-gba'),
(65, 'G1A019086', 1, '2020-02-04 19:51:16', 'Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaN8-00/012.002; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.0 Mobile Safari/533.4 3gpp-gba'),
(66, 'G1A019086', 15, '2020-02-04 19:51:16', 'Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaN8-00/012.002; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.0 Mobile Safari/533.4 3gpp-gba'),
(67, 'G1A019086', 14, '2020-02-04 19:51:16', 'Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaN8-00/012.002; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.0 Mobile Safari/533.4 3gpp-gba'),
(68, 'G1A019086', 16, '2020-02-04 19:51:16', 'Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaN8-00/012.002; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.0 Mobile Safari/533.4 3gpp-gba'),
(69, 'G1A019041', 8, '2020-02-04 19:51:21', 'Mozilla/5.0 (Linux; Android 9; CPH1819) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(70, 'G1A019040', 1, '2020-02-04 19:51:46', 'Mozilla/5.0 (Linux; Android 9; RMX1821) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(71, 'G1A019016', 5, '2020-02-04 19:52:55', 'Mozilla/5.0 (Linux; Android 7.1.2; Redmi 4A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36'),
(72, 'G1A019044', 8, '2020-02-04 19:53:16', 'Mozilla/5.0 (Linux; U; Android 9; id-id; Redmi 7 Build/PKQ1.181021.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.3.4-g'),
(73, 'G1A019062', 5, '2020-02-04 19:53:37', 'Mozilla/5.0 (Linux; U; Android 7.1.2; id-id; Redmi 4A Build/N2G47H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.3.4-g'),
(74, 'G1A019018', 8, '2020-02-04 19:53:54', 'Mozilla/5.0 (Linux; Android 5.1.1; A37f) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.116 Mobile Safari/537.36'),
(75, 'G1A019054', 8, '2020-02-04 19:56:14', 'Mozilla/5.0 (Linux; U; Android 9; in-id; CPH1823 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 OppoBrowser/15.6.3.1'),
(76, 'G1A019090', 9, '2020-02-04 19:57:07', 'Mozilla/5.0 (Linux; Android 6.0; LG-K350) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.136 Mobile Safari/537.36'),
(77, 'G1A019071', 9, '2020-02-04 20:00:20', 'Mozilla/5.0 (Linux; U; Android 7.0; id-id; Redmi Note 4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.4.3-g'),
(78, 'G1C016006', 5, '2020-02-04 20:00:30', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(79, 'G1C016006', 2, '2020-02-04 20:00:30', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(80, 'G1C016006', 14, '2020-02-04 20:00:30', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(81, 'G1C016006', 19, '2020-02-04 20:00:30', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(82, 'G1C016006', 8, '2020-02-04 20:00:30', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(83, 'G1C016006', 12, '2020-02-04 20:00:30', 'Mozilla/5.0 (Linux; U; Android 9; in-id; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(84, 'G1A019072', 14, '2020-02-04 20:01:36', 'Mozilla/5.0 (Linux; U; Android 9; en-US; RMX1801 Build/PKQ1.181121.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/13.0.0.1288 Mobile Safari/537.36'),
(85, 'G1A019090', 6, '2020-02-04 20:02:24', 'Mozilla/5.0 (Linux; Android 6.0; LG-K350) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.136 Mobile Safari/537.36'),
(86, 'G1A019090', 1, '2020-02-04 20:02:24', 'Mozilla/5.0 (Linux; Android 6.0; LG-K350) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.136 Mobile Safari/537.36'),
(87, 'G1A019090', 9, '2020-02-04 20:02:24', 'Mozilla/5.0 (Linux; Android 6.0; LG-K350) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.136 Mobile Safari/537.36'),
(88, 'G1A019038', 5, '2020-02-04 20:08:38', 'Mozilla/5.0 (Linux; Android 7.0; vivo 1714 Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/5.8.0.10'),
(89, 'G1A019079', 5, '2020-02-04 20:10:56', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(90, 'G1A019017', 5, '2020-02-04 20:15:20', 'Mozilla/5.0 (Linux; U; Android 9; en-us; RMX1941 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.134 Mobile Safari/537.36 RealmeBrowser/35.5.0.8'),
(91, 'G1A019096', 1, '2020-02-04 20:19:45', 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Mobile/15E148 Safari/604.1'),
(92, 'G1A019068', 1, '2020-02-04 20:23:53', 'Mozilla/5.0 (Linux; Android 5.1.1; A37f) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.92 Mobile Safari/537.36'),
(93, 'G1A019073', 1, '2020-02-04 20:26:22', 'Mozilla/5.0 (Linux; U; Android 4.4.4; en-US; 2014811 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.13.0.1207 Mobile Safari/537.36'),
(94, 'C1B019028', 3, '2020-02-04 20:55:10', 'Mozilla/5.0 (Linux; Android 5.1.1; A37fw Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.93 Mobile Safari/537.36'),
(95, 'G1A019005', 8, '2020-02-04 20:55:46', 'Mozilla/5.0 (Linux; U; Android 9; in-id; CPH1923 Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36 OppoBrowser/25.6.3.1'),
(96, 'G1A019014', 8, '2020-02-04 21:17:55', 'Mozilla/5.0 (Linux; Android 9; ASUS_X00TD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.116 Mobile Safari/537.36'),
(97, 'G1A019014', 9, '2020-02-04 21:17:55', 'Mozilla/5.0 (Linux; Android 9; ASUS_X00TD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.116 Mobile Safari/537.36'),
(98, 'G1A019014', 11, '2020-02-04 21:17:55', 'Mozilla/5.0 (Linux; Android 9; ASUS_X00TD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.116 Mobile Safari/537.36'),
(99, 'G1A019014', 6, '2020-02-04 21:17:55', 'Mozilla/5.0 (Linux; Android 9; ASUS_X00TD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.116 Mobile Safari/537.36'),
(100, 'G1A019014', 5, '2020-02-04 21:17:55', 'Mozilla/5.0 (Linux; Android 9; ASUS_X00TD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.116 Mobile Safari/537.36'),
(101, 'G1A019014', 1, '2020-02-04 21:17:55', 'Mozilla/5.0 (Linux; Android 9; ASUS_X00TD) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.116 Mobile Safari/537.36'),
(102, 'G1A019048', 5, '2020-02-04 21:34:29', 'Mozilla/5.0 (Linux; Android 9; SM-A750GN) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(103, 'G1A019029', 15, '2020-02-04 21:49:04', 'Mozilla/5.0 (Linux; Android 9; CPH1917) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.136 Mobile Safari/537.36'),
(104, 'G1A019027', 5, '2020-02-04 21:53:05', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'),
(105, 'G1A019002', 8, '2020-02-04 22:01:06', 'Mozilla/5.0 (Linux; U; Android 9; en-US; ASUS_X00TD Build/PKQ1) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.14.0.1221 Mobile Safari/537.36'),
(106, 'G1A019098', 8, '2020-02-04 22:21:49', 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Mobile/15E148 Safari/604.1'),
(107, 'G1A019037', 14, '2020-02-05 04:51:10', 'Mozilla/5.0 (Linux; U; Android 9; id-id; Redmi Note 5 Build/PKQ1.180904.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/11.3.4-g'),
(108, 'G1A019031', 8, '2020-02-05 09:14:26', 'Mozilla/5.0 (Linux; U; Android 7.0; id-id; Redmi Note 4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/10.9.9-g');
-- --------------------------------------------------------
--
-- Struktur dari tabel `students`
--
CREATE TABLE `students` (
`id` bigint(20) UNSIGNED NOT NULL,
`npm` varchar(12) NOT NULL,
`name` varchar(32) NOT NULL,
`birthPlace` varchar(32) DEFAULT NULL,
`birthDate` date DEFAULT NULL,
`highSchoolSource` varchar(64) DEFAULT NULL,
`gender` enum('L','P') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data untuk tabel `students`
--
INSERT INTO `students` (`id`, `npm`, `name`, `birthPlace`, `birthDate`, `highSchoolSource`, `gender`) VALUES
(1, 'G1A019001', '<NAME>', 'Binjai', '2001-10-25', 'SMA N 1 Binjai', 'P'),
(2, 'G1A019002', '<NAME>', '<NAME>', '2000-12-26', 'SMA N 9 Bengkulu Utara', 'L'),
(3, 'G1A019003', '<NAME>', 'Curup', '2001-11-12', 'SMA N 1 Rejang Lebong', 'P'),
(4, 'G1A019004', '<NAME>', 'Mangunharjo', '2000-01-01', 'SMA Negeri Purwodadi', 'P'),
(5, 'G1A019005', '<NAME>', '<NAME>ata', '2001-02-19', 'SMAN 2 Bengkulu Selatan', 'P'),
(6, 'G1A019006', '<NAME>', 'Manna', '2002-05-28', ' SMAN 2 Bengkulu Selatan', 'P'),
(7, 'G1A019007', 'Renti epana sari', 'Tanjung Raman', '2001-03-31', 'SMA N 2 Bengkulu Selatan', 'P'),
(8, 'G1A019008', '<NAME>', 'Bengkulu', '2001-05-15', 'SMAN 5 KOTA BENGKULU', 'P'),
(9, 'G1A019009', '<NAME>', 'Manna', '2001-02-10', 'SMAN 2 BENGKULU SELATAN', 'L'),
(10, 'G1A019010', '<NAME>', 'Bengkulu', '2001-06-29', 'sman 5 kota bengkulu', 'L'),
(11, 'G1A019011', '<NAME>', 'Bengkulu', '2001-03-10', 'SMA 2 Kota Bengkulu', 'L'),
(12, 'G1A019012', '<NAME>', 'Pekanbaru', '2001-07-20', 'SMAN 1 kaur', 'L'),
(13, 'G1A019013', '<NAME>', '<NAME>', '2001-06-09', 'SMAN 1 Bengkulu Utara', 'L'),
(14, 'G1A019014', 'Mufti restu mahesa', 'Cilacap', '2001-10-26', 'Sman 4 sungai penuh', 'L'),
(15, 'G1A019015', '<NAME>', 'Bengkulu', '2000-12-09', 'SMAN 3 Bengkulu Tengah', 'L'),
(16, 'G1A019016', '<NAME>', '<NAME>', '2001-03-05', 'SMA N 3 Lebong', 'P'),
(17, 'G1A019017', '<NAME>', '<NAME>', '2002-08-24', 'SMAIT IQRA\'', 'P'),
(18, 'G1A019018', '<NAME>', 'Bengkulu', '2000-07-29', 'sma muhammadiyah 4 bengkulu', 'L'),
(19, 'G1A019019', '', '', '0000-00-00', '', NULL),
(20, 'G1A019020', 'Desi AdeWinda .P ', 'Siabu', '2002-12-22', 'SMA N 1 SIABU ', 'P'),
(21, 'G1A019021', '<NAME>', 'Jagong', '2002-05-10', 'SMAN 5 Takengon', 'P'),
(22, 'G1A019022', '<NAME>', 'Pematang Siantar', '2000-08-24', 'SMA Teladan Pematangsiantar', 'P'),
(23, 'G1A019023', '<NAME>', 'Bengkulu', '2001-12-09', 'SMAN 5 BKL', 'L'),
(24, 'G1A019024', '<NAME>', 'Bengkulu', '2001-04-03', 'SMA Negeri 1 Lebong', 'L'),
(25, 'G1A019025', '<NAME>', 'Bengkulu', '2001-05-29', 'SMAN 06 Kota Bengkulu', 'L'),
(26, 'G1A019026', '<NAME>', 'Bengkulu', '2000-12-29', 'SMAN 1 Bengkulu Utara', 'P'),
(27, 'G1A019027', '<NAME>', 'Bengkulu', '2001-08-24', 'SMA: 4 kota bengkulu', 'L'),
(28, 'G1A019028', '<NAME>', 'Curup', '2001-04-04', ' SMAN 1 Rejang Lebong', 'L'),
(29, 'G1A019029', '<NAME>', 'Tanjung Jaya', '2001-11-04', 'SMAN 01 Curup', 'L'),
(30, 'G1A019030', '<NAME>', 'Bengkulu', '2000-06-06', 'Smk Negeri 1 Bengkulu', 'L'),
(31, 'G1A019031', '<NAME>', 'Palembang', '2001-11-13', ' SMAN 01 Bengkulu Selatan', 'L'),
(32, 'G1A019032', '<NAME> ', 'Padang', '2001-06-14', 'sman2 Padang', 'L'),
(33, 'G1A019033', '<NAME>', 'Curup', '2001-10-25', 'sman 01 rejang lebong', 'L'),
(34, 'G1A019034', 'Ad<NAME>ario putra', 'Bengkulu', '1999-07-06', 'SMAN 1 LLG', 'L'),
(35, 'G1A019035', '<NAME>ri', 'Bengkulu', '2001-11-13', 'SMA N 5 BKL', 'P'),
(36, 'G1A019036', 'Y<NAME>', 'Bengkulu', '2001-05-01', 'sman5 kota bkl', 'L'),
(37, 'G1A019037', '<NAME>', 'Bengkulu', '2000-06-29', 'SMAN 2 Kota Bengkulu', 'P'),
(38, 'G1A019038', '<NAME>', 'Bengkulu', '2001-04-09', 'SMAN 2 kota BKL', 'P'),
(39, 'G1A019039', 'S<NAME>', 'Lahat', '2001-04-10', 'SMA Negeri 4 Lahat', 'P'),
(40, 'G1A019040', '<NAME>', 'Bengkulu', '2001-10-02', 'SMAN5 bengkulu', 'L'),
(41, 'G1A019041', '<NAME>ungkas', 'Bengkulu', '2001-06-18', 'Sman 2 Kota Bengkulu', 'L'),
(42, 'G1A019042', 'Ilpiklus Andika Putra', 'Selika', '2001-06-29', 'SMAN 2 kaur', 'L'),
(43, 'G1A019043', '<NAME>', 'Bengkulu', '2001-07-13', 'SMAN 1 Kota Bengkulu', 'P'),
(44, 'G1A019044', '<NAME>', 'Pendopo', '2001-11-03', 'SMA N 1 pendopo barat', 'P'),
(45, 'G1A019045', '', '', '0000-00-00', '', NULL),
(46, 'G1A019046', '<NAME>', '<NAME>', '2000-05-25', 'SMAN 5 Lubuklinggau', 'L'),
(47, 'G1A019047', '<NAME>', 'Bengkulu', '2001-10-01', ' sman 5 kota bengkulu', 'L'),
(48, 'G1A019048', '<NAME>', 'Bengkulu', '2001-05-31', 'SMA N 7 KOTA BENGKULU', 'L'),
(49, 'G1A019049', '<NAME>', 'Medan', '2001-02-25', 'SMAN 3 Rantau utara ', 'L'),
(50, 'G1A019050', '<NAME> ', 'Curup', '2001-02-04', ' SMAN 1 CURUP', 'L'),
(51, 'G1A019051', '<NAME>', 'L<NAME>inggau', '2001-10-13', 'sman 2 lebongselatan', 'P'),
(52, 'G1A019052', '<NAME> ', 'Bengkulu', '2001-10-27', 'Sma : 5 kota bengkulu', 'P'),
(53, 'G1A019053', '', '', '0000-00-00', '', NULL),
(54, 'G1A019054', '<NAME>', 'Bengkulu', '2000-01-01', 'SMAIT Darul Quran', 'P'),
(55, 'G1A019055', '<NAME>', 'Sarolangun', '2001-03-18', 'SMAN 2 SAROLANGUN', 'L'),
(56, 'G1A019056', '<NAME>', 'Air Hitam', '2001-05-15', 'Sman 4 mukomuko', 'L'),
(57, 'G1A019057', '<NAME>', 'Bintuhan', '2001-08-07', 'SMAN 1 Kaur', 'P'),
(58, 'G1A019058', '', '', '0000-00-00', '', NULL),
(59, 'G1A019059', '<NAME>', 'Bengkulu', '2001-09-20', 'SMAN 7 Bengkulu Utara', 'L'),
(60, 'G1A019060', '<NAME>', 'Batam', '2001-12-22', 'SMAN 09 Kota Bengkulu', 'L'),
(62, 'G1A019062', '<NAME>', 'Tais', '2001-04-10', 'SMAN 5 KOTA BENGKULU', 'L'),
(63, 'G1A019063', '<NAME>', 'Bengkulu', '2001-09-14', 'SMA IT IQRA\'', 'L'),
(64, 'G1A019064', '<NAME>', '<NAME>', '2002-06-03', 'SMAN 4 KAUR', 'L'),
(65, 'G1A019065', '<NAME> ', 'Pematang Siantar', '2002-02-24', 'SMAN 1 PEMATANGSIANTAR ', 'P'),
(66, 'G1A019066', '<NAME>', 'Bengkulu', '2001-07-19', 'Sman 2 kota bkl ', 'L'),
(67, 'G1A019067', '<NAME>', 'Pasaman', '2000-04-17', 'SMA IT IQRA', 'L'),
(68, 'G1A019068', '<NAME>', '', '0000-00-00', '', NULL),
(69, 'G1A019069', '<NAME>', '<NAME>', '2000-11-24', 'SMA N keberbakatan Olahraga bengkulu', 'L'),
(70, 'G1A019070', '', '', '0000-00-00', '', NULL),
(71, 'G1A019071', '<NAME> ', 'Palembang', '2001-11-29', 'MAN 1 Bengkulu Utara ', 'L'),
(72, 'G1A019072', '<NAME>', 'Argamakmur', '1999-12-02', 'SMA 01 Argamakmur', 'L'),
(73, 'G1A019073', '<NAME> ', 'Curup', '2001-11-09', ' sma n 2 rejang lebong', 'L'),
(74, 'G1A019074', '<NAME>', 'Bengkulu', '2001-01-14', 'SMAN 4 kota Bengkulu', 'P'),
(75, 'G1A019075', '<NAME>', 'Bengkulu', '2001-03-24', 'SMA N 7 BKL', 'L'),
(76, 'G1A019076', '<NAME>', 'Bekasi', '2002-04-22', 'SMAN 2 kota Bengkulu', 'P'),
(77, 'G1A019077', '<NAME>', 'Manna', '2001-06-04', 'SMAN2 BENGKULU SELATAN', 'P'),
(78, 'G1A019078', '<NAME>', 'Jakarta', '2001-05-16', 'SMA 2 rejang Lebong ', 'P'),
(79, 'G1A019079', '<NAME>', 'Bengkulu', '2000-12-14', 'Sman 5 bkl', 'P'),
(80, 'G1A019080', '<NAME>', 'Bengkulu', '0000-00-00', 'sman 7 kota bengkulu', 'P'),
(81, 'G1A019081', '<NAME>', 'Lahat', '2001-06-15', 'sma n 3 lahat', 'P'),
(82, 'G1A019082', '<NAME>', '<NAME>', '2001-10-02', 'SMA N Rupit', 'L'),
(83, 'G1A019083', '<NAME>', 'Bengkulu', '2001-05-15', 'SMAN 5', 'L'),
(84, 'G1A019084', '<NAME>', 'Bengkulu', '2000-11-01', 'Man 2Kota Bengkulu.', 'P'),
(85, 'G1A019085', '<NAME>', 'Lubuk Linggau', '2001-07-21', 'SMKN 3 LUBUKLINGGAU', 'L'),
(86, 'G1A019086', '<NAME>', 'Lubuk Linggau', '2000-10-19', 'SMAN 2 Kota Bengkulu', 'L'),
(87, 'G1A019087', '<NAME> ', 'Batu Raja', '2001-05-23', 'SMA N 2 BENGKULU ', 'L'),
(88, 'G1A019088', '<NAME>', 'Bengkulu', '1999-11-24', 'SMKN 1 Bengkulu Selatan', 'L'),
(89, 'G1A019089', '<NAME>', 'Bengkulu', '2001-06-02', 'Sma 7 kota Bengkulu', 'L'),
(90, 'G1A019090', '<NAME>', 'Bengkulu', '2001-10-04', 'SMAN 2 Kota Bengkulu', 'L'),
(91, 'G1A019091', '<NAME>', 'Lamongan', '2000-07-24', 'SMAN 2 KOTA BENGKULU', 'L'),
(92, 'G1A019092', 'Okto Redo', 'Jamb<NAME>', '2001-10-01', 'SMA Muhammadiyah 1 Bengkulu', 'P'),
(93, 'G1A019093', '<NAME>', 'Manna', '2001-07-25', 'SMKN 1 Bengkulu Selatan', 'P'),
(94, 'G1A019094', '<NAME>', 'Bengkulu', '2001-04-25', 'SMAN 7 BKL', 'L'),
(95, 'G1A019095', '<NAME>', 'Bengkulu', '0000-00-00', 'SMA IT IQRA', 'L'),
(96, 'G1A019096', '<NAME>', 'Bengkulu', '2000-12-21', 'SMAS IT ASSYIFA BOARDING SCHOOL SUBANG', 'L'),
(97, 'G1A019097', '<NAME> ', 'Bengkulu', '2000-12-05', 'sman 7 kota bkl', 'L'),
(98, 'G1A019098', '<NAME> ', 'Argamakmur', '2001-04-11', 'SMAN 1 BENGKULU UTARA', 'P'),
(99, 'G1A019061', '<NAME>', 'Mukomuko', '2001-05-26', 'SMA N 3 Mukomuko', 'L');
--
-- Indexes for dumped tables
--
--
-- Indeks untuk tabel `msi_survey_items`
--
ALTER TABLE `msi_survey_items`
ADD PRIMARY KEY (`id`),
ADD KEY `FK_msi_survey_item_msi_survey_parent` (`parent_id`);
--
-- Indeks untuk tabel `msi_survey_parents`
--
ALTER TABLE `msi_survey_parents`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `msi_survey_results`
--
ALTER TABLE `msi_survey_results`
ADD PRIMARY KEY (`id`),
ADD KEY `FK_msi_survey_results_msi_survey_item` (`item_id`);
--
-- Indeks untuk tabel `students`
--
ALTER TABLE `students`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT untuk tabel yang dibuang
--
--
-- AUTO_INCREMENT untuk tabel `msi_survey_items`
--
ALTER TABLE `msi_survey_items`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT untuk tabel `msi_survey_parents`
--
ALTER TABLE `msi_survey_parents`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT untuk tabel `msi_survey_results`
--
ALTER TABLE `msi_survey_results`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=109;
--
-- AUTO_INCREMENT untuk tabel `students`
--
ALTER TABLE `students`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=101;
--
-- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables)
--
--
-- Ketidakleluasaan untuk tabel `msi_survey_items`
--
ALTER TABLE `msi_survey_items`
ADD CONSTRAINT `FK_msi_survey_item_msi_survey_parent` FOREIGN KEY (`parent_id`) REFERENCES `msi_survey_parents` (`id`);
--
-- Ketidakleluasaan untuk tabel `msi_survey_results`
--
ALTER TABLE `msi_survey_results`
ADD CONSTRAINT `FK_msi_survey_results_msi_survey_item` FOREIGN KEY (`item_id`) REFERENCES `msi_survey_items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<footer class="main-footer">
<strong>Copyright © 2019 <?php echo anchor(base_url(), 'Survey MSI #10'); ?>.</strong>
</footer>
<aside class="control-sidebar control-sidebar-dark">
</aside>
</div>
<script src="<?php echo base_url('assets/adminlte/plugins/jquery/jquery.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/adminlte/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/adminlte/js/adminlte.js'); ?>"></script>
<script src="<?php echo base_url('assets/adminlte/plugins/chart.js/Chart.min.js'); ?>"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.4.0/dist/chartjs-plugin-datalabels.min.js"></script>
<script>
$(function() {
var config = {
type: 'pie',
data : {
datasets: [{
data: [
<?php foreach ($bases as $base) : ?>
<?php echo $base->jumlah; ?>,
<?php endforeach; ?>
],
backgroundColor: [
'#f7464a',
'#46bfbd',
'#fdb45c'
],
}],
labels: [
<?php foreach ($bases as $base) : ?>
'<?php echo $base->name; ?>',
<?php endforeach; ?>
]
},
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2) +"%";
return percentage;
},
color: '#fff',
}
},
responsive: true,
legend: {
position: 'top',
labels: {
fontColor: '#fff'
}
},
animation: {
animateScale: true,
animeRotate: true
}
}
}
var ChartContext = $('#stats').get(0).getContext('2d')
window.pPercentage = new Chart(ChartContext, config);
var coloR = [];
var dynamicColors = function() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return 'rgb('+ r +', '+ g +', '+ b +')';
}
var config = {
type: 'pie',
data : {
datasets: [{
data: [
<?php foreach ($all_language as $base) : ?>
<?php echo $base->jumlah; ?>,
<?php endforeach; ?>
],
backgroundColor: dynamicColors,
}],
labels: [
<?php foreach ($all_language as $base) : ?>
'<?php echo $base->name; ?> (<?php echo $base->parent; ?>)',
<?php endforeach; ?>
]
},
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2) +"%";
return percentage;
},
color: '#fff',
}
},
responsive: true,
legend: {
position: 'top',
labels: {
fontColor: '#1F8BFF'
}
},
animation: {
animateScale: true,
animeRotate: true
}
}
}
var ChartContext = $('#statsAll').get(0).getContext('2d')
window.pPercentage = new Chart(ChartContext, config);
var config = {
type: 'pie',
data : {
datasets: [{
data: [
<?php foreach ($desktop as $base) : ?>
<?php echo $base->jumlah; ?>,
<?php endforeach; ?>
],
backgroundColor: dynamicColors,
}],
labels: [
<?php foreach ($desktop as $base) : ?>
'<?php echo $base->name; ?>',
<?php endforeach; ?>
]
},
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2) +"%";
return percentage;
},
color: '#fff',
}
},
responsive: true,
legend: {
position: 'top',
labels: {
fontColor: '#1F8BFF'
}
},
animation: {
animateScale: true,
animeRotate: true
}
}
}
var ChartContext = $('#statsDesktop').get(0).getContext('2d')
window.pPercentage = new Chart(ChartContext, config);
var config = {
type: 'pie',
data : {
datasets: [{
data: [
<?php foreach ($mobiles as $base) : ?>
<?php echo $base->jumlah; ?>,
<?php endforeach; ?>
],
backgroundColor: dynamicColors,
}],
labels: [
<?php foreach ($mobiles as $base) : ?>
'<?php echo $base->name; ?>',
<?php endforeach; ?>
]
},
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2) +"%";
return percentage;
},
color: '#fff',
}
},
responsive: true,
legend: {
position: 'top',
labels: {
fontColor: '#1F8BFF'
}
},
animation: {
animateScale: true,
animeRotate: true
}
}
}
var ChartContext = $('#statsMobile').get(0).getContext('2d')
window.pPercentage = new Chart(ChartContext, config);
var config = {
type: 'pie',
data : {
datasets: [{
data: [
<?php foreach ($web as $base) : ?>
<?php echo $base->jumlah; ?>,
<?php endforeach; ?>
],
backgroundColor: dynamicColors,
}],
labels: [
<?php foreach ($web as $base) : ?>
'<?php echo $base->name; ?>',
<?php endforeach; ?>
]
},
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2) +"%";
return percentage;
},
color: '#fff',
}
},
responsive: true,
legend: {
position: 'right',
labels: {
fontColor: '#1F8BFF'
}
},
animation: {
animateScale: true,
animeRotate: true
}
}
}
var ChartContext = $('#statsWeb').get(0).getContext('2d')
window.pPercentage = new Chart(ChartContext, config);
});
</script>
<!-- Elapsed in {elapsed_time} times -->
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Report extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('report_model', 'report');
}
public function index()
{
$params['title'] = 'Hasil Survey MSI 2020';
$reports['reports'] = $this->report->reports();
$this->load->view('adminlte/header', $params);
$this->load->view('adminlte/report', $reports);
$this->load->view('adminlte/footer');
}
public function overview()
{
$params['title'] = 'Ringkasan Hasil Survey';
$overview['total']['base'] = $this->report->total_base();
$overview['total']['items'] = $this->report->total_language();
$overview['total']['students'] = $this->report->total_students();
$overview['total']['votes'] = $this->report->total_votes();
$stats['bases'] = $this->report->base_stats();
$stats['all_language'] = $this->report->all_language();
$stats['desktop'] = $this->report->desktop();
$stats['mobiles'] = $this->report->mobiles();
$stats['web'] = $this->report->web();
$this->load->view('adminlte/header', $params);
$this->load->view('adminlte/overview', $overview);
$this->load->view('adminlte/footer', $stats);
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Kelola Semester</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><?php echo anchor(base_url(), 'Home'); ?></li>
<li class="breadcrumb-item active">Semester</li>
</ol>
</div>
</div>
</div>
</section>
<section class="content">
<div class="card card-primary">
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover" id="semester">
<thead>
<tr>
<th>#</th>
<th>Semester</th>
</tr>
</thead>
<tbody id="semester_list"></tbody>
</table>
</div>
</div>
</div>
</section>
</div>
<div class="modal fade" id="confirmDeleteDialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Hapus Data Surat</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p class="confirmDeleteText">Yakin ingin menghapus data Semester? Tindakan ini tidak dapat dibatalkan.</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<button type="button" class="btn btn-primary confirmDeleteMailBtn">Hapus</button>
</div>
</div>
</div>
</div><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="content-wrapper">
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Ringkasan</h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active">Ringkasan</li>
</ol>
</div>
</div>
</div>
</div>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-success">
<div class="inner">
<h3><?php echo $total['base']; ?></h3>
<p>Basis</p>
</div>
<div class="icon">
<i class="ion ion-bag"></i>
</div>
</div>
</div>
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-primary">
<div class="inner">
<h3><?php echo $total['items']; ?></h3>
<p>Bahasa</p>
</div>
<div class="icon">
<i class="ion ion-stats-bars"></i>
</div>
</div>
</div>
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-warning">
<div class="inner">
<h3><?php echo $total['students']; ?></h3>
<p>Mahasiswa</p>
</div>
<div class="icon">
<i class="ion ion-person-add"></i>
</div>
</div>
</div>
<div class="col-lg-3 col-6">
<!-- small box -->
<div class="small-box bg-info">
<div class="inner">
<h3><?php echo $total['votes']; ?></h3>
<p>Pilihan</p>
</div>
<div class="icon">
<i class="ion ion-pie-graph"></i>
</div>
</div>
</div>
</div>
<div class="row">
<section class="col-lg-7 connectedSortable">
<!-- Custom tabs (Charts with tabs)-->
<div class="card p-0">
<div class="card-header">
<h3 class="card-title">
<i class="fas fa-chart-pie mr-1"></i>
Statistik Bahasa
</h3>
<div class="card-tools">
<ul class="nav nav-pills ml-auto">
<li class="nav-item">
<a class="nav-link active" href="#all" data-toggle="tab">Semua</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#desktop" data-toggle="tab">Desktop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#mobile" data-toggle="tab">Mobile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#web" data-toggle="tab">Web</a>
</li>
</ul>
</div>
</div>
<div class="card-body">
<div class="tab-content">
<div class="chart tab-pane active" id="all">
<canvas id="statsAll" height="300" style="height: 300px;"></canvas>
</div>
<div class="chart p-0 tab-pane" id="desktop">
<canvas id="statsDesktop" height="300" style="height: 300px;"></canvas>
</div>
<div class="chart tab-pane" id="mobile">
<canvas id="statsMobile" height="300" style="height: 300px;"></canvas>
</div>
<div class="chart tab-pane" id="web">
<canvas id="statsWeb" height="300" style="height: 300px;"></canvas>
</div>
</div>
</div>
</div>
</section>
<section class="col-lg-5 connectedSortable">
<div class="card bg-gradient-primary">
<div class="card-header border-0">
<h3 class="card-title">
<i class="fas fa-chart-bar"></i>
Statistik Basis
</h3>
</div>
<div class="card-body">
<canvas id="stats" height="300" style="height: 300px;"></canvas>
</div>
</div>
</section>
</div>
</div>
</section>
</div><file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<link rel="apple-touch-icon" sizes="76x76" href="<?php echo base_url('assets/msi/img/apple-icon.png'); ?>" />
<link rel="icon" type="image/png" href="<?php echo base_url('assets/msi/img/favicon.png'); ?>" />
<title>Survey Bahasa Pemrograman Paling Diminati Mahasiswa Teknik Informatika Universitas Bengkulu 2019</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<!-- CSS Files -->
<link href="<?php echo base_url('assets/msi/css/bootstrap.min.css'); ?>" rel="stylesheet" />
<link href="<?php echo base_url('assets/msi/css/paper-bootstrap-wizard.css'); ?>" rel="stylesheet" />
<!-- CSS Just for demo purpose, don't include it in your project -->
<link href="<?php echo base_url('assets/msi/css/demo.css'); ?>" rel="stylesheet" />
<!-- Fonts and Icons -->
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
<link href="<?php echo base_url('assets/msi/css/themify-icons.css'); ?>" rel="stylesheet">
</head>
<body>
<div class="image-container set-full-height" style="background-image: url('<?php echo base_url('assets/msi/img/paper-1.jpeg'); ?>')">
<div class="logo-container">
<div class="logo">
<img src="<?php echo base_url('assets/msi/img/ms2.jpg'); ?>">
</div>
<div class="brand">
<NAME>
</div>
</div>
<!-- Big container -->
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<!-- Wizard container -->
<div class="wizard-container">
<div class="card wizard-card" data-color="blue" id="wizardProfile">
<form action="#" method="POST id="itemsForm">
<div class="wizard-header text-center">
<h3 class="wizard-title">Survey #10</h3>
<p class="category">Bahasa Pemrograman Paling Diminati Mahasiswa Teknik Informatika Universitas Bengkulu 2019</p>
</div>
<div class="wizard-navigation to-hide">
<div class="progress-with-circle">
<div class="progress-bar" role="progressbar" aria-valuenow="1" aria-valuemin="1" aria-valuemax="3" style="width: 21%;"></div>
</div>
<ul>
<li>
<a href="#about" data-toggle="tab">
<div class="icon-circle">
<i class="ti-user"></i>
</div>
NPM
</a>
</li>
<li>
<a href="#base" data-toggle="tab">
<div class="icon-circle">
<i class="ti-settings"></i>
</div>
Base
</a>
</li>
<li>
<a href="#language" data-toggle="tab">
<div class="icon-circle">
<i class="ti-world"></i>
</div>
Bahasa
</a>
</li>
</ul>
</div>
<div class="tab-content to-hide">
<div class="tab-pane" id="about">
<div class="row">
<h5 class="info-text"> Masukkan NPM kamu untuk memulai...</h5>
<div class="col-sm-4 col-sm-offset-1">
<div class="picture-container">
<div class="picture">
<img src="<?php echo base_url('assets/msi/img/user.png'); ?>" class="picture-src" id="wizardPicturePreview" title="" />
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>NPM:</label>
<input name="npm" type="text" class="form-control inp-npm">
<label class="error-1 error"></label>
</div>
<div class="form-group">
<label>Nama:</label>
<input name="name" type="text" class="form-control inp-name">
</div>
</div>
</div>
</div>
<div class="tab-pane" id="base">
<h5 class="info-text">Basis pemrograman yang kamu minati</h5>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-checkbox">
<input type="checkbox" name="base[]" value="1">
<div class="card card-checkboxes card-hover-effect">
<i class="ti-html5"></i>
<p>Web</p>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-checkbox">
<input type="checkbox" name="base[]" value="2">
<div class="card card-checkboxes card-hover-effect">
<i class="ti-android"></i>
<p>Mobile</p>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-checkbox">
<input type="checkbox" name="base[]" value="3">
<div class="card card-checkboxes card-hover-effect">
<i class="ti-microsoft"></i>
<p>Desktop</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="language">
<div class="row">
<div class="col-sm-12">
<h5 class="info-text">Bahasa pemrograman yang kamu minati:</h5>
</div>
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="items"></div>
</div>
</div>
</div>
</div>
</div>
<div class="wizard-footer to-hide">
<div class="pull-right">
<input type='button' class='btn btn-next btn-fill btn-warning btn-wd' name='next' value='Selanjutnya' />
<button type="button" class="btn btn-finish btn-fill btn-warning btn-wd">Selesai</button>
</div>
<div class="pull-left">
<input type='button' class='btn btn-previous btn-default btn-wd' name='previous' value='Kembali' />
</div>
<div class="clearfix"></div>
</div>
<div class="result">
<div class="row justify-content-center">
<div class="col-sm-8 col-sm-offset-2">
<div class="col-sm-12">
<div class="choice active" data-toggle="wizard-checkbox">
<div class="card card-checkboxes card-hover-effect">
<i class="ti-star"></i>
<p>Terima Kasih!</p>
<p style="color: #333333;">Terima kasih telah mengisi kuisioner ini. Have a Nice Day!</p>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div> <!-- wizard container -->
</div>
</div><!-- end row -->
</div> <!-- big container -->
<div class="footer">
<div class="container text-center">
Tugas Mata Kuliah Manajemen Sistem Informasi. Kelompok 10
</div>
</div>
</div>
</body>
<!-- Core JS Files -->
<script src="<?php echo base_url('assets/msi/js/jquery-2.2.4.min.js'); ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/msi/js/bootstrap.min.js'); ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/msi/js/jquery.bootstrap.wizard.js'); ?>" type="text/javascript"></script>
<!-- Plugin for the Wizard -->
<script src="<?php echo base_url('assets/msi/js/demo.js'); ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/msi/js/paper-bootstrap-wizard.js'); ?>" type="text/javascript"></script>
<!-- More information about jquery.validate here: https://jqueryvalidation.org/ -->
<script src="<?php echo base_url('assets/msi/js/jquery.validate.min.js'); ?>" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.result').hide();
$('.btn-finish').click(function(e) {
e.preventDefault();
$(this).html('<i class="fa fa-spin fa-spinner"></i> Mengirim...');
var npm = $('.inp-npm').val();
var selectedItems = [];
$('.itemval:checked').each(function(i) {
var val = $(this).val();
selectedItems[i] = val;
});
$.ajax({
method: 'POST',
url: '<?php echo site_url('ajax/save_results'); ?>',
data: {
npm: npm,
items: selectedItems
},
context: this,
success: function(res) {
if (res.success) {
$('.to-hide').hide('fade');
$('.result').show();
}
else {
$(this).html('Selesai');
}
}
});
});
$('.inp-npm').keyup(function(e) {
e.preventDefault();
var npm = $(this).val();
if (npm.length == 9) {
$.ajax({
method: 'POST',
url: '<?php echo site_url('ajax/validate_npm'); ?>',
data: { npm: npm },
success: function(res) {
if ( ! res.success || ! res.is_exist) {
$('.error-1').text(res.message);
}
else {
$('.error-1').hide('fade');
var name = res.message;
$('.inp-name').val(name);
}
}
});
}
});
$('.btn-next').click(function(e) {
e.preventDefault();
$('.items').empty();
var count = $('[name="base[]"]:checked');
var col;
if (count.length == 1)
col = 12;
else if (count.length == 2)
col = 6;
else if (count.length == 3)
col = 4;
$('[name="base[]"]:checked').each(function() {
var base = $(this).val();
var logo, logoName;
if(base == 1) {
logo = 'html5';
logoName = 'Web';
}
else if(base == 2) {
logo = 'android';
logoName = 'Mobile';
}
else if(base == 3) {
logo = 'microsoft';
logoName = 'Desktop';
}
$.ajax({
method: 'POST',
url: '<?php echo site_url('ajax/items'); ?>',
data: { base: base },
success: function(res) {
if (res.success) {
var items = res.items;
var childItems = '';
for(var i = 0; i < items.length; i++) {
childItems += '<div class="item card" data-item="'+ items[i].id +'"><input type="checkbox" name="items['+ base +'][]" data-base="'+ base +'" class="itemval" data-val="'+ items[i].id +'" value="'+ items[i].id +'"><div><p>'+ items[i].name +'</p></div></div>';
}
$('.items').append('<div class="col-sm-'+ col +'"><div class="choice active"><div class="card card-checkboxes card-hover-effect"><i class="ti-'+ logo +'"></i><p>'+ logoName +'</p></div>'+ childItems +'</div></div>');
}
}
});
});
});
$('body').on('click', '.item', function(e) {
var id = $(this).data('item');
if ( $(this).hasClass('font-active')) {
$(this).removeClass('font-active');
$(this).find('[type="checkbox"]').removeAttr('checked');
}
else {
$(this).addClass('font-active');
$(this).find('[type="checkbox"]').attr('checked','true');
}
});
});
</script>
</html>
| 43112fa5db3751c18bc82e3dfccf8b02e4255e45 | [
"Markdown",
"SQL",
"PHP"
] | 15 | Markdown | mulyosyahidin/kuisioner-msi | e3a7cf265f3a2ad523cbfdb6b25961d278d8f362 | c3293aaee35a2b47c3f7182bc4aa3616f1b9eb75 |
refs/heads/master | <repo_name>lucascerdeira/trabalho-de-c<file_sep>/main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <locale.h>
// Retorna a senha somente com números
char* PassNumeric(int Size) {
char *random_pass;
time_t Time = time(NULL);
random_pass = NULL;
random_pass = (char *)realloc(random_pass, sizeof(char) * Size);
srand(Time * rand());
for (int i = 0; i < Size; i++) {
random_pass[i] = 48 + (rand() % 10);
}
return random_pass;
}
char* PassAlfa(int Size) {
int tipo = 0;
char *random_pass;
time_t seconds = time(NULL);
random_pass = NULL;
random_pass = (char *)realloc(random_pass, sizeof(char) * Size);
srand(seconds * rand());
for (int i = 0; i < Size; i++){
tipo = rand() % 2;
if (tipo == 0) {
random_pass[i] = 65 + (rand() % 26);
}
else if (tipo == 1) {
random_pass[i] = 97 + (rand() % 26);
}
}
return random_pass;
}
char* PassAlfa1(int Size) {
int tipo = 0;
char *random_pass;
time_t seconds = time(NULL);
random_pass = NULL;
random_pass = (char *)realloc(random_pass, sizeof(char) * Size);
srand(seconds * rand());
for (int i = 0; i < Size; i++){
tipo = rand() % 2;
if (tipo == 0) {
random_pass[i] = 65 + (rand() % 26);
}
else if (tipo == 1) {
random_pass[i] = 48 + (rand() % 10);
}
}
return random_pass;
}
char* PassAlfa2(int Size) {
int tipo = 0;
char *random_pass;
time_t seconds = time(NULL);
random_pass = NULL;
random_pass = (char *)realloc(random_pass, sizeof(char) * Size);
srand(seconds * rand());
for (int i = 0; i < Size; i++){
tipo = rand() % 3;
if (tipo == 0) {
random_pass[i] = 65 + (rand() % 26);
}
else if (tipo == 1) {
random_pass[i] = 97 + (rand() % 26);
}
else if (tipo == 2) {
random_pass[i] = 48 + (rand() % 10);
}
}
return random_pass;
}
char* PassGeral(int Size) {
char especiais[9] = {43, 45, 95, 64, 42, 38, 61, 36, 37};
char *random_pass;
int caracter_especial = 0;
int tipo = 0;
time_t Time = time(NULL);
random_pass = NULL;
random_pass = (char *)realloc(random_pass, sizeof(char) * Size);
srand(Time * rand());
for (int i = 0; i < Size; i++) {
tipo = rand() % 4;
if (tipo == 0) {
random_pass[i] = 65 + (rand() % 26);
} else if (tipo == 1) {
random_pass[i] = 97 + (rand() % 26);
} else if (tipo == 2) {
random_pass[i] = 48 + (rand() % 10);
} else {
caracter_especial = rand() % 10;
random_pass[i] = especiais[caracter_especial];
}
}
return random_pass;
}
int main() {
setlocale(LC_ALL, "Portuguese");
printf("GRUPO 3.\nNOMES: \n");
printf("========================\n");
printf("<NAME>\n");
printf("<NAME>\n");
printf("<NAME> \n");
printf("<NAME> \n");
printf("========================\n\n");
// Var
int Escolha_Usuario, i, Tamanho_Senha;
// Ponteiro que recebe a resposta das funções
char *Senha;
// Pronteiro que recebe os RAs do arquivo
char RA[7];
// Ponteiro para o arquivo de matriculas
FILE *MATR_FILE;
// Ponteiro para arquivo de senhas.txt
FILE *SENHA_FILE;
// Inicializando as variáveis
Escolha_Usuario = 0;
i = 0;
Tamanho_Senha = 0;
Senha = NULL;
MATR_FILE = NULL;
SENHA_FILE = NULL;
// Abre os arquivos
MATR_FILE = fopen("MATR.txt", "r");
SENHA_FILE = fopen("SENHAS.txt", "w");
// Verifica se existe o arquivo
if (MATR_FILE == NULL) {
fclose(MATR_FILE);
printf("Arquivo não encontrado ou inválido");
return 1;
}
printf("Indique o número de caracteres (mínimo de 6 caracteres): ");
while (i == 0) {
scanf("%d", &Tamanho_Senha);
if (Tamanho_Senha >= 6) {
i = 1;
} else {
printf("\nNúmero de caracteres inválido!\n");
printf("Digite a quantidade de caracteres: ");
}
}
printf("Escolha o tipo de senha que deseja gerar: \n");
printf("1. Numérica – conterá apenas algarismos.\n");
printf("2. Alfabética – conterá apenas letras maiúsculas e minúsculas.\n");
printf("3. Alfanumérica 1 – conterá letras maiúsculas e algarismos.\n");
printf("4. Alfanumérica 2 – conterá letras maiúsculas, minúsculas e algarismos.\n");
printf("5. Geral – conterá letras maiúsculas, minúsculas, algarismos e os caracteres: +, -, _ , @, *, &, =, $, %%, &\n\n");
printf("OPÇÃO: ");
i = 0;
while (i == 0) {
scanf("%d", &Escolha_Usuario);
if (Escolha_Usuario <=0 || Escolha_Usuario >= 6) {
printf("Opção incorreta!\n");
printf("OPÇÃO: ");
} else {
i = 1;
}
}
if( Escolha_Usuario == 1) {
while (fscanf(MATR_FILE, "%s\n", RA) != EOF) {
Senha = NULL;
Senha = PassNumeric(Tamanho_Senha);
fprintf(SENHA_FILE,"%s;%s;\n", RA, Senha);
free(Senha);
}
} else if (Escolha_Usuario == 2){
while (fscanf(MATR_FILE, "%s\n", RA) != EOF) {
Senha = NULL;
Senha = PassAlfa(Tamanho_Senha);
fprintf(SENHA_FILE,"%s;%s;\n", RA, Senha);
free(Senha);
}
} else if (Escolha_Usuario == 3) {
while (fscanf(MATR_FILE, "%s\n", RA) != EOF) {
Senha = NULL;
Senha = PassAlfa1(Tamanho_Senha);
fprintf(SENHA_FILE,"%s;%s;\n", RA, Senha);
free(Senha);
}
} else if (Escolha_Usuario == 4) {
while (fscanf(MATR_FILE, "%s\n", RA) != EOF) {
Senha = NULL;
Senha = PassAlfa2(Tamanho_Senha);
fprintf(SENHA_FILE,"%s;%s;\n", RA, Senha);
free(Senha);
}
} else if (Escolha_Usuario == 5) {
while (fscanf(MATR_FILE, "%s\n", RA) != EOF) {
Senha = NULL;
Senha = PassGeral(Tamanho_Senha);
fprintf(SENHA_FILE,"%s;%s;\n", RA, Senha);
free(Senha);
}
}
fclose(MATR_FILE);
fclose(SENHA_FILE);
return 0;
}<file_sep>/README.md
# Sistema de senhas desenvolvido em C
| bc92a31aa2040417e7355701572c1f645f3a3e80 | [
"Markdown",
"C"
] | 2 | C | lucascerdeira/trabalho-de-c | 42f6503de089545087f3b7ba96b91728a47d7ccd | dd310ee9759ffff1f8ad0c389cb399eba12d2b3f |
refs/heads/master | <repo_name>samarth1107/Snake-Game<file_sep>/Game.py
import pygame
import pygame.freetype
from numpy import loadtxt
import time
import sys
#Constants for the game
WIDTH, HEIGHT = (32, 32)
#moving direction for pacman
DOWN = (0,1)
RIGHT = (1,0)
TOP = (0,-1)
LEFT = (-1,0)
NOTHING = (0,0)
#Draws image for the wall
def draw_wall(screen, pos):
pixels = pixels_from_points(pos)
screen.blit(wall,(pixels))
#Draws image for the player
def draw_pacman(screen, pos):
pixels = pixels_from_points(pos)
screen.blit(pacman,(pixels))
#Draws coin image for the coin
def draw_coin(screen, pos):
pixels = pixels_from_points(pos)
x,y=pixels
x=x+4
y=y+4
screen.blit(coin,(x,y))
#Uitlity functions
def add_to_pos(pos, pos2):
return (pos[0]+pos2[0], pos[1]+pos2[1])
#to get pixel from points
def pixels_from_points(pos):
return (pos[0]*WIDTH, pos[1]*HEIGHT)
#this variable will keep track of direction of ghost or enemy
loop=[0,0,0,0,0,0]
#to draw enemy vertically
def draw_enemy_vertical(screen,pos):
pos=tuple(pos)
pixels = pixels_from_points(pos)
screen.blit(ghost,(pixels))
#to get next position of enemy in the vertical position
def enemy_vertical_pos(pos,start,end,num):
global loop
pos=list(pos)
if pos[1]>end[1] and loop[num]==0:
step=-1
elif pos[1]==start[1]:
loop[num]=0
step=-1
elif pos[1]>end[1] and loop[num]==1 :
step=+1
elif pos[1]==end[1]:
loop[num]=1
step=+1
pos[1]=pos[1]+step
return pos
#to draw enemy horizontally
def draw_enemy_horizontal(screen,pos):
pos=tuple(pos)
pixels = pixels_from_points(pos)
screen.blit(ghost,(pixels))
#to get position of ghost or enemy in the horizontal direction
def enemy_horizontal_pos(pos,start,end,num):
global loop
pos=list(pos)
if pos[0]<end[0] and loop[num]==0:
step=+1
elif pos[0]==start[0]:
loop[num]=0
step=+1
elif pos[0]<end[0] and loop[num]==1 :
step=-1
elif pos[0]==end[0]:
loop[num]=1
step=-1
pos[0]=pos[0]+step
return pos
#Initializing pygame
pygame.init()
screen = pygame.display.set_mode((640,700), 0, 32)
background = pygame.surface.Surface((700,700)).convert()
#this will define the font on the screen
myfont=pygame.font.SysFont('Comic Sans MS',20)
#to load wall image
wall=pygame.image.load('wall.png')
#to load ghost image
ghost=pygame.image.load('ghost.png')
#to load coin image
coin=pygame.image.load('coin.png')
#to load pacman image
pacman=pygame.image.load('pacman.png')
#Initializing variables
layout = loadtxt('layout.txt', dtype=str)
rows, cols = layout.shape
pacman_position = (1,1)
background.fill((0,0,0))
score=0
time_sec=0
#initial postion of enemy
enemy_1=[1,12]
enemy_2=[17,9]
enemy_3=[6,17]
enemy_4=[10,2]
enemy_5=[1,13]
#this variable will help
step=1
# Main game loop
while True:
#to set move direction to NONE if any valid is not given
move_direction=NOTHING
#if the player collects all the coins then declares him as winner
if score == 100:
scoretext=myfont.render("winner winner in "+str(time_sec)+" second",0,(0,255,0))
#to set position of winner text on screen
screen.blit(scoretext,(200,650))
pygame.display.update()
#all these condition will reset the game
pacman_position=(1,1)
move_direction = DOWN
score=0
layout = loadtxt('layout.txt', dtype=str)
time_sec=0
time.sleep(10)
#to get event form pygame screen
for event in pygame.event.get():
#to exit from game
if event.type ==pygame.QUIT:
exit()
#to get input from keyboard
elif event.type == pygame.KEYDOWN:
if event.key==pygame.K_DOWN:
move_direction = DOWN
elif event.key==pygame.K_RIGHT:
move_direction = RIGHT
elif event.key==pygame.K_LEFT:
move_direction = LEFT
elif event.key==pygame.K_UP:
move_direction = TOP
#to set background to bkack color
screen.blit(background, (0,0))
#to show score
scoretext=myfont.render("Score is "+str(score),0,(0,255,0))
screen.blit(scoretext,(0,650))
#to keep record of time
time_sec+=0.5
#to show time
timetext=myfont.render("Time is "+str(time_sec),0,(0,255,0))
screen.blit(timetext,(0,670))
#to get previous position of pacman (to be use in the enemy condition)
S_pacman_position=pacman_position
#to get new position of pacman
pacman_position = add_to_pos(pacman_position, move_direction)
#to draw and collect coins from screen
for col in range(cols):
for row in range(rows):
value = layout[row][col]
pos = (col, row)
#to collect coins and mark it "." and increase score by 1
if pacman_position==pos and value=='c':
layout[row][col]="."
score+=1
#to not move pacman if the next postion given by user is wall
if pacman_position==pos and value =='w':
#set move direction to NONE
move_direction = NOTHING
pacman_position=S_pacman_position
#if the pacman goes out of the pygame screen
if pacman_position[1]>20 or pacman_position[0]>20 or pacman_position<(0,0):
#all these condition will reset the game
pacman_position=(1,1)
move_direction = DOWN
score=0
layout = loadtxt('layout.txt', dtype=str)
scoretext=myfont.render("Try again",0,(0,255,0))
#to set position of text on screen
screen.blit(scoretext,(200,650))
time.sleep(2)
#to draw wall and coin
if value == 'w':
draw_wall(screen, pos)
elif value == 'c':
draw_coin(screen, pos)
#to draw all enemy and ghost
draw_enemy_vertical(screen,enemy_1)
draw_enemy_vertical(screen,enemy_2)
draw_enemy_horizontal(screen,enemy_3)
draw_enemy_horizontal(screen,enemy_4)
draw_enemy_horizontal(screen,enemy_5)
#to update the screen
pygame.display.update()
#if pacman comes in the way of ghost or enemy
if list(pacman_position)==enemy_1 or list(pacman_position)==enemy_2 or list(pacman_position)==enemy_3 or list(pacman_position)==enemy_4 or list(pacman_position)==enemy_5 or list(S_pacman_position)==enemy_1 or list(S_pacman_position)==enemy_2 or list(S_pacman_position)==enemy_3 or list(S_pacman_position)==enemy_4 or list(S_pacman_position)==enemy_5:
pacman_position=(1,1)
move_direction = DOWN
score=score-1
layout = loadtxt('layout.txt', dtype=str)
scoretext=myfont.render("Try again",0,(0,255,0))
#to set position of text on screen
screen.blit(scoretext,(200,650))
time.sleep(2)
#to get new position of all enemy or ghost
enemy_1=enemy_vertical_pos(enemy_1,[1,12],[1,1],1)
enemy_2=enemy_vertical_pos(enemy_2,[17,8],[17,4],2)
enemy_3=enemy_horizontal_pos(enemy_3,[6,17],[14,17],3)
enemy_4=enemy_horizontal_pos(enemy_4,[10,2],[18,2],4)
enemy_5=enemy_horizontal_pos(enemy_5,[1,13],[18,13],5)
#this will move pacman from extrerme left opening to extreme right opening or vice versa
if pacman_position==(0,9):
pacman_position=(19,9)
elif pacman_position==(19,9):
pacman_position=(0,9)
#to draw pacman on screen
draw_pacman(screen, pacman_position)
#to update screen and show new elements on screen
pygame.display.update()
#to put computer on sleep for 0.5 second
time.sleep(0.5)
<file_sep>/README.md
# Snake-Game
simple snake game with image, txt and python script
| 2f1d84bc8e3f3cfb426297eeec110fc92a644970 | [
"Markdown",
"Python"
] | 2 | Python | samarth1107/Snake-Game | 5696ffb67c81a6e7399b6f1a0656bc7d00ebb478 | 992f6b6e488ae40de9ebb7d1fc0f562626e8d552 |
refs/heads/master | <file_sep>const model = require('../db/model');
const nunjucks = require('../nunjucks');
let
Pet = model.Pet,
User = model.User;
(async () => {
var user = await User.create({
name: 'John',
gender: false,
email: 'john-' + Date.now() + '@garfield.pet',
passwd: '<PASSWORD>'
});
// console.log('created: ' + JSON.stringify(user));
var cat = await Pet.create({
ownerId: user.id,
name: 'Garfield',
gender: false,
birth: '2007-07-07',
});
// console.log('created: ' + JSON.stringify(cat));
var dog = await Pet.create({
ownerId: user.id,
name: 'Odie',
gender: false,
birth: '2008-08-08',
});
// console.log('created: ' + JSON.stringify(dog));
})();
var fn_hello = async (ctx, next) => {
var name = ctx.params.name;
var data = await Pet.findAll({
where: {
name: name
}
});
console.log(data)
if(data.length){
ctx.response.body = `<ul><li>Hello, ${data[0].id}!</li>
<li>Hello, ${data[0].name}!</li>
<li>Hello, ${data[0].birth}!</li>
<li>Hello, ${data[0].version}!</li>
<li>Hello, ${data[0].createAt}!</li></ul>`;
}else{
ctx.response.body = `<h1>没有哟!</h1>`;
}
};
var fn_kitty = async (ctx, next) => {
var name = ctx.params.name;
var data = await User.findAll({
where: {
name: name
}
});
// console.log(data)
if(data.length){
// ctx.response.body = `<h1>Hello, ${data[0].email}!</h1>
// <h1>Hello, ${data[0].name}!</h1>
// <h1>Hello, ${data[0].passwd}!</h1>
// <h1>Hello, ${data[0].version}!</h1>
// <h1>Hello, ${data[0].createAt}!</h1>`;
ctx.response.body = nunjucks.render('hello.html', {data:data});
}else{
ctx.response.body = `<h1>没有哟!</h1>`;
}
};
module.exports = {
'GET /kitty/:name': fn_hello,
'GET /kitty2/:name': fn_kitty
};<file_sep>const fs = require('fs');
function addControllers(router, dirName) {
var files = fs.readdirSync(__dirname + `/${dirName}`);
var js_files = files.filter(f => f.endsWith('.js'));
js_files.forEach(f=>{
console.log(`process controller: ${f}...`);
const mapping = require(__dirname + `/${dirName}/` + f);
mapping.forEach(route=>{
if (route.startsWith('GET ')) {
var path = route.substring(4);
router.get(path, mapping[route]);
console.log(`register route mapping: GET ${path}`);
} else if (route.startsWith('POST ')) {
var path = route.substring(5);
router.post(path, mapping[route]);
console.log(`register URL mapping: POST ${path}`);
} else {
console.log(`invalid URL: ${route}`);
}
})
})
}
// addControllers(router);
module.exports = function (dir) {
let
controllers_dir = dir || 'controllers', // 如果不传参数,扫描目录默认为'controllers'
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
};<file_sep>node-koa2-demo
===========================
###########环境依赖
node v7.6+
mysql 5.7
###########部署步骤
1. 添加系统环境变量
2. npm install //安装node运行环境
3. npm start //前端编译
###########目录结构描述
├── controllers // 路由
│ ├── hello.js // hello字段路由
│ ├── index.js // index字段路由
│ └── kitty.js // kitty字段路由
│
├── views // html模板
│ └── hello.html
│
├── node_modules
├── db // mysql model配置
│ ├── config.js
│ ├── db.js
│ ├── db_init.js
│ ├── model.js
│ └── models // 多table 模板
│ ├── Pet.js
│ └── User.js
│
├── app.js
├── controller.js // 路由配置
├── nunjucks.js // 模板引擎 配置
├── Readme.md // help
└── package.json
###########V1.0.0 版本内容更新
1. 新功能 aaaaaaaaa
2. 新功能 bbbbbbbbb
3. 新功能 ccccccccc
4. 新功能 ddddddddd | aa417a6b3f44b3b3618a090c7b5ce4a89338de82 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | pipiyuan/node_koa2 | 831fb607533a71b13df487d8cd08f47998186bc7 | 9113e918e60a1c5db3dcf35930e4d5bbaea2e15b |
refs/heads/master | <repo_name>JohnnyNeagoe/GoT-GIPHS<file_sep>/assets/javascript/script.js
var topics = ["<NAME>", "<NAME>", "House Stark", "<NAME>", "<NAME>", "<NAME>"];
renderButtons();
$(document).on("click", ".topic", displayGifs);
function renderButtons() {
$("#buttonsView").empty();
for (var i = 0; i < topics.length; i++) {
var a = $("<button>");
a.addClass("topic");
a.attr("data-name", topics[i]);
a.text(topics[i]);
$("#buttonsView").append(a);
}
}
$("#addGif").on("click", function(event) {
event.preventDefault();
var searchName = $("#gifInput").val().trim();
var wordList =["<NAME>"]
topics.push(searchName);
renderButtons();
});
function displayGifs(){
$("#gifView").empty();
var searchName = $(this).attr("data-name");
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + searchName + "&api_key=<KEY>&limit=10";
$.ajax({
url: queryURL,
method: "GET"
})
.then(function(response) {
var results = response.data;
for (var i = 0; i < results.length; i++) {
var actionState = results[i].images.fixed_height.url;
var stillState = results[i].images.fixed_height_still.url;
var gifDiv = $("<div class='gifHold'>");
var rating = results[i].rating;
var p = $("<p>").text("Rating: " + rating);
var resultsImage = $("<img class='item'>");
resultsImage.attr("src", stillState);
resultsImage.attr("data-still", stillState);
resultsImage.attr("data-animate", actionState);
resultsImage.attr("data-state", "still");
gifDiv.prepend(p);
gifDiv.prepend(resultsImage);
$("#gifView").prepend(gifDiv);
};
$(".item").on("click", function(){
if ($(this).attr("data-state") === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate")
} else {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
}
});
});
}
<file_sep>/README.md
# GoT-GIPHS
Game of Thrones Giph Generator
| a79affd391f47f95bd421b47df41816207eb75d5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | JohnnyNeagoe/GoT-GIPHS | 69afa3260f7fd1ff973b26b70db7586402ac782a | 382876165c59643aedd5c6b7a884199e442695d4 |
refs/heads/master | <repo_name>thimmaiah/life_of_a_trade<file_sep>/app/views/positions/show.json.jbuilder
json.partial! '/positions/show', position: @position
json.partial! '/layouts/permissions', entity: @position<file_sep>/app/indices/customer_index.rb
ThinkingSphinx::Index.define :customer, :with => :real_time do
# fields
indexes name
indexes credit_rating
indexes account_number
set_property :enable_star => 1
set_property :min_infix_len => 3
set_property :dict => :keywords
set_property :field_weights => {
:name => 10,
:credit_rating => 5,
:account_number => 8
}
end
<file_sep>/app/views/teams/show.json.jbuilder
json.partial! 'teams/show', team: @team
json.users do
json.partial! 'users/index', users: @team.users
end<file_sep>/app/models/contest.rb
class Contest < ActiveRecord::Base
has_many :teams
STATES = ["Not Started", "Started", "Paused", "Ended"]
scope :active, ->() { where(:is_active => true)}
end
<file_sep>/app/views/trades/_show.json.jbuilder
json.extract! trade, :id, :contest_id, :team_id, :quantity, :price, :security_id, :buy_sell, :customer_id, :created_at, :updated_at
json.trade_date display_date(trade.trade_date)
json.settlement_date display_date(trade.settlement_date)
json.security_name trade.security.name if trade.security
json.security_ticker trade.security.ticker if trade.security
json.customer_name trade.customer.name if trade.customer
json.customer_name team.name if trade.team
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :omniauthable
include DeviseTokenAuth::Concerns::User
# Roles for users
ADMIN = "Admin"
TRADER = "Trader"
OPS = "Ops"
SIM = "Simulation"
end
<file_sep>/spec/factories.rb
# require 'factory_girl'
# load File.expand_path("spec/factories.rb")
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :user do
ignore do
user_role nil
type nil
end
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
email { Faker::Internet.email }
password {<PASSWORD>}
confirmation_sent_at { Time.now }
confirmed_at { Time.now }
sign_in_count { 5 }
role { user_role ? user_role : "Trader" }
trait :new_user do
confirmed_at nil
confirmation_sent_at nil
sign_in_count nil
user_role "Reader"
end
factory :admin do
role {"Super User"}
end
end
factory :trade do
quantity { 10 * (1+rand(10))}
price { 10 + rand(100) }
security_id { Security.offset(rand(Security.count)).first.id }
customer_id { Customer.offset(rand(Customer.count)).first.id }
buy_sell { ["Buy", "Sell"][rand(2)] }
trade_date { Date.today }
settlement_date { Date.today + 1.day }
user_id { User.offset(rand(User.count)).first.id }
team_id { User.find(user_id).team_id }
contest_id { User.find(user_id).contest_id }
end
factory :customer do
name { Faker::Company.name }
credit_rating {Customer::RATINGS[rand(Customer::RATINGS.length)]}
bank { "BONY" }
account_number {1_000_000 + Random.rand(10_000_000 - 1_000_000)}
end
factory :contest do
name { "Contest #{rand(5**5)}" }
description { Faker::Company.catch_phrase }
startDate {Date.today + rand(10)}
currentTradeDate { startDate }
is_active {true}
auto_inc_days {true}
end
factory :team do
name { "Team #{rand(5**5)}" }
description { Faker::Company.catch_phrase }
contest_id { Contest.offset(rand(Contest.count)).first.id }
end
factory :security do
name { Faker::Company.name }
ticker { (0...3).map { ('a'..'z').to_a[rand(26)] }.join.upcase }
description { Faker::Company.catch_phrase }
sector {Security::SECTORS[rand(Security::SECTORS.length)]}
region {Security::REGIONS[rand(Security::REGIONS.length)]}
asset_class {Security::ASSET_CLASSES[rand(Security::ASSET_CLASSES.length)]}
price {(rand(10) + 1)**2}
tick_size {rand(10) + 1}
liquidity {Security::LIQUIDITY[rand(Security::LIQUIDITY.length)]}
end
end
<file_sep>/app/models/security.rb
class Security < ActiveRecord::Base
ASSET_CLASSES = ["Stock", "Bond", "Derivative"]
REGIONS = ["US", "EU", "EMEA", "APAC"]
SECTORS = ["Auto", "Pharma", "Manufacturing", "Construction", "Technology"]
LIQUIDITY = ["None", "Low", "Medium", "High", "Very High"]
after_save ThinkingSphinx::RealTime.callback_for(:security)
end
<file_sep>/app/views/teams/_index.json.jbuilder
json.array!(teams) do |team|
json.extract! team, :id, :is_active, :name, :description, :contest_id
json.url team_url(team, format: :json)
json.contest team.contest.name if team.contest
json.partial! '/layouts/permissions', entity: team
end
<file_sep>/app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
if(!user)
@user = User.new
else
@user = user
end
case @user.role
when "Contestant"
contestant_privilages
when "Team Admin"
team_admin_privilages
when "Contest Admin"
contest_admin_privilages
when "Super User"
super_user_privilages
else
guest_privilages
end
end
def guest_privilages
can [:read, :search], :all
end
def contestant_privilages
guest_privilages
can [:manage], Trade, :team_id=>@user.team_id
can [:read], Position, :team_id=>@user.team_id
can [:manage], User, :id=>@user.id
can [:read, :search], User, :team_id=>@user.team_id
end
def team_admin_privilages
contestant_privilages
can [:manage], User, :team_id=>@user.team_id
end
def contest_admin_privilages
team_admin_privilages
can [:read], Position, :contest_id => @user.contest_id
can [:read], Trade, :contest_id => @user.contest_id
can [:manage], Team, :contest_id => @user.contest_id
can [:create], Contest
can [:manage], Contest, :id => @user.contest_id
can [:manage], User, :contest_id => @user.contest_id
can [:read], User, :contest_id => @user.contest_id
can [:manage], Customer
can [:manage], Security
end
def super_user_privilages
can [:read, :manage], :all
end
end
<file_sep>/app/views/trades/show.json.jbuilder
json.partial! '/trades/show', trade: @trade
json.partial! '/layouts/permissions', entity: @trade<file_sep>/app/indices/team_index.rb
ThinkingSphinx::Index.define :team, :with => :real_time do
# fields
indexes name
set_property :enable_star => 1
set_property :min_infix_len => 3
set_property :dict => :keywords
set_property :field_weights => {
:name => 10
}
end
<file_sep>/app/views/positions/_show.json.jbuilder
json.extract! position, :id, :contest_id, :team_id, :name, :quantity, :average_price, :pnl, :eod_mark, :created_at, :updated_at
json.security do
json.partial! '/securities/show', security: position.security
end
<file_sep>/app/views/trades/index.json.jbuilder
json.array!(@trades) do |trade|
json.partial! '/trades/show', trade: trade
json.partial! '/layouts/permissions', entity: trade
end
<file_sep>/app/views/users/show.json.jbuilder
json.extract! @user, :id, :last_name, :first_name, :email, :role, :account_balance, :blocked_amount :created_at, :updated_at
if current_user.id == @user.id
json.extended_permissions do
[Contest, Team, User, Security, Customer, Trade, Position].each do |entity|
json.set! entity.to_s do
json.read can?(:read, entity)
json.create can?(:create, entity)
end
end
end
end<file_sep>/app/views/teams/index.json.jbuilder
json.partial! '/teams/index', teams: @teams<file_sep>/lib/tasks/generate_test_data.rake
namespace :lot do
require "faker"
require 'digest/sha1'
require 'factory_girl'
# require File.expand_path("spec/factories.rb")
desc "Cleans p DB - DELETES everything - watch out"
task :emptyDB => :environment do
User.delete_all
Trade.delete_all
Position.delete_all
Security.delete_all
Customer.delete_all
Contest.delete_all
Team.delete_all
end
desc "generates fake users for testing"
task :generateFakeUsers => :environment do
begin
# Now generate some consumers
(1..20).each do |j|
u = FactoryGirl.build(:user)
u.save
puts "User #{u.id}"
end
(1..10).each do |j|
u = FactoryGirl.build(:user, role: "Simulation", account_balance: 1000000000)
u.save
puts "User #{u.id}"
end
rescue Exception => exception
puts exception.backtrace.join("\n")
raise exception
end
end
desc "generates fake users for testing"
task :generateFakeAdmin => :environment do
begin
u = FactoryGirl.build(:user, email: "<EMAIL>", password: "<EMAIL>", role: "Super")
u.save
puts u.to_xml
rescue Exception => exception
puts exception.backtrace.join("\n")
raise exception
end
end
desc "generates Securities"
task :generateSecurities => :environment do
(1..50).each do
FactoryGirl.create(:security)
end
end
desc "generates Customers"
task :generateCustomers => :environment do
(1..50).each do
FactoryGirl.create(:customer)
end
end
desc "generates Trades"
task :generateTrades => :environment do
User.where(role: "Contestant").each do |u|
(1..5).each do
FactoryGirl.create(:trade, {team_id: u.team_id, user_id: u.id, contest_id: u.contest_id})
end
end
end
desc "Generating all Fake Data"
task :generateFakeAll => [:emptyDB, :generateFakeUsers, :emptyDB, :generateSecurities, :generateCustomers] do
puts "Generating all Fake Data"
end
end<file_sep>/app/models/position.rb
class Position < ActiveRecord::Base
has_many :trades
belongs_to :security
belongs_to :team
before_create:defaults
def defaults
self.quantity = 0 if self.quantity.nil?
end
before_save :compute_avg_price
def compute_avg_price
val = 0
qty = 0
self.quantity = 0
self.trades.reload
self.trades.each do |trade|
if trade.buy?
val += trade.value
qty += trade.quantity
end
self.quantity += trade.quantity
end
self.average_price = qty > 0 ? val/qty : 0
end
def value
self.quantity * self.average_price
end
def recompute_pnl
Rails.logger.debug "recompute_pnl: Position #{self.id} for Team #{self.team_id}"
# recompute
# save
# broadcast
end
after_save :broadcast
def broadcast
json_data = ApplicationController.new.render_to_string(
:partial => '/positions/show.json', :locals => {:position=>self}
)
channel = "/positions/#{self.team.contest_id}/#{self.team_id}"
Rails.logger.debug "Broadcasting #{json_data} on #{channel}"
RestClient.post "http://localhost:9292/faye", message: {channel: channel, data: json_data}.to_json
end
end
<file_sep>/app/views/teams/_show.json.jbuilder
json.extract! team, :id, :name, :description, :contest_id, :is_active, :created_at, :updated_at
json.contest team.contest.name if team.contest
json.partial! '/layouts/permissions', entity: team
<file_sep>/app/views/positions/index.json.jbuilder
json.array!(@positions) do |position|
json.extract! position, :id, :contest_id, :team_id, :name, :quantity, :average_price, :pnl, :eod_mark
json.url position_url(position, format: :json)
json.security do
json.partial! '/securities/show', security: position.security
end
json.partial! '/layouts/permissions', entity: position
end
<file_sep>/app/views/layouts/_permissions.json.jbuilder
json.permissions do
json.read can?(:read, entity)
json.manage can?(:manage, entity)
end<file_sep>/app/views/customers/_index.json.jbuilder
json.array!(customers) do |customer|
json.extract! customer, :id, :name, :credit_rating, :bank, :account_number
json.url customer_url(customer, format: :json)
json.partial! '/layouts/permissions', entity: customer
end
<file_sep>/app/models/customer.rb
class Customer < ActiveRecord::Base
RATINGS = ["AAA", "AA", "A", "BBB", "BB", "B", "C", "Junk"]
after_save ThinkingSphinx::RealTime.callback_for(:customer)
end
<file_sep>/app/models/team.rb
class Team < ActiveRecord::Base
has_many :users
has_many :trades
belongs_to :contest
after_save ThinkingSphinx::RealTime.callback_for(:team)
scope :active, ->() { where(:is_active => true)}
# This is to ensure all users in this team have the current contest set correctly
after_save :update_user_contest
def update_user_contest
self.users.update_all(contest_id: self.contest_id)
end
def recompute_pnl
Rails.logger.debug "recompute_pnl: Team #{self.id}"
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
mount_devise_token_auth_for 'User', at: 'auth'
resources :users
resources :positions
resources :trades do
collection do
get 'search'
end
end
resources :customers do
collection do
get 'search'
end
end
resources :teams do
collection do
get 'search'
end
end
resources :contests
resources :securities do
collection do
get 'search'
end
end
root to: "home#index"
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def display_date(input_date)
if input_date
return input_date.strftime("%m/%d/%Y")
end
return ""
end
def display_date_w_day(input_date)
if input_date
return input_date.strftime("%a, %b %d, %Y")
end
return ""
end
def display_short_date(input_date)
if input_date
return input_date.strftime("%b %d, %Y")
end
return ""
end
def display_date_time(input_date)
if input_date
return input_date.strftime("%m/%d/%Y %I:%M %p")
end
return ""
end
def display_time(input_time)
if input_time
return input_time.strftime("%I:%M %p")
end
return ""
end
end
<file_sep>/app/views/securities/_index.json.jbuilder
json.array!(securities) do |security|
json.extract! security, :id, :name, :liquidity, :ticker, :description, :price, :asset_class, :region, :tick_size, :sector
json.url security_url(security, format: :json)
json.partial! '/layouts/permissions', entity: security
end
<file_sep>/app/models/trade.rb
class Trade < ActiveRecord::Base
belongs_to :security
belongs_to :customer
belongs_to :team
belongs_to :user
belongs_to :position
# before_create :new_position
# after_create :update_position
def new_position
if self.position == nil
pos_params = { security_id:self.security_id, team_id: self.team_id, contest_id: self.contest_id }
existing_pos = Position.where(pos_params).first
self.position = existing_pos ? existing_pos : Position.new(pos_params)
self.position.save
self.position_id = self.position.id
end
end
def update_position
self.position.save
end
def value
self.quantity * self.price
end
def buy?
buy_sell == "Buy"
end
# after_save :broadcast
def broadcast
json_data = ApplicationController.new.render_to_string(
:partial => '/trades/show.json', :locals => {:trade=>self}
)
channel = "/trades/#{self.team.contest_id}/#{self.team_id}"
Rails.logger.debug "Broadcasting #{json_data} on #{channel}"
RestClient.post "http://localhost:9292/faye", message: {channel: channel, data: json_data}.to_json
end
end
<file_sep>/README.md
# Life Of A Trade
# Setup
1. Clone the repo
2. To load all the required gems, run command "bundle"
3. To create the DB schema run command "bundle exec rake db:create"
4. To load the required tables run "bundle exec rake db:schema:load"
5. To populate with dummy data run ""bundle exec rake lot:generateFakeAll"
<file_sep>/app/indices/user_index.rb
ThinkingSphinx::Index.define :user, :with => :real_time do
# fields
indexes first_name
indexes last_name
indexes email
set_property :enable_star => 1
set_property :min_infix_len => 3
set_property :dict => :keywords
set_property :field_weights => {
:first_name => 10,
:last_name => 10,
:email => 6
}
end
<file_sep>/app/views/contests/show.json.jbuilder
json.extract! @contest, :id, :name, :is_active, :description, :created_at, :updated_at, :state, :auto_inc_days
json.currentTradeDate display_date(@contest.currentTradeDate)
json.startDate display_date(@contest.startDate)
json.teams do
json.partial! 'teams/index', teams: @contest.teams
end
json.partial! '/layouts/permissions', entity: @contest
<file_sep>/app/views/customers/index.json.jbuilder
json.partial! '/customers/index', customers: @customers<file_sep>/app/indices/security_index.rb
ThinkingSphinx::Index.define :security, :with => :real_time do
# fields
indexes name
indexes ticker
indexes asset_class
indexes sector
indexes region
set_property :enable_star => 1
set_property :min_infix_len => 3
set_property :dict => :keywords
set_property :field_weights => {
:name => 10,
:ticker => 10,
:asset_class => 5,
:sector => 7,
:region => 5
}
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
respond_to :json
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
# protect_from_forgery with: :exception
rescue_from CanCan::AccessDenied do |exception|
render status: 403, template: "/layouts/access_denied.json"
end
end
<file_sep>/app/views/layouts/access_denied.json.jbuilder
json.access_denied do
json.user_id current_user.id
end<file_sep>/app/views/customers/show.json.jbuilder
json.extract! @customer, :id, :name, :credit_rating, :bank, :account_number, :created_at, :updated_at
json.partial! '/layouts/permissions', entity: @customer<file_sep>/app/views/securities/index.json.jbuilder
json.partial! '/securities/index', securities: @securities<file_sep>/faye.ru
# Start using the following command
# rackup faye.ru -s thin -E production
require 'faye'
Faye::WebSocket.load_adapter('thin')
app = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25)
app.on(:publish) do |client_id, channel, data|
puts "#{channel} recvd #{data}"
end
run app<file_sep>/app/views/securities/show.json.jbuilder
json.partial! '/securities/show', security: @security
json.partial! '/layouts/permissions', entity: @security<file_sep>/app/views/contests/index.json.jbuilder
json.array!(@contests) do |contest|
json.extract! contest, :id, :is_active, :name, :description, :state, :currentTradeDate, :startDate, :auto_inc_days
json.url contest_url(contest, format: :json)
json.partial! '/layouts/permissions', entity: contest
end
| 2b8be7c9301fe1dccd140da58b1e829178515c14 | [
"Markdown",
"Ruby"
] | 40 | Ruby | thimmaiah/life_of_a_trade | e22c14495b44029d2ce62fc78e772c38d2e2f15a | e4c41e0d6e883cbf3c84d648bfb983fb12e72efa |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace PassGen
{
public partial class Form1 : Form
{
//We don't want these characters, they are excluded
public char[] lstExclude = new char[] { 'o', '0', 'O', 'i', 'l' };
//Array of numbers
public char[] lstNumbers = "0123456789".ToCharArray();
//Array of lower case characters
public char[] lstLowerCase = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
//Array of upper case characters
public char[] lstUpperCase = Enumerable.Range('A', 'Z' - 'A' + 1).Select(i => (Char)i).ToArray();
//Array of special characters
public char[] lstSymbols = @"`-=~!@#$%^&*()_+{[}]|\\""':;<,>.?/".ToCharArray();
//This is the password array
List<char> lstPassword = new List<char>(new char[] { });
//Initialize the random generator
public Random intRandom = new Random();
public Form1()
{
InitializeComponent();
}
private void btnGenerate_Click(object sender, EventArgs e)
{
//This is going to be our password at the end
string strPassword;
//And it's length
int intPassLen;
//A temp counter
int intCounter = 0;
//Minimum length of our password
int intMin = Convert.ToInt32(nMin.Value);
//Maximum length of our password
int intMax = Convert.ToInt32(nMax.Value);
//The difference
int intDiff = intMin - intMax;
//If there is no difference between the max/min lenght
//Then we have a static length of the password
if (intDiff == 0)
{
intPassLen = intMax;
} else
{
//If not, we'll have to generate a random length (min/max)
intPassLen = intRandom.Next(intMin, intMax + 1);
}
do
{
//Get a random character
char chLetter = (char)intRandom.Next(33, 127);
//Check the conditions (uppercase/lowercase, exclusions, numerals, symbols
if (!((lstExclude.Contains(chLetter)) ||
((lstLowerCase.Contains(chLetter) && !cbLowercase.Checked)) ||
((lstUpperCase.Contains(chLetter) && !cbUppercase.Checked)) ||
((lstNumbers.Contains(chLetter) && !cbNumbers.Checked)) ||
((lstSymbols.Contains(chLetter) && !cbSymbols.Checked))))
{
//If all conditions are met, add the character to the array
lstPassword.Add(chLetter);
intCounter++;
}
// Loop until you reach the desired password length
} while (intCounter < intPassLen);
//Convert the array of characters to a string
strPassword = string.Join("", lstPassword.ToArray());
//Clear the password char array so it doesn't add up
lstPassword.Clear();
//Update the texbox on the screen
tbPassword.Text = strPassword;
//Update the length label on the screen
lblLength.Text = "Length:" + strPassword.Length.ToString();
}
private void nMin_ValueChanged(object sender, EventArgs e)
{
//Don't allow the min value to be bigger than the max value
if (nMin.Value > nMax.Value) nMin.Value = nMax.Value;
}
private void txtExclude_TextChanged(object sender, EventArgs e)
{
//Add the excluded character from the text box to the exclusion array
lstExclude = txtExclude.Text.ToCharArray();
}
}
}
<file_sep># PassGen
PassGen is a small utility that generates random and strong passwords.
You can include numbers, symbols, lowercase and uppercase characters and exclude any of these specifically.
You can also choose the minimum and maximum length of the password.

Click on Generate to get your password, then select the text at the top and copy with CTRL-C.
# Download
You can compile from the source with Visual Studio and .NET 4.5 or download the binary from the releases section.
| e1d863f498647da37bd8cc0eb1e0dc36cb96c472 | [
"Markdown",
"C#"
] | 2 | C# | klimenta/PassGen | 91fe7c5ff8a3b330c2dddb6cfce4627c798b7daa | d335482bec197c92dc34c6843e09076c8422fee8 |
refs/heads/master | <repo_name>dmvaldman/elba<file_sep>/README.md
> ### *Able was I ere I saw Elba* – Napoleon
Elba makes JavaScript appear to be written backwards. For example,
```
(function hi(){
console.log('elba');
})();
```
Will become
```
'';(function hi(){ console.log('elba');})();
```
When either version is executed it will log the string `elba`. Try it in your JavaScript console.
For a more complicated example, here is [underscore.js](https://gist.githubusercontent.com/dmvaldman/8238a65a460ffea046888c1872db66f5/raw/cd70b743086164b8db0fa2c3cc9ef0b13f3b3fc7/erocsrednu.js)
<img src="http://i.imgur.com/yZxfEx3.png">
## Installation:
```
npm install -g elba
```
## Usage
```
elba myFile.js > eliFym.js
```
## How it works:
`\u202E` is the unicode right-to-left override character.
It will make any text after it appear right-to-left until the presence of
a `\u202D` (left-to-right override character) or a newline character.
For example: `"\u202E" + "hello"` is interpreted as `"olleh"`.
To make your source code backwards, we turn it into a single string (with no line breaks) and add a `\u202E` character
near the beginning. The gotchya is that this string must also be interpretable as a valid JavaScript file.
If both these are true, then it will be displayed backwards by any text-editor that supports
bi-directional text and will still work exactly as intended. The code only _appears_ backwards in the editor.
Let's call the user specified source code `S`. We first remove all comments and line-breaks from `S`. We then prepend the source code with
`'\u202E';`. Then, `'\u202E'; S` is both a one-line string, AND valid JavaScript (when interpreted). 🙃
<file_sep>/index.js
#!/usr/bin/env node
var fs = require('fs');
var file = process.argv[2];
if (!file) process.exit(0);
var readStream = fs.createReadStream(file, 'utf8');
var text = "'\u202E';"; // Prepend this to the source code
readStream.on('data', function(buf){
var str = buf.toString('utf8');
str = str.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm, ""); // replace comments and multiple spaces
str = str.replace(/\n/g, ""); // replace line breaks
str = str.replace(/\s+/g, " "); // replace multiple spaces with single space
text += str;
}).on('end', function(){
process.stdout.write(text);
});
| 613d2613a2e05980114b1e11beeebd5e7189afc5 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | dmvaldman/elba | 1ea66481868c8232ac9c1940625acae0d3251a5f | 22a07568443a7431bcf271085ca246e434153a50 |
refs/heads/master | <file_sep>library(plotly)
library(dplyr)
library(janitor)
#### Średnia i minimalna pensja####
# Plik wzięty z bazy danych GUS
pensja_df = read.csv('pensja.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
pensja_df = subset(pensja_df, select = -c(Kod,X,Nazwa))
pensja_df = t(pensja_df)
pensja_df = unname(pensja_df)
pensja_df = as.data.frame(pensja_df) #Jest bez 2019
# Miesięczna pensja w województwach
DOLNO = as.numeric(gsub(",", ".", as.character(pensja_df$V1)))
KUJAW = as.numeric(gsub(",", ".", as.character(pensja_df$V2)))
LUBEL = as.numeric(gsub(",", ".", as.character(pensja_df$V3)))
LUBUS = as.numeric(gsub(",", ".", as.character(pensja_df$V4)))
LODZK = as.numeric(gsub(",", ".", as.character(pensja_df$V5)))
MALOP = as.numeric(gsub(",", ".", as.character(pensja_df$V6)))
MAZOW = as.numeric(gsub(",", ".", as.character(pensja_df$V7)))
OPOLS = as.numeric(gsub(",", ".", as.character(pensja_df$V8)))
PODKA = as.numeric(gsub(",", ".", as.character(pensja_df$V9)))
PODLA = as.numeric(gsub(",", ".", as.character(pensja_df$V10)))
POMOR = as.numeric(gsub(",", ".", as.character(pensja_df$V11)))
SLASK = as.numeric(gsub(",", ".", as.character(pensja_df$V12)))
SWIET = as.numeric(gsub(",", ".", as.character(pensja_df$V13)))
WARMI = as.numeric(gsub(",", ".", as.character(pensja_df$V14)))
WIELK = as.numeric(gsub(",", ".", as.character(pensja_df$V15)))
ZACHO = as.numeric(gsub(",", ".", as.character(pensja_df$V16)))
#Wykres
srednie_pensja_plot = plot_ly(x = 1:13) %>%
layout(title = 'Wzrost średniej pensji w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018"),
tickvals = list(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)),
yaxis = list(title = 'Średnia pensja (zł)')) %>%
add_lines(y = DOLNO, name = "Dolnośląskie")%>%
add_lines(y = KUJAW, name = "Kujawsko-pomorskie")%>%
add_lines(y = LUBEL, name = "Lubelskie")%>%
add_lines(y = LUBUS, name = "Lubuskie")%>%
add_lines(y = LODZK, name = "Łódzkie")%>%
add_lines(y = MALOP, name = "Małopolskie")%>%
add_lines(y = MAZOW, name = "Mazowieckie")%>%
add_lines(y = OPOLS, name = "Opolskiea")%>%
add_lines(y = PODKA, name = "Podkarpackie")%>%
add_lines(y = PODLA, name = "Podlaskie")%>%
add_lines(y = POMOR, name = "pomorskie")%>%
add_lines(y = SLASK, name = "Śląskie")%>%
add_lines(y = SWIET, name = "świętokrzyskie")%>%
add_lines(y = WARMI, name = "Warmińsko-mazurskie")%>%
add_lines(y = WIELK, name = "Wielkopolskie")%>%
add_lines(y = ZACHO, name = "Zachodniopomorskie")
### Minimalna pensja 2006-2019 ###
placa_min = c(899,936,1126,1276,1317,1386,1500,1600,1680,1750,1850,2000,2100,2250)
placa_min_df = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(placa_min_df) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
#Wykres
o = 1:14
placa_min_plot = plot_ly(x = o) %>%
layout(title = 'Wzrost płacy minimalnej brutto w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018"),
tickvals = list(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)),
yaxis = list(title = 'Kwota brutto (zł)')) %>%
add_lines(y = placa_min, name = "Płaca minimalna")
# Uzupełniam tabelę wartościami płacy minimalnej
for (i in 1:13) {
placa_min_df[1,i] = as.numeric(placa_min[i])
placa_min_df[2,i] = as.numeric(placa_min[i])
placa_min_df[3,i] = as.numeric(placa_min[i])
placa_min_df[4,i] = as.numeric(placa_min[i])
placa_min_df[5,i] = as.numeric(placa_min[i])
placa_min_df[6,i] = as.numeric(placa_min[i])
placa_min_df[7,i] = as.numeric(placa_min[i])
placa_min_df[8,i] = as.numeric(placa_min[i])
placa_min_df[9,i] = as.numeric(placa_min[i])
placa_min_df[10,i] = as.numeric(placa_min[i])
placa_min_df[11,i] = as.numeric(placa_min[i])
placa_min_df[12,i] = as.numeric(placa_min[i])
placa_min_df[13,i] = as.numeric(placa_min[i])
placa_min_df[14,i] = as.numeric(placa_min[i])
placa_min_df[15,i] = as.numeric(placa_min[i])
placa_min_df[16,i] = as.numeric(placa_min[i])
}
placa_min_df = t(placa_min_df)
placa_min_df = unname(placa_min_df)
placa_min_df = as.data.frame(placa_min_df)
### Minimalna pensja 2006-2019 ###
placa_min2012_2019 = c(1500,1600,1680,1750,1850,2000,2100,2250)
placa_min2012_2019_df = data.frame('','','','','','','','', stringsAsFactors = FALSE)
names(placa_min2012_2019_df) = c("2012","2013","2014","2015","2016","2017","2018")
# Uzupełniam tabelę wartościami płacy minimalnej
for (i in 1:8) {
placa_min2012_2019_df[1,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[2,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[3,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[4,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[5,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[6,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[7,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[8,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[9,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[10,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[11,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[12,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[13,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[14,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[15,i] = as.numeric(placa_min2012_2019[i])
placa_min2012_2019_df[16,i] = as.numeric(placa_min2012_2019[i])
}
placa_min2012_2019_df = t(placa_min2012_2019_df)
placa_min2012_2019_df = unname(placa_min2012_2019_df)
placa_min2012_2019_df = as.data.frame(placa_min2012_2019_df)
#### Województwe i daty ####
wojewodztwa = c("dolnoślaskim","kujawsko-pomorskim","lubelskim","lubuskim","łódzkim",
"małopolskim","mazowieckim","opolskim","podkarpackim","podlaskim",
"pomorskim","ślaskim","świetokrzyskim","warminsko-mazurskim",
"wielkopolskim","zachodniopomorskim")
daty = seq(as.Date("2006/1/1"), by = "month", length.out = 168, format = "%Y %B")
daty = format(daty, "%B %Y")
#### Wczytywanie plików ####
ryz_df = read.csv('(1) Ryż.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
kurczak_df = read.csv('(9) Kurczęta patroszone.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
kielbasa_wedzona_df = read.csv('(12) Kiełbasa wędzona.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
kielbasa_wedzona_df_2 = read.csv('(12) Kiełbasa wędzone 2.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
smietana_df = read.csv('(19) Śmietana 18% - 200g.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
maslo_df = read.csv('(22) Masło - 200g.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
czekolada_df = read.csv('(32) Czekolada - 100g.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
spodnie_df = read.csv('(42) Spodnie jeans 06-17.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
spodnie_df2 = read.csv('(42) Spodnie jeans 18-19.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
buty_df = read.csv('(45) Półbuty damskie.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
zlewozmywak_df = read.csv('(47) Zlewozmywak.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
lekarz_df = read.csv('(54) Lekarz.csv',header = TRUE,sep = ";",encoding = "UTF-8",stringsAsFactors=FALSE)
#### Ryż edycja nagłówków i tabel ####
ryz_df = subset(ryz_df, select = -c(Kod,X)) #Usuwam zbędną kolumnę Kod i X
#Edtuję nazwy kolumn na sensowne
names(ryz_df) <- gsub("styczeń.ryż...za.1kg.cena.", "styczeń.", names(ryz_df))
names(ryz_df) <- gsub("luty.ryż...za.1kg.cena.", "luty.", names(ryz_df))
names(ryz_df) <- gsub("marzec.ryż...za.1kg.cena.", "marzec.", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.ryż...za.1kg.cena.", "kwiecień.", names(ryz_df))
names(ryz_df) <- gsub("maj.ryż...za.1kg.cena.", "maj.", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.ryż...za.1kg.cena.", "czerwiec.", names(ryz_df))
names(ryz_df) <- gsub("lipiec.ryż...za.1kg.cena.", "lipiec.", names(ryz_df))
names(ryz_df) <- gsub("sierpień.ryż...za.1kg.cena.", "sierpień.", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.ryż...za.1kg.cena.", "wrzesień.", names(ryz_df))
names(ryz_df) <- gsub("październik.ryż...za.1kg.cena.", "październik.", names(ryz_df))
names(ryz_df) <- gsub("listopad.ryż...za.1kg.cena.", "listopad.", names(ryz_df))
names(ryz_df) <- gsub("grudzień.ryż...za.1kg.cena.", "grudzień.", names(ryz_df))
names(ryz_df) <- gsub("..zł.", "", names(ryz_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(ryz_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(ryz_df))
names(ryz_df) <- gsub("luty.2006", "2006 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2007", "2007 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2008", "2008 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2009", "2009 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2010", "2010 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2011", "2011 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2012", "2012 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2013", "2013 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2014", "2014 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2015", "2015 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2016", "2016 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2017", "2017 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2018", "2018 2 luty", names(ryz_df))
names(ryz_df) <- gsub("luty.2019", "2019 2 luty", names(ryz_df))
names(ryz_df) <- gsub("marzec.2006", "2006 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2007", "2007 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2008", "2008 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2009", "2009 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2010", "2010 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2011", "2011 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2012", "2012 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2013", "2013 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2014", "2014 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2015", "2015 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2016", "2016 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2017", "2017 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2018", "2018 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("marzec.2019", "2019 3 marzec", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(ryz_df))
names(ryz_df) <- gsub("maj.2006", "2006 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2007", "2007 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2008", "2008 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2009", "2009 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2010", "2010 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2011", "2011 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2012", "2012 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2013", "2013 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2014", "2014 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2015", "2015 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2016", "2016 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2017", "2017 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2018", "2018 5 maj", names(ryz_df))
names(ryz_df) <- gsub("maj.2019", "2019 5 maj", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(ryz_df))
names(ryz_df) <- gsub("październik.2006", "2006 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2007", "2007 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2008", "2008 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2009", "2009 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2010", "2010 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2011", "2011 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2012", "2012 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2013", "2013 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2014", "2014 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2015", "2015 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2016", "2016 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2017", "2017 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2018", "2018 90 październik", names(ryz_df))
names(ryz_df) <- gsub("październik.2019", "2019 90 październik", names(ryz_df))
names(ryz_df) <- gsub("listopad.2006", "2006 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2007", "2007 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2008", "2008 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2009", "2009 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2010", "2010 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2011", "2011 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2012", "2012 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2013", "2013 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2014", "2014 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2015", "2015 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2016", "2016 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2017", "2017 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2018", "2018 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("listopad.2019", "2019 91 listopad", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(ryz_df))
names(ryz_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(ryz_df))
ryz_df = ryz_df[sort(colnames(ryz_df))] #Sortuję chronologicznie
ryz_df = subset(ryz_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
ryz_df = t(ryz_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
ryz_df = unname(ryz_df) #Usuwam zbędne teraz nazwy
ryz_df = as.data.frame(ryz_df) #Przekształcam na dataframe
#Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
#wartości NA
ryz_dolnoslaskie = as.numeric(gsub(",", ".", as.character(ryz_df$V1)))
ryz_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(ryz_df$V2)))
ryz_lubelskie = as.numeric(gsub(",", ".", as.character(ryz_df$V3)))
ryz_lubuskie = as.numeric(gsub(",", ".", as.character(ryz_df$V4)))
ryz_lodzkie = as.numeric(gsub(",", ".", as.character(ryz_df$V5)))
ryz_malopolskie = as.numeric(gsub(",", ".", as.character(ryz_df$V6)))
ryz_mazowieckie = as.numeric(gsub(",", ".", as.character(ryz_df$V7)))
ryz_opolskie = as.numeric(gsub(",", ".", as.character(ryz_df$V8)))
ryz_podkarpackie = as.numeric(gsub(",", ".", as.character(ryz_df$V9)))
ryz_podlaskie = as.numeric(gsub(",", ".", as.character(ryz_df$V10)))
ryz_pomorskie = as.numeric(gsub(",", ".", as.character(ryz_df$V11)))
ryz_slaskie = as.numeric(gsub(",", ".", as.character(ryz_df$V12)))
ryz_swietokrzyskie = as.numeric(gsub(",", ".", as.character(ryz_df$V13)))
ryz_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(ryz_df$V14)))
ryz_wielkopolskie = as.numeric(gsub(",", ".", as.character(ryz_df$V15)))
ryz_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(ryz_df$V16)))
#### Wykres cen ryżu ####
y = (1:168)
#Wykres dla ryzu i wszystkich województw
ryz_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen ryżu w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = ryz_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = ryz_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = ryz_lubelskie, name = "lubelskie")%>%
add_lines(y = ryz_lubuskie, name = "lubuskie")%>%
add_lines(y = ryz_lodzkie, name = "łódzkie")%>%
add_lines(y = ryz_malopolskie, name = "małopolskie")%>%
add_lines(y = ryz_mazowieckie, name = "mazowieckie")%>%
add_lines(y = ryz_opolskie, name = "opolskie")%>%
add_lines(y = ryz_podkarpackie, name = "podkarpackie")%>%
add_lines(y = ryz_podlaskie, name = "podlaskie")%>%
add_lines(y = ryz_pomorskie, name = "pomorskie")%>%
add_lines(y = ryz_slaskie, name = "śląskie")%>%
add_lines(y = ryz_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = ryz_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = ryz_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = ryz_zachodniopomorskie, name = "zachodniopomorskie")
#print(ryz_plot)
#### Średnie roczne ceny ryżu ####
roczne_sr_ryz = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_ryz) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_ryz[1,i] = round(mean(ryz_dolnoslaskie[(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[2,i] = round(mean(ryz_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[3,i] = round(mean(ryz_lubelskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[4,i] = round(mean(ryz_lubuskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[5,i] = round(mean(ryz_lodzkie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[6,i] = round(mean(ryz_malopolskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[7,i] = round(mean(ryz_mazowieckie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[8,i] = round(mean(ryz_opolskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[9,i] = round(mean(ryz_podkarpackie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[10,i] = round(mean(ryz_podlaskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[11,i] = round(mean(ryz_pomorskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[12,i] = round(mean(ryz_slaskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[13,i] = round(mean(ryz_swietokrzyskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[14,i] = round(mean(ryz_warminsko_mazurskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[15,i] = round(mean(ryz_wielkopolskie [(1+(i-1)*12):(12*i)]),digits = 2)
roczne_sr_ryz[16,i] = round(mean(ryz_zachodniopomorskie[(1+(i-1)*12):(12*i)]),digits = 2)
}
roczne_sr_ryz = t(roczne_sr_ryz)
roczne_sr_ryz = unname(roczne_sr_ryz) #Usuwam zbędne teraz nazwy
roczne_sr_ryz = as.data.frame(roczne_sr_ryz) #Przekształcam na dataframe
#### Średnia cena ryżu dla każdego wojewódstwa ####
ryz_dolnoslaskie_sr = round(mean(ryz_dolnoslaskie), digits = 2) #1
ryz_kujawsko_pomorskie_sr = round(mean(ryz_kujawsko_pomorskie), digits = 2) #2
ryz_lubelskie_sr = round(mean(ryz_lubelskie), digits = 2) #3
ryz_lubuskie_sr = round(mean(ryz_lubuskie), digits = 2) #4
ryz_lodzkie_sr = round(mean(ryz_lodzkie), digits = 2) #5
ryz_malopolskie_sr = round(mean(ryz_malopolskie), digits = 2) #6
ryz_mazowieckie_sr = round(mean(ryz_mazowieckie), digits = 2) #7
ryz_opolskie_sr = round(mean(ryz_opolskie), digits = 2) #8
ryz_podkarpackie_sr = round(mean(ryz_podkarpackie), digits = 2) #9
ryz_podlaskie_sr = round(mean(ryz_podlaskie), digits = 2) #10
ryz_pomorskie_sr = round(mean(ryz_pomorskie), digits = 2) #11
ryz_slaskie_sr = round(mean(ryz_slaskie), digits = 2) #12
ryz_swietokrzyskie_sr = round(mean(ryz_swietokrzyskie), digits = 2) #13
ryz_warminsko_mazurskie_sr = round(mean(ryz_warminsko_mazurskie), digits = 2) #14
ryz_wielkopolskie_sr = round(mean(ryz_wielkopolskie), digits = 2) #15
ryz_zachodniopomorskie_sr = round(mean(ryz_zachodniopomorskie), digits = 2) #16
#### Średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_ryz = c(ryz_dolnoslaskie_sr,ryz_kujawsko_pomorskie_sr,ryz_lubelskie_sr,ryz_lubuskie_sr,ryz_lodzkie_sr,
ryz_malopolskie_sr,ryz_mazowieckie_sr,ryz_opolskie_sr,ryz_podkarpackie_sr,ryz_podlaskie_sr,
ryz_pomorskie_sr,ryz_slaskie_sr,ryz_swietokrzyskie_sr,ryz_warminsko_mazurskie_sr,
ryz_wielkopolskie_sr,ryz_zachodniopomorskie_sr)
ryz_najmn_w_kazdym_woj = c(min(ryz_dolnoslaskie),min(ryz_kujawsko_pomorskie),min(ryz_lubelskie),
min(ryz_lubuskie),min(ryz_lodzkie),min(ryz_malopolskie),
min(ryz_mazowieckie),min(ryz_opolskie),min(ryz_podkarpackie),
min(ryz_podlaskie),min(ryz_pomorskie),min(ryz_slaskie),
min(ryz_swietokrzyskie),min(ryz_warminsko_mazurskie),
min(ryz_wielkopolskie),min(ryz_zachodniopomorskie))
ryz_najw_w_kazdym_woj = c(max(ryz_dolnoslaskie),max(ryz_kujawsko_pomorskie),max(ryz_lubelskie),
max(ryz_lubuskie),max(ryz_lodzkie),max(ryz_malopolskie),
max(ryz_mazowieckie),max(ryz_opolskie),max(ryz_podkarpackie),
max(ryz_podlaskie),max(ryz_pomorskie),max(ryz_slaskie),
max(ryz_swietokrzyskie),max(ryz_warminsko_mazurskie),
max(ryz_wielkopolskie),max(ryz_zachodniopomorskie))
### Najwyższe i najniższe, różne
ryz_sr_cena = mean(sr_cena_ryz) #Średnia cena ryżu dla całego kraju
ryz_odsd_cena = sd(sr_cena_ryz) #Odchylenie standardowe ceny ryżu
ryz_najw_sr = max(sr_cena_ryz) #Najwyższa średnia cena ryżu
ryz_najm_sr = min(sr_cena_ryz) #Najniższa średnia cena ryżu
ryz_najmn_k = min(ryz_najmn_w_kazdym_woj) #Najniższa cena kiedykolwiek
ryz_najw_k = max(ryz_najw_w_kazdym_woj) #Najwyższa cena kiedykolwiek
rnajw_sr = as.numeric(match(ryz_najw_sr,sr_cena_ryz)) #Numer województwa
rnajmn_sr = as.numeric(match(ryz_najm_sr,sr_cena_ryz)) #Numer województwa
print(paste("Najwyższa średnia cena ryżu jest w województwie", wojewodztwa[rnajw_sr],
"i wynosi",ryz_najw_sr))
print(paste("Najniższa średnia cena ryżu jest w województwie", wojewodztwa[rnajmn_sr],
"i wynosi",ryz_najm_sr))
rnajmn_kazde = as.numeric(match(ryz_najmn_k,ryz_najmn_w_kazdym_woj)) #Numer województwa
rnajw_kazde = as.numeric(match(ryz_najw_k,ryz_najw_w_kazdym_woj)) #Numer województwa
rnajmn_kiedy = match(ryz_najmn_k,ryz_opolskie) #Kiedy
rnajw_kiedy = match(ryz_najw_k,ryz_swietokrzyskie) #Kiedy
print(paste("Najniższa cena ryżu była", daty[rnajmn_kiedy], "w województwie",
wojewodztwa[rnajmn_kazde],"i wynosiła", ryz_najmn_k, "zł"))
print(paste("Najwyższa cena ryżu była", daty[rnajw_kiedy], wojewodztwa[rnajw_kazde],
"i wynosiła", ryz_najw_k, "zł"))
print(paste("Odchylenie standardowe cen ryżu wynosi", round(ryz_odsd_cena, digits = 4), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny ryżu ####
ryz_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_ryz$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_ryz$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_ryz$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_ryz$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_ryz$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_ryz$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_ryz$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_ryz$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_ryz$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_ryz$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_ryz$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_ryz$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_ryz$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny ryżu wynosi", round(mean(ryz_placa_min_kor), digits = 4), "co wskazuje na raczej małą korelację"))
#### Korelacja średniej pensji do średniej ceny ryżu ####
ryz_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_ryz$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_ryz$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_ryz$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_ryz$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_ryz$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_ryz$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_ryz$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_ryz$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_ryz$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_ryz$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_ryz$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_ryz$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_ryz$V13))),
cor(WARMI, as.numeric(as.character(roczne_sr_ryz$V14))),
cor(WIELK, as.numeric(as.character(roczne_sr_ryz$V15))),
cor(ZACHO, as.numeric(as.character(roczne_sr_ryz$V16))))
sr_ryz_kor = mean(ryz_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny ryżu wynosi", round(sr_ryz_kor, digits = 4), "co wskazuje na raczej małą korelację"))
print(".........................................................")
#### Kurczak edycja nagłówków i tabel ####
kurczak_df = subset(kurczak_df, select = -c(Kod,X) ) #Usuwam zbędną kolumnę Kod i X
#Edtuję nazwy kolumn na sensowne
names(kurczak_df) <- gsub("styczeń.kurczęta.patroszone...za.1kg.cena.", "styczeń.", names(kurczak_df))
names(kurczak_df) <- gsub("luty.kurczęta.patroszone...za.1kg.cena.", "luty.", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.kurczęta.patroszone...za.1kg.cena.", "marzec.", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.kurczęta.patroszone...za.1kg.cena.", "kwiecień.", names(kurczak_df))
names(kurczak_df) <- gsub("maj.kurczęta.patroszone...za.1kg.cena.", "maj.", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.kurczęta.patroszone...za.1kg.cena.", "czerwiec.", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.kurczęta.patroszone...za.1kg.cena.", "lipiec.", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.kurczęta.patroszone...za.1kg.cena.", "sierpień.", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.kurczęta.patroszone...za.1kg.cena.", "wrzesień.", names(kurczak_df))
names(kurczak_df) <- gsub("październik.kurczęta.patroszone...za.1kg.cena.", "październik.", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.kurczęta.patroszone...za.1kg.cena.", "listopad.", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.kurczęta.patroszone...za.1kg.cena.", "grudzień.", names(kurczak_df))
names(kurczak_df) <- gsub("..zł.", "", names(kurczak_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(kurczak_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2006", "2006 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2007", "2007 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2008", "2008 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2009", "2009 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2010", "2010 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2011", "2011 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2012", "2012 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2013", "2013 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2014", "2014 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2015", "2015 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2016", "2016 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2017", "2017 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2018", "2018 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("luty.2019", "2019 2 luty", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2006", "2006 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2007", "2007 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2008", "2008 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2009", "2009 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2010", "2010 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2011", "2011 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2012", "2012 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2013", "2013 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2014", "2014 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2015", "2015 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2016", "2016 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2017", "2017 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2018", "2018 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("marzec.2019", "2019 3 marzec", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2006", "2006 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2007", "2007 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2008", "2008 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2009", "2009 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2010", "2010 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2011", "2011 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2012", "2012 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2013", "2013 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2014", "2014 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2015", "2015 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2016", "2016 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2017", "2017 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2018", "2018 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("maj.2019", "2019 5 maj", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2006", "2006 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2007", "2007 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2008", "2008 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2009", "2009 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2010", "2010 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2011", "2011 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2012", "2012 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2013", "2013 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2014", "2014 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2015", "2015 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2016", "2016 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2017", "2017 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2018", "2018 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("październik.2019", "2019 90 październik", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2006", "2006 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2007", "2007 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2008", "2008 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2009", "2009 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2010", "2010 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2011", "2011 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2012", "2012 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2013", "2013 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2014", "2014 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2015", "2015 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2016", "2016 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2017", "2017 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2018", "2018 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("listopad.2019", "2019 91 listopad", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(kurczak_df))
names(kurczak_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(kurczak_df))
kurczak_df = kurczak_df[sort(colnames(kurczak_df))] #Sortuję chronologicznie
kurczak_df = subset(kurczak_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
kurczak_df = t(kurczak_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
kurczak_df = unname(kurczak_df) #Usuwam zbędne teraz nazwy
kurczak_df = as.data.frame(kurczak_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
kurczak_dolnoslaskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V1)))
kurczak_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V2)))
kurczak_lubelskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V3)))
kurczak_lubuskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V4)))
kurczak_lodzkie = as.numeric(gsub(",", ".", as.character(kurczak_df$V5)))
kurczak_malopolskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V6)))
kurczak_mazowieckie = as.numeric(gsub(",", ".", as.character(kurczak_df$V7)))
kurczak_opolskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V8)))
kurczak_podkarpackie = as.numeric(gsub(",", ".", as.character(kurczak_df$V9)))
kurczak_podlaskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V10)))
kurczak_pomorskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V11)))
kurczak_slaskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V12)))
kurczak_swietokrzyskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V13)))
kurczak_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V14)))
kurczak_wielkopolskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V15)))
kurczak_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(kurczak_df$V16)))
#### Wykres cen kurczaka ####
y = (1:168)
#Wykres dla kurczaka i wszystkich województw
kurczak_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen kurczaka w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = kurczak_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = kurczak_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = kurczak_lubelskie, name = "lubelskie")%>%
add_lines(y = kurczak_lubuskie, name = "lubuskie")%>%
add_lines(y = kurczak_lodzkie, name = "łódzkie")%>%
add_lines(y = kurczak_malopolskie, name = "małopolskie")%>%
add_lines(y = kurczak_mazowieckie, name = "mazowieckie")%>%
add_lines(y = kurczak_opolskie, name = "opolskie")%>%
add_lines(y = kurczak_podkarpackie, name = "podkarpackie")%>%
add_lines(y = kurczak_podlaskie, name = "podlaskie")%>%
add_lines(y = kurczak_pomorskie, name = "pomorskie")%>%
add_lines(y = kurczak_slaskie, name = "śląskie")%>%
add_lines(y = kurczak_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = kurczak_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = kurczak_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = kurczak_zachodniopomorskie, name = "zachodniopomorskie")
#print(kurczak_plot)
#### Średnie roczne ceny kurczaka ####
roczne_sr_kurczak = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_kurczak) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_kurczak[1,i] = round(mean(kurczak_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[2,i] = round(mean(kurczak_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[3,i] = round(mean(kurczak_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[4,i] = round(mean(kurczak_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[5,i] = round(mean(kurczak_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[6,i] = round(mean(kurczak_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[7,i] = round(mean(kurczak_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[8,i] = round(mean(kurczak_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[9,i] = round(mean(kurczak_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[10,i] = round(mean(kurczak_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[11,i] = round(mean(kurczak_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[12,i] = round(mean(kurczak_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[13,i] = round(mean(kurczak_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[14,i] = round(mean(kurczak_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[15,i] = round(mean(kurczak_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kurczak[16,i] = round(mean(kurczak_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_kurczak = t(roczne_sr_kurczak)
roczne_sr_kurczak = unname(roczne_sr_kurczak) #Usuwam zbędne teraz nazwy
roczne_sr_kurczak = as.data.frame(roczne_sr_kurczak) #Przekształcam na dataframe
#### Średnia cena kurczaka dla każdego wojewódstwa ####
kurczak_dolnoslaskie_sr = round(mean(kurczak_dolnoslaskie), digits = 2) #1
kurczak_kujawsko_pomorskie_sr = round(mean(kurczak_kujawsko_pomorskie), digits = 2) #2
kurczak_lubelskie_sr = round(mean(kurczak_lubelskie), digits = 2) #3
kurczak_lubuskie_sr = round(mean(kurczak_lubuskie), digits = 2) #4
kurczak_lodzkie_sr = round(mean(kurczak_lodzkie), digits = 2) #5
kurczak_malopolskie_sr = round(mean(kurczak_malopolskie), digits = 2) #6
kurczak_mazowieckie_sr = round(mean(kurczak_mazowieckie), digits = 2) #7
kurczak_opolskie_sr = round(mean(kurczak_opolskie), digits = 2) #8
kurczak_podkarpackie_sr = round(mean(kurczak_podkarpackie), digits = 2) #9
kurczak_podlaskie_sr = round(mean(kurczak_podlaskie), digits = 2) #10
kurczak_pomorskie_sr = round(mean(kurczak_pomorskie), digits = 2) #11
kurczak_slaskie_sr = round(mean(kurczak_slaskie), digits = 2) #12
kurczak_swietokrzyskie_sr = round(mean(kurczak_swietokrzyskie), digits = 2) #13
kurczak_warminsko_mazurskie_sr = round(mean(kurczak_warminsko_mazurskie), digits = 2) #14
kurczak_wielkopolskie_sr = round(mean(kurczak_wielkopolskie), digits = 2) #15
kurczak_zachodniopomorskie_sr = round(mean(kurczak_zachodniopomorskie), digits = 2) #16
#### Kurczak średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_kurczak = c(kurczak_dolnoslaskie_sr,kurczak_kujawsko_pomorskie_sr,kurczak_lubelskie_sr,kurczak_lubuskie_sr,kurczak_lodzkie_sr,
kurczak_malopolskie_sr,kurczak_mazowieckie_sr,kurczak_opolskie_sr,kurczak_podkarpackie_sr,kurczak_podlaskie_sr,
kurczak_pomorskie_sr,kurczak_slaskie_sr,kurczak_swietokrzyskie_sr,kurczak_warminsko_mazurskie_sr,
kurczak_wielkopolskie_sr,kurczak_zachodniopomorskie_sr)
kurczak_najmn_w_kazdym_woj = c(min(kurczak_dolnoslaskie),min(kurczak_kujawsko_pomorskie),min(kurczak_lubelskie),
min(kurczak_lubuskie),min(kurczak_lodzkie),min(kurczak_malopolskie),
min(kurczak_mazowieckie),min(kurczak_opolskie),min(kurczak_podkarpackie),
min(kurczak_podlaskie),min(kurczak_pomorskie),min(kurczak_slaskie),
min(kurczak_swietokrzyskie),min(kurczak_warminsko_mazurskie),
min(kurczak_wielkopolskie),min(kurczak_zachodniopomorskie))
kurczak_najw_w_kazdym_woj = c(max(kurczak_dolnoslaskie),max(kurczak_kujawsko_pomorskie),max(kurczak_lubelskie),
max(kurczak_lubuskie),max(kurczak_lodzkie),max(kurczak_malopolskie),
max(kurczak_mazowieckie),max(kurczak_opolskie),max(kurczak_podkarpackie),
max(kurczak_podlaskie),max(kurczak_pomorskie),max(kurczak_slaskie),
max(kurczak_swietokrzyskie),max(kurczak_warminsko_mazurskie),
max(kurczak_wielkopolskie),max(kurczak_zachodniopomorskie))
### Najwyższe i najniższe, różne
kurczak_sr_cena = mean(sr_cena_kurczak) #Średnia cena ryżu dla całego kraju
kurczak_odsd_cena = sd(sr_cena_kurczak) #Odchylenie standardowe ceny ryżu
kurczak_najw_sr = max(sr_cena_kurczak) #Najwyższa średnia cena ryżu
kurczak_najm_sr = min(sr_cena_kurczak) #Najniższa średnia cena ryżu
kurczak_najmn_k = min(kurczak_najmn_w_kazdym_woj) #Najniższa cena kiedykolwiek
kurczak_najw_k = max(kurczak_najw_w_kazdym_woj) #Najwyższa cena kiedykolwiek
kur_najw_sr = as.numeric(match(kurczak_najw_sr,sr_cena_kurczak)) #Numer województwa
kur_najmn_sr = as.numeric(match(kurczak_najm_sr,sr_cena_kurczak)) #Numer województwa
print(paste("Najwyższa średnia cena kurczaka jest w województwie", wojewodztwa[kur_najw_sr],
"i wynosi",kurczak_najw_sr))
print(paste("Najniższa średnia cena kurczaka jest w województwie", wojewodztwa[kur_najmn_sr],
"i wynosi",kurczak_najm_sr))
kur_najmn_kazde = as.numeric(match(kurczak_najmn_k,kurczak_najmn_w_kazdym_woj)) #Numer województwa
kur_najw_kazde = as.numeric(match(kurczak_najw_k,kurczak_najw_w_kazdym_woj)) #Numer województwa
kur_najmn_kiedy = match(kurczak_najmn_k,kurczak_zachodniopomorskie) #Kiedy
kur_najw_kiedy = match(kurczak_najw_k,kurczak_swietokrzyskie) #Kiedy
print(paste("Najniższa cena kurczaka była w", daty[kur_najmn_kiedy], "w województwie",
wojewodztwa[kur_najmn_kazde],"i wynosiła", kurczak_najmn_k, "zł"))
print(paste("Najwyższa cena kurczaka była w", daty[kur_najw_kiedy], "w województwie",
wojewodztwa[kur_najw_kazde],"i wynosiła", kurczak_najw_k, "zł"))
print(paste("Odchylenie standardowe cen kurczaka wynosi", round(kurczak_odsd_cena, digits = 4), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny kurczaka ####
kurczak_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_kurczak$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_kurczak$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_kurczak$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_kurczak$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_kurczak$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_kurczak$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_kurczak$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_kurczak$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_kurczak$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_kurczak$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_kurczak$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_kurczak$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_kurczak$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny kurczaka wynosi", round(mean(kurczak_placa_min_kor),
digits = 4), "co wskazuje na umiarkowaną korelację"))
#### Korelacja średniej pensji do średniej ceny kurczaka ####
kurczak_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_kurczak$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_kurczak$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_kurczak$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_kurczak$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_kurczak$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_kurczak$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_kurczak$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_kurczak$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_kurczak$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_kurczak$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_kurczak$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_kurczak$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_kurczak$V13))),
cor(WARMI, as.numeric(as.character(roczne_sr_kurczak$V14))),
cor(WIELK, as.numeric(as.character(roczne_sr_kurczak$V15))),
cor(ZACHO, as.numeric(as.character(roczne_sr_kurczak$V16))))
sr_kurczak_kor = mean(kurczak_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny kurczaka wynosi", round(sr_kurczak_kor,
digits = 4), "co wskazuje na umiarkowaną korelację"))
print(".........................................................")
#### Kiełbasa edycja nagłówków i tabel ####
kielbasa_wedzona_df = kielbasa_wedzona_df %>% remove_empty("cols") # Usuwam puste kolumny
kielbasa_wedzona_df_2 = kielbasa_wedzona_df_2 %>% remove_empty("cols") # Usuwam puste kolumny
kielbasa_wedzona_df_2 = select(kielbasa_wedzona_df_2, -contains('2016')) #Usuwam 2016 rok
kielbasa_wedzona_df = full_join(kielbasa_wedzona_df, kielbasa_wedzona_df_2) #Łączę dataframy
rm(kielbasa_wedzona_df_2)
kielbasa_wedzona_df = subset(kielbasa_wedzona_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(kielbasa_wedzona_df) <- gsub("styczeń.kiełbasa.wędzona...za.1kg.cena.", "styczeń.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.kiełbasa.wędzona..2....za.1kg.cena.", "styczeń.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.kiełbasa.wędzona...za.1kg.cena.", "luty.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.kiełbasa.wędzona..2....za.1kg.cena.", "luty.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.kiełbasa.wędzona...za.1kg.cena.", "marzec.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.kiełbasa.wędzona..2....za.1kg.cena.", "marzec.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.kiełbasa.wędzona...za.1kg.cena.", "kwiecień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.kiełbasa.wędzona..2....za.1kg.cena.", "kwiecień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.kiełbasa.wędzona...za.1kg.cena.", "maj.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.kiełbasa.wędzona..2....za.1kg.cena.", "maj.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.kiełbasa.wędzona...za.1kg.cena.", "czerwiec.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.kiełbasa.wędzona..2....za.1kg.cena.", "czerwiec.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.kiełbasa.wędzona...za.1kg.cena.", "lipiec.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.kiełbasa.wędzona..2....za.1kg.cena.", "lipiec.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.kiełbasa.wędzona...za.1kg.cena.", "sierpień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.kiełbasa.wędzona..2....za.1kg.cena.", "sierpień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.kiełbasa.wędzona...za.1kg.cena.", "wrzesień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.kiełbasa.wędzona..2....za.1kg.cena.", "wrzesień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.kiełbasa.wędzona...za.1kg.cena.", "październik.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.kiełbasa.wędzona..2....za.1kg.cena.", "październik.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.kiełbasa.wędzona...za.1kg.cena.", "listopad.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.kiełbasa.wędzona..2....za.1kg.cena.", "listopad.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.kiełbasa.wędzona...za.1kg.cena.", "grudzień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.kiełbasa.wędzona..2....za.1kg.cena.", "grudzień.", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("..zł.", "", names(kielbasa_wedzona_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(kielbasa_wedzona_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2006", "2006 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2007", "2007 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2008", "2008 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2009", "2009 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2010", "2010 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2011", "2011 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2012", "2012 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2013", "2013 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2014", "2014 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2015", "2015 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2016", "2016 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2017", "2017 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2018", "2018 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("luty.2019", "2019 2 luty", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2006", "2006 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2007", "2007 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2008", "2008 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2009", "2009 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2010", "2010 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2011", "2011 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2012", "2012 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2013", "2013 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2014", "2014 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2015", "2015 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2016", "2016 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2017", "2017 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2018", "2018 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("marzec.2019", "2019 3 marzec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2006", "2006 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2007", "2007 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2008", "2008 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2009", "2009 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2010", "2010 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2011", "2011 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2012", "2012 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2013", "2013 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2014", "2014 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2015", "2015 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2016", "2016 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2017", "2017 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2018", "2018 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("maj.2019", "2019 5 maj", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2006", "2006 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2007", "2007 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2008", "2008 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2009", "2009 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2010", "2010 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2011", "2011 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2012", "2012 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2013", "2013 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2014", "2014 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2015", "2015 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2016", "2016 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2017", "2017 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2018", "2018 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("październik.2019", "2019 90 październik", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2006", "2006 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2007", "2007 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2008", "2008 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2009", "2009 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2010", "2010 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2011", "2011 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2012", "2012 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2013", "2013 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2014", "2014 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2015", "2015 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2016", "2016 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2017", "2017 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2018", "2018 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("listopad.2019", "2019 91 listopad", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(kielbasa_wedzona_df))
names(kielbasa_wedzona_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(kielbasa_wedzona_df))
kielbasa_wedzona_df = kielbasa_wedzona_df[sort(colnames(kielbasa_wedzona_df))] #Sortuję chronologicznie
#kielbasa_wedzona_df = subset(kielbasa_wedzona_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
kielbasa_wedzona_df = t(kielbasa_wedzona_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
kielbasa_wedzona_df = unname(kielbasa_wedzona_df) #Usuwam zbędne teraz nazwy
kielbasa_wedzona_df = as.data.frame(kielbasa_wedzona_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
kielbasa_wedzona_dolnoslaskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V1)))
kielbasa_wedzona_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V2)))
kielbasa_wedzona_lubelskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V3)))
kielbasa_wedzona_lubuskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V4)))
kielbasa_wedzona_lodzkie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V5)))
kielbasa_wedzona_malopolskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V6)))
kielbasa_wedzona_mazowieckie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V7)))
kielbasa_wedzona_opolskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V8)))
kielbasa_wedzona_podkarpackie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V9)))
kielbasa_wedzona_podlaskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V10)))
kielbasa_wedzona_pomorskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V11)))
kielbasa_wedzona_slaskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V12)))
kielbasa_wedzona_swietokrzyskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V13)))
kielbasa_wedzona_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V14)))
kielbasa_wedzona_wielkopolskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V15)))
kielbasa_wedzona_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(kielbasa_wedzona_df$V16)))
#### Wykres cen kiełbasy wędzonej ####
y = (1:168)
#Wykres dla kiełbasy i wszystkich województw
kielbasa_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen kiełbasy wędzonej w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = kielbasa_wedzona_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = kielbasa_wedzona_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = kielbasa_wedzona_lubelskie, name = "lubelskie")%>%
add_lines(y = kielbasa_wedzona_lubuskie, name = "lubuskie")%>%
add_lines(y = kielbasa_wedzona_lodzkie, name = "łódzkie")%>%
add_lines(y = kielbasa_wedzona_malopolskie, name = "małopolskie")%>%
add_lines(y = kielbasa_wedzona_mazowieckie, name = "mazowieckie")%>%
add_lines(y = kielbasa_wedzona_opolskie, name = "opolskie")%>%
add_lines(y = kielbasa_wedzona_podkarpackie, name = "podkarpackie")%>%
add_lines(y = kielbasa_wedzona_podlaskie, name = "podlaskie")%>%
add_lines(y = kielbasa_wedzona_pomorskie, name = "pomorskie")%>%
add_lines(y = kielbasa_wedzona_slaskie, name = "śląskie")%>%
add_lines(y = kielbasa_wedzona_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = kielbasa_wedzona_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = kielbasa_wedzona_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = kielbasa_wedzona_zachodniopomorskie, name = "zachodniopomorskie")
#print(kielbasa_plot)
#### Średnie roczne ceny kiełbasy wędzonej ####
roczne_sr_kielbasa = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_kielbasa) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_kielbasa[1,i] = round(mean(kielbasa_wedzona_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[2,i] = round(mean(kielbasa_wedzona_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[3,i] = round(mean(kielbasa_wedzona_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[4,i] = round(mean(kielbasa_wedzona_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[5,i] = round(mean(kielbasa_wedzona_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[6,i] = round(mean(kielbasa_wedzona_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[7,i] = round(mean(kielbasa_wedzona_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[8,i] = round(mean(kielbasa_wedzona_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[9,i] = round(mean(kielbasa_wedzona_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[10,i] = round(mean(kielbasa_wedzona_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[11,i] = round(mean(kielbasa_wedzona_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[12,i] = round(mean(kielbasa_wedzona_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[13,i] = round(mean(kielbasa_wedzona_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[14,i] = round(mean(kielbasa_wedzona_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[15,i] = round(mean(kielbasa_wedzona_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_kielbasa[16,i] = round(mean(kielbasa_wedzona_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_kielbasa = t(roczne_sr_kielbasa)
roczne_sr_kielbasa = unname(roczne_sr_kielbasa) #Usuwam zbędne teraz nazwy
roczne_sr_kielbasa = as.data.frame(roczne_sr_kielbasa) #Przekształcam na dataframe
#### Średnia cena kiełbasy wędzonej dla każdego wojewódstwa ####
kielbasa_dolnoslaskie_sr = round(mean(kielbasa_wedzona_dolnoslaskie), digits = 2) #1
kielbasa_kujawsko_pomorskie_sr = round(mean(kielbasa_wedzona_kujawsko_pomorskie), digits = 2) #2
kielbasa_lubelskie_sr = round(mean(kielbasa_wedzona_lubelskie), digits = 2) #3
kielbasa_lubuskie_sr = round(mean(kielbasa_wedzona_lubuskie), digits = 2) #4
kielbasa_lodzkie_sr = round(mean(kielbasa_wedzona_lodzkie), digits = 2) #5
kielbasa_malopolskie_sr = round(mean(kielbasa_wedzona_malopolskie), digits = 2) #6
kielbasa_mazowieckie_sr = round(mean(kielbasa_wedzona_mazowieckie), digits = 2) #7
kielbasa_opolskie_sr = round(mean(kielbasa_wedzona_opolskie), digits = 2) #8
kielbasa_podkarpackie_sr = round(mean(kielbasa_wedzona_podkarpackie), digits = 2) #9
kielbasa_podlaskie_sr = round(mean(kielbasa_wedzona_podlaskie), digits = 2) #10
kielbasa_pomorskie_sr = round(mean(kielbasa_wedzona_pomorskie), digits = 2) #11
kielbasa_slaskie_sr = round(mean(kielbasa_wedzona_slaskie), digits = 2) #12
kielbasa_swietokrzyskie_sr = round(mean(kielbasa_wedzona_swietokrzyskie), digits = 2) #13
kielbasa_warminsko_mazurskie_sr = round(mean(kielbasa_wedzona_warminsko_mazurskie), digits = 2) #14
kielbasa_wielkopolskie_sr = round(mean(kielbasa_wedzona_wielkopolskie), digits = 2) #15
kielbasa_zachodniopomorskie_sr = round(mean(kielbasa_wedzona_zachodniopomorskie), digits = 2) #16
#### Kiełbasa wędzona średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_kielbasa = c(kielbasa_dolnoslaskie_sr,kielbasa_kujawsko_pomorskie_sr,kielbasa_lubelskie_sr,kielbasa_lubuskie_sr,kielbasa_lodzkie_sr,
kielbasa_malopolskie_sr,kielbasa_mazowieckie_sr,kielbasa_opolskie_sr,kielbasa_podkarpackie_sr,kielbasa_podlaskie_sr,
kielbasa_pomorskie_sr,kielbasa_slaskie_sr,kielbasa_swietokrzyskie_sr,kielbasa_warminsko_mazurskie_sr,
kielbasa_wielkopolskie_sr,kielbasa_zachodniopomorskie_sr)
kielbasa_najmn_w_kazdym_woj = c(min(kielbasa_wedzona_dolnoslaskie),min(kielbasa_wedzona_kujawsko_pomorskie),min(kielbasa_wedzona_lubelskie),
min(kielbasa_wedzona_lubuskie),min(kielbasa_wedzona_lodzkie),min(kielbasa_wedzona_malopolskie),
min(kielbasa_wedzona_mazowieckie),min(kielbasa_wedzona_opolskie),min(kielbasa_wedzona_podkarpackie),
min(kielbasa_wedzona_podlaskie),min(kielbasa_wedzona_pomorskie),min(kielbasa_wedzona_slaskie),
min(kielbasa_wedzona_swietokrzyskie),min(kielbasa_wedzona_warminsko_mazurskie),
min(kielbasa_wedzona_wielkopolskie),min(kielbasa_wedzona_zachodniopomorskie))
kielbasa_najw_w_kazdym_woj = c(max(kielbasa_wedzona_dolnoslaskie),max(kielbasa_wedzona_kujawsko_pomorskie),max(kielbasa_wedzona_lubelskie),
max(kielbasa_wedzona_lubuskie),max(kielbasa_wedzona_lodzkie),max(kielbasa_wedzona_malopolskie),
max(kielbasa_wedzona_mazowieckie),max(kielbasa_wedzona_opolskie),max(kielbasa_wedzona_podkarpackie),
max(kielbasa_wedzona_podlaskie),max(kielbasa_wedzona_pomorskie),max(kielbasa_wedzona_slaskie),
max(kielbasa_wedzona_swietokrzyskie),max(kielbasa_wedzona_warminsko_mazurskie),
max(kielbasa_wedzona_wielkopolskie),max(kielbasa_wedzona_zachodniopomorskie))
### Najwyższe i najniższe, różne
kielbasa_sr_cena = mean(sr_cena_kielbasa) #Średnia cena kiełbasy dla całego kraju
kielbasa_odsd_cena = sd(sr_cena_kielbasa) #Odchylenie standardowe ceny kiełbasy
kielbasa_najw_sr = max(sr_cena_kielbasa) #Najwyższa średnia cena kiełbasy
kielbasa_najm_sr = min(sr_cena_kielbasa) #Najniższa średnia cena kiełbasy
kielbasa_najmn_k = min(kielbasa_najmn_w_kazdym_woj) #Najniższa cena kiełbasy kiedykolwiek
kielbasa_najw_k = max(kielbasa_najw_w_kazdym_woj) #Najwyższa cena kiełbasy kiedykolwiek
kiel_najw_sr = as.numeric(match(kielbasa_najw_sr,sr_cena_kielbasa)) #Numer województwa
kiel_najmn_sr = as.numeric(match(kielbasa_najm_sr,sr_cena_kielbasa)) #Numer województwa
print(paste("Najwyższa średnia cena kiełbasy jest w województwie", wojewodztwa[kiel_najw_sr],
"i wynosi",kielbasa_najw_sr))
print(paste("Najniższa średnia cena kiełbasy jest w województwie", wojewodztwa[kiel_najmn_sr],
"i wynosi",kielbasa_najm_sr))
kiel_najmn_kazde = as.numeric(match(kielbasa_najmn_k, kielbasa_najmn_w_kazdym_woj)) #Numer województwa
kiel_najw_kazde = as.numeric(match(kielbasa_najw_k, kielbasa_najw_w_kazdym_woj)) #Numer województwa
kiel_najmn_kiedy = match(kielbasa_najmn_k, kielbasa_wedzona_wielkopolskie) #Kiedy
kiel_najw_kiedy = match(kielbasa_najw_k, kielbasa_wedzona_zachodniopomorskie) #Kiedy
print(paste("Najniższa cena kiełbasy była w", daty[kiel_najmn_kiedy], "w województwie",
wojewodztwa[kiel_najmn_kazde],"i wynosiła", kielbasa_najmn_k, "zł"))
print(paste("Najwyższa cena kiełbasy była w", daty[kiel_najw_kiedy], "w województwie",
wojewodztwa[kiel_najw_kazde],"i wynosiła", kielbasa_najw_k, "zł"))
print(paste("Odchylenie standardowe cen kiełbasy wynosi", round(kielbasa_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny kiełbasy wędzonej ####
kielbasa_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_kielbasa$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_kielbasa$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_kielbasa$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_kielbasa$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_kielbasa$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_kielbasa$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_kielbasa$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_kielbasa$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_kielbasa$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_kielbasa$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_kielbasa$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_kielbasa$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_kielbasa$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny kielbasy wynosi", round(mean(kielbasa_placa_min_kor),
digits = 4), "co wskazuje na bardzo silną korelację"))
#### Korelacja średniej pensji do średniej ceny kiełbasy wędzonej ####
kielbasa_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_kielbasa$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_kielbasa$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_kielbasa$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_kielbasa$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_kielbasa$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_kielbasa$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_kielbasa$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_kielbasa$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_kielbasa$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_kielbasa$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_kielbasa$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_kielbasa$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_kielbasa$V13))),
cor(WARMI, as.numeric(as.character(roczne_sr_kielbasa$V14))),
cor(WIELK, as.numeric(as.character(roczne_sr_kielbasa$V15))),
cor(ZACHO, as.numeric(as.character(roczne_sr_kielbasa$V16))))
sr_kielbasa_kor = mean(kielbasa_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny kielbasy wynosi", round(sr_kielbasa_kor,
digits = 4), "co wskazuje na bardzo silną korelację"))
print(".........................................................")
#### Śmietana edycja nagłówków i tabel ####
smietana_df = smietana_df %>% remove_empty("cols") # Usuwam puste kolumny
smietana_df = subset(smietana_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(smietana_df) <- gsub("styczeń.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "styczeń.", names(smietana_df))
names(smietana_df) <- gsub("luty.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "luty.", names(smietana_df))
names(smietana_df) <- gsub("marzec.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "marzec.", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "kwiecień.", names(smietana_df))
names(smietana_df) <- gsub("maj.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "maj.", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "czerwiec.", names(smietana_df))
names(smietana_df) <- gsub("lipiec.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "lipiec.", names(smietana_df))
names(smietana_df) <- gsub("sierpień.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "sierpień.", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "wrzesień.", names(smietana_df))
names(smietana_df) <- gsub("październik.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "październik.", names(smietana_df))
names(smietana_df) <- gsub("listopad.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "listopad.", names(smietana_df))
names(smietana_df) <- gsub("grudzień.śmietana.o.zawartości.tłuszczu.18....za.200.g.cena.", "grudzień.", names(smietana_df))
names(smietana_df) <- gsub("..zł.", "", names(smietana_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(smietana_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(smietana_df))
names(smietana_df) <- gsub("luty.2006", "2006 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2007", "2007 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2008", "2008 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2009", "2009 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2010", "2010 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2011", "2011 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2012", "2012 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2013", "2013 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2014", "2014 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2015", "2015 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2016", "2016 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2017", "2017 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2018", "2018 2 luty", names(smietana_df))
names(smietana_df) <- gsub("luty.2019", "2019 2 luty", names(smietana_df))
names(smietana_df) <- gsub("marzec.2006", "2006 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2007", "2007 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2008", "2008 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2009", "2009 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2010", "2010 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2011", "2011 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2012", "2012 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2013", "2013 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2014", "2014 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2015", "2015 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2016", "2016 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2017", "2017 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2018", "2018 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("marzec.2019", "2019 3 marzec", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(smietana_df))
names(smietana_df) <- gsub("maj.2006", "2006 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2007", "2007 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2008", "2008 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2009", "2009 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2010", "2010 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2011", "2011 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2012", "2012 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2013", "2013 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2014", "2014 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2015", "2015 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2016", "2016 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2017", "2017 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2018", "2018 5 maj", names(smietana_df))
names(smietana_df) <- gsub("maj.2019", "2019 5 maj", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(smietana_df))
names(smietana_df) <- gsub("październik.2006", "2006 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2007", "2007 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2008", "2008 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2009", "2009 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2010", "2010 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2011", "2011 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2012", "2012 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2013", "2013 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2014", "2014 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2015", "2015 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2016", "2016 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2017", "2017 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2018", "2018 90 październik", names(smietana_df))
names(smietana_df) <- gsub("październik.2019", "2019 90 październik", names(smietana_df))
names(smietana_df) <- gsub("listopad.2006", "2006 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2007", "2007 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2008", "2008 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2009", "2009 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2010", "2010 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2011", "2011 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2012", "2012 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2013", "2013 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2014", "2014 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2015", "2015 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2016", "2016 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2017", "2017 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2018", "2018 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("listopad.2019", "2019 91 listopad", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(smietana_df))
names(smietana_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(smietana_df))
smietana_df = smietana_df[sort(colnames(smietana_df))] #Sortuję chronologicznie
#smietana_df = subset(smietana_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
smietana_df = t(smietana_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
smietana_df = unname(smietana_df) #Usuwam zbędne teraz nazwy
smietana_df = as.data.frame(smietana_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
smietana_dolnoslaskie = as.numeric(gsub(",", ".", as.character(smietana_df$V1)))
smietana_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(smietana_df$V2)))
smietana_lubelskie = as.numeric(gsub(",", ".", as.character(smietana_df$V3)))
smietana_lubuskie = as.numeric(gsub(",", ".", as.character(smietana_df$V4)))
smietana_lodzkie = as.numeric(gsub(",", ".", as.character(smietana_df$V5)))
smietana_malopolskie = as.numeric(gsub(",", ".", as.character(smietana_df$V6)))
smietana_mazowieckie = as.numeric(gsub(",", ".", as.character(smietana_df$V7)))
smietana_opolskie = as.numeric(gsub(",", ".", as.character(smietana_df$V8)))
smietana_podkarpackie = as.numeric(gsub(",", ".", as.character(smietana_df$V9)))
smietana_podlaskie = as.numeric(gsub(",", ".", as.character(smietana_df$V10)))
smietana_pomorskie = as.numeric(gsub(",", ".", as.character(smietana_df$V11)))
smietana_slaskie = as.numeric(gsub(",", ".", as.character(smietana_df$V12)))
smietana_swietokrzyskie = as.numeric(gsub(",", ".", as.character(smietana_df$V13)))
smietana_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(smietana_df$V14)))
smietana_wielkopolskie = as.numeric(gsub(",", ".", as.character(smietana_df$V15)))
smietana_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(smietana_df$V16)))
#### Wykres cen śmietany ####
u = (1:96)
#Wykres dla śmietany i wszystkich województw
smietana_plot = plot_ly(x = u )%>%
layout(title = 'Zmiana cen śmietany w latach 2012-2019', xaxis = list(title = 'Rok',
ticktext = list("2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = smietana_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = smietana_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = smietana_lubelskie, name = "lubelskie")%>%
add_lines(y = smietana_lubuskie, name = "lubuskie")%>%
add_lines(y = smietana_lodzkie, name = "łódzkie")%>%
add_lines(y = smietana_malopolskie, name = "małopolskie")%>%
add_lines(y = smietana_mazowieckie, name = "mazowieckie")%>%
add_lines(y = smietana_opolskie, name = "opolskie")%>%
add_lines(y = smietana_podkarpackie, name = "podkarpackie")%>%
add_lines(y = smietana_podlaskie, name = "podlaskie")%>%
add_lines(y = smietana_pomorskie, name = "pomorskie")%>%
add_lines(y = smietana_slaskie, name = "śląskie")%>%
add_lines(y = smietana_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = smietana_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = smietana_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = smietana_zachodniopomorskie, name = "zachodniopomorskie")
#print(kielbasa_plot)
#### Średnie roczne ceny śmietany ####
roczne_sr_smietana = data.frame('','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_smietana) = c("2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:8) {
roczne_sr_smietana[1,i] = round(mean(smietana_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[2,i] = round(mean(smietana_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[3,i] = round(mean(smietana_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[4,i] = round(mean(smietana_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[5,i] = round(mean(smietana_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[6,i] = round(mean(smietana_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[7,i] = round(mean(smietana_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[8,i] = round(mean(smietana_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[9,i] = round(mean(smietana_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[10,i] = round(mean(smietana_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[11,i] = round(mean(smietana_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[12,i] = round(mean(smietana_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[13,i] = round(mean(smietana_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[14,i] = round(mean(smietana_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[15,i] = round(mean(smietana_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_smietana[16,i] = round(mean(smietana_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_smietana = t(roczne_sr_smietana)
roczne_sr_smietana = unname(roczne_sr_smietana) #Usuwam zbędne teraz nazwy
roczne_sr_smietana = as.data.frame(roczne_sr_smietana) #Przekształcam na dataframe
#### Średnia cena śmietany dla każdego wojewódstwa ####
smietana_dolnoslaskie_sr = round(mean(smietana_dolnoslaskie), digits = 2) #1
smietana_kujawsko_pomorskie_sr = round(mean(smietana_kujawsko_pomorskie), digits = 2) #2
smietana_lubelskie_sr = round(mean(smietana_lubelskie), digits = 2) #3
smietana_lubuskie_sr = round(mean(smietana_lubuskie), digits = 2) #4
smietana_lodzkie_sr = round(mean(smietana_lodzkie), digits = 2) #5
smietana_malopolskie_sr = round(mean(smietana_malopolskie), digits = 2) #6
smietana_mazowieckie_sr = round(mean(smietana_mazowieckie), digits = 2) #7
smietana_opolskie_sr = round(mean(smietana_opolskie), digits = 2) #8
smietana_podkarpackie_sr = round(mean(smietana_podkarpackie), digits = 2) #9
smietana_podlaskie_sr = round(mean(smietana_podlaskie), digits = 2) #10
smietana_pomorskie_sr = round(mean(smietana_pomorskie), digits = 2) #11
smietana_slaskie_sr = round(mean(smietana_slaskie), digits = 2) #12
smietana_swietokrzyskie_sr = round(mean(smietana_swietokrzyskie), digits = 2) #13
smietana_warminsko_mazurskie_sr = round(mean(smietana_warminsko_mazurskie), digits = 2) #14
smietana_wielkopolskie_sr = round(mean(smietana_wielkopolskie), digits = 2) #15
smietana_zachodniopomorskie_sr = round(mean(smietana_zachodniopomorskie), digits = 2) #16
#### Śmietana średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_smietana = c(smietana_dolnoslaskie_sr,smietana_kujawsko_pomorskie_sr,smietana_lubelskie_sr,smietana_lubuskie_sr,smietana_lodzkie_sr,
smietana_malopolskie_sr,smietana_mazowieckie_sr,smietana_opolskie_sr,smietana_podkarpackie_sr,smietana_podlaskie_sr,
smietana_pomorskie_sr,smietana_slaskie_sr,smietana_swietokrzyskie_sr,smietana_warminsko_mazurskie_sr,
smietana_wielkopolskie_sr,smietana_zachodniopomorskie_sr)
smietana_najmn_w_kazdym_woj = c(min(smietana_dolnoslaskie),min(smietana_kujawsko_pomorskie),min(smietana_lubelskie),
min(smietana_lubuskie),min(smietana_lodzkie),min(smietana_malopolskie),
min(smietana_mazowieckie),min(smietana_opolskie),min(smietana_podkarpackie),
min(smietana_podlaskie),min(smietana_pomorskie),min(smietana_slaskie),
min(smietana_swietokrzyskie),min(smietana_warminsko_mazurskie),
min(smietana_wielkopolskie),min(smietana_zachodniopomorskie))
smietana_najw_w_kazdym_woj = c(max(smietana_dolnoslaskie),max(smietana_kujawsko_pomorskie),max(smietana_lubelskie),
max(smietana_lubuskie),max(smietana_lodzkie),max(smietana_malopolskie),
max(smietana_mazowieckie),max(smietana_opolskie),max(smietana_podkarpackie),
max(smietana_podlaskie),max(smietana_pomorskie),max(smietana_slaskie),
max(smietana_swietokrzyskie),max(smietana_warminsko_mazurskie),
max(smietana_wielkopolskie),max(smietana_zachodniopomorskie))
### Najwyższe i najniższe, różne
smietana_sr_cena = mean(sr_cena_smietana) #Średnia cena śmietany dla całego kraju
smietana_odsd_cena = sd(sr_cena_smietana) #Odchylenie standardowe ceny śmietany
smietana_najw_sr = max(sr_cena_smietana) #Najwyższa średnia cena śmietany
smietana_najm_sr = min(sr_cena_smietana) #Najniższa średnia cena śmietany
smietana_najmn_k = min(smietana_najmn_w_kazdym_woj) #Najniższa cena śmietany kiedykolwiek
smietana_najw_k = max(smietana_najw_w_kazdym_woj) #Najwyższa cena śmietany kiedykolwiek
smiet_najw_sr = as.numeric(match(smietana_najw_sr,sr_cena_smietana)) #Numer województwa
smiet_najmn_sr = as.numeric(match(smietana_najm_sr,sr_cena_smietana)) #Numer województwa
print(paste("Najwyższa średnia cena śmietany jest w województwie", wojewodztwa[smiet_najw_sr],
"i wynosi",smietana_najw_sr))
print(paste("Najniższa średnia cena śmietany jest w województwie", wojewodztwa[smiet_najmn_sr],
"i wynosi",smietana_najm_sr))
smietana_najmn_kazde = as.numeric(match(smietana_najmn_k, smietana_najmn_w_kazdym_woj)) #Numer województwa
smietana_najw_kazde = as.numeric(match(smietana_najw_k, smietana_najw_w_kazdym_woj)) #Numer województwa
smietana_najmn_kiedy = match(smietana_najmn_k, smietana_swietokrzyskie) #Kiedy
smietana_najw_kiedy = match(smietana_najw_k, smietana_dolnoslaskie) #Kiedy
print(paste("Najniższa cena śmietany była w", daty[73:168][smietana_najmn_kiedy], "w województwie",
wojewodztwa[smietana_najmn_kazde],"i wynosiła", smietana_najmn_k, "zł"))
print(paste("Najwyższa cena śmietany była w", daty[73:168][smietana_najw_kiedy], "w województwie",
wojewodztwa[smietana_najw_kazde],"i wynosiła", smietana_najw_k, "zł"))
print(paste("Odchylenie standardowe cen śmietany wynosi", round(smietana_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny śmietany ####
smietana_placa_min_kor = c(cor(as.numeric(as.character(placa_min2012_2019_df$V1)), as.numeric(as.character(roczne_sr_smietana$V1))),
cor(as.numeric(as.character(placa_min2012_2019_df$V2)), as.numeric(as.character(roczne_sr_smietana$V2))),
cor(as.numeric(as.character(placa_min2012_2019_df$V3)), as.numeric(as.character(roczne_sr_smietana$V3))),
cor(as.numeric(as.character(placa_min2012_2019_df$V4)), as.numeric(as.character(roczne_sr_smietana$V4))),
cor(as.numeric(as.character(placa_min2012_2019_df$V5)), as.numeric(as.character(roczne_sr_smietana$V5))),
cor(as.numeric(as.character(placa_min2012_2019_df$V6)), as.numeric(as.character(roczne_sr_smietana$V6))),
cor(as.numeric(as.character(placa_min2012_2019_df$V7)), as.numeric(as.character(roczne_sr_smietana$V7))),
cor(as.numeric(as.character(placa_min2012_2019_df$V8)), as.numeric(as.character(roczne_sr_smietana$V8))),
cor(as.numeric(as.character(placa_min2012_2019_df$V9)), as.numeric(as.character(roczne_sr_smietana$V9))),
cor(as.numeric(as.character(placa_min2012_2019_df$V10)), as.numeric(as.character(roczne_sr_smietana$V10))),
cor(as.numeric(as.character(placa_min2012_2019_df$V11)), as.numeric(as.character(roczne_sr_smietana$V11))),
cor(as.numeric(as.character(placa_min2012_2019_df$V12)), as.numeric(as.character(roczne_sr_smietana$V12))),
cor(as.numeric(as.character(placa_min2012_2019_df$V13)), as.numeric(as.character(roczne_sr_smietana$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny śmietany wynosi", round(mean(smietana_placa_min_kor),
digits = 4), "co wskazuje na umiarkowanie silnę korelację"))
#### Korelacja średniej pensji do średniej ceny śmietany ####
smietana_sr_pensja_kor = c(cor(DOLNO[6:13], as.numeric(as.character(roczne_sr_smietana$V1))),
cor(KUJAW[6:13], as.numeric(as.character(roczne_sr_smietana$V2))),
cor(LUBEL[6:13], as.numeric(as.character(roczne_sr_smietana$V3))),
cor(LUBUS[6:13], as.numeric(as.character(roczne_sr_smietana$V4))),
cor(LODZK[6:13], as.numeric(as.character(roczne_sr_smietana$V5))),
cor(MALOP[6:13], as.numeric(as.character(roczne_sr_smietana$V6))),
cor(MAZOW[6:13], as.numeric(as.character(roczne_sr_smietana$V7))),
cor(OPOLS[6:13], as.numeric(as.character(roczne_sr_smietana$V8))),
cor(PODKA[6:13], as.numeric(as.character(roczne_sr_smietana$V9))),
cor(PODLA[6:13], as.numeric(as.character(roczne_sr_smietana$V10))),
cor(POMOR[6:13], as.numeric(as.character(roczne_sr_smietana$V11))),
cor(SLASK[6:13], as.numeric(as.character(roczne_sr_smietana$V12))),
cor(SWIET[6:13], as.numeric(as.character(roczne_sr_smietana$V13))),
cor(WARMI[6:13], as.numeric(as.character(roczne_sr_smietana$V14))),
cor(WIELK[6:13], as.numeric(as.character(roczne_sr_smietana$V15))),
cor(ZACHO[6:13], as.numeric(as.character(roczne_sr_smietana$V16))))
sr_smietana_kor = mean(smietana_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny śmietany wynosi", round(sr_smietana_kor,
digits = 4), "co wskazuje na umiarkowanie silnę korelację"))
print(".........................................................")
#### Masło edycja nagłówków i tabel ####
maslo_df = maslo_df %>% remove_empty("cols") # Usuwam puste kolumny
maslo_df = subset(maslo_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(maslo_df) <- gsub("styczeń.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "styczeń.", names(maslo_df))
names(maslo_df) <- gsub("luty.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "luty.", names(maslo_df))
names(maslo_df) <- gsub("marzec.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "marzec.", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "kwiecień.", names(maslo_df))
names(maslo_df) <- gsub("maj.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "maj.", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "czerwiec.", names(maslo_df))
names(maslo_df) <- gsub("lipiec.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "lipiec.", names(maslo_df))
names(maslo_df) <- gsub("sierpień.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "sierpień.", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "wrzesień.", names(maslo_df))
names(maslo_df) <- gsub("październik.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "październik.", names(maslo_df))
names(maslo_df) <- gsub("listopad.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "listopad.", names(maslo_df))
names(maslo_df) <- gsub("grudzień.masło.świeże.o.zawartości.tłuszczu.ok..82.5....za.200.g.cena.", "grudzień.", names(maslo_df))
names(maslo_df) <- gsub("..zł.", "", names(maslo_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(maslo_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(maslo_df))
names(maslo_df) <- gsub("luty.2006", "2006 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2007", "2007 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2008", "2008 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2009", "2009 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2010", "2010 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2011", "2011 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2012", "2012 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2013", "2013 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2014", "2014 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2015", "2015 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2016", "2016 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2017", "2017 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2018", "2018 2 luty", names(maslo_df))
names(maslo_df) <- gsub("luty.2019", "2019 2 luty", names(maslo_df))
names(maslo_df) <- gsub("marzec.2006", "2006 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2007", "2007 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2008", "2008 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2009", "2009 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2010", "2010 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2011", "2011 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2012", "2012 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2013", "2013 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2014", "2014 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2015", "2015 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2016", "2016 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2017", "2017 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2018", "2018 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("marzec.2019", "2019 3 marzec", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(maslo_df))
names(maslo_df) <- gsub("maj.2006", "2006 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2007", "2007 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2008", "2008 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2009", "2009 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2010", "2010 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2011", "2011 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2012", "2012 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2013", "2013 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2014", "2014 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2015", "2015 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2016", "2016 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2017", "2017 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2018", "2018 5 maj", names(maslo_df))
names(maslo_df) <- gsub("maj.2019", "2019 5 maj", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(maslo_df))
names(maslo_df) <- gsub("październik.2006", "2006 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2007", "2007 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2008", "2008 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2009", "2009 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2010", "2010 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2011", "2011 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2012", "2012 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2013", "2013 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2014", "2014 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2015", "2015 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2016", "2016 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2017", "2017 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2018", "2018 90 październik", names(maslo_df))
names(maslo_df) <- gsub("październik.2019", "2019 90 październik", names(maslo_df))
names(maslo_df) <- gsub("listopad.2006", "2006 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2007", "2007 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2008", "2008 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2009", "2009 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2010", "2010 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2011", "2011 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2012", "2012 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2013", "2013 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2014", "2014 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2015", "2015 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2016", "2016 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2017", "2017 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2018", "2018 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("listopad.2019", "2019 91 listopad", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(maslo_df))
names(maslo_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(maslo_df))
maslo_df = maslo_df[sort(colnames(maslo_df))] #Sortuję chronologicznie
#maslo_df = subset(maslo_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
maslo_df = t(maslo_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
maslo_df = unname(maslo_df) #Usuwam zbędne teraz nazwy
maslo_df = as.data.frame(maslo_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
maslo_dolnoslaskie = as.numeric(gsub(",", ".", as.character(maslo_df$V1)))
maslo_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(maslo_df$V2)))
maslo_lubelskie = as.numeric(gsub(",", ".", as.character(maslo_df$V3)))
maslo_lubuskie = as.numeric(gsub(",", ".", as.character(maslo_df$V4)))
maslo_lodzkie = as.numeric(gsub(",", ".", as.character(maslo_df$V5)))
maslo_malopolskie = as.numeric(gsub(",", ".", as.character(maslo_df$V6)))
maslo_mazowieckie = as.numeric(gsub(",", ".", as.character(maslo_df$V7)))
maslo_opolskie = as.numeric(gsub(",", ".", as.character(maslo_df$V8)))
maslo_podkarpackie = as.numeric(gsub(",", ".", as.character(maslo_df$V9)))
maslo_podlaskie = as.numeric(gsub(",", ".", as.character(maslo_df$V10)))
maslo_pomorskie = as.numeric(gsub(",", ".", as.character(maslo_df$V11)))
maslo_slaskie = as.numeric(gsub(",", ".", as.character(maslo_df$V12)))
maslo_swietokrzyskie = as.numeric(gsub(",", ".", as.character(maslo_df$V13)))
maslo_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(maslo_df$V14)))
maslo_wielkopolskie = as.numeric(gsub(",", ".", as.character(maslo_df$V15)))
maslo_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(maslo_df$V16)))
#### Wykres cen masła ####
y = (1:168)
#Wykres dla masłą i wszystkich województw
maslo_plot = plot_ly(x = y )%>%
layout(title = '<NAME> w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = maslo_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = maslo_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = maslo_lubelskie, name = "lubelskie")%>%
add_lines(y = maslo_lubuskie, name = "lubuskie")%>%
add_lines(y = maslo_lodzkie, name = "łódzkie")%>%
add_lines(y = maslo_malopolskie, name = "małopolskie")%>%
add_lines(y = maslo_mazowieckie, name = "mazowieckie")%>%
add_lines(y = maslo_opolskie, name = "opolskie")%>%
add_lines(y = maslo_podkarpackie, name = "podkarpackie")%>%
add_lines(y = maslo_podlaskie, name = "podlaskie")%>%
add_lines(y = maslo_pomorskie, name = "pomorskie")%>%
add_lines(y = maslo_slaskie, name = "śląskie")%>%
add_lines(y = maslo_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = maslo_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = maslo_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = maslo_zachodniopomorskie, name = "zachodniopomorskie")
#print(kielbasa_plot)
#### Średnie roczne ceny masła ####
roczne_sr_maslo = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_maslo) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_maslo[1,i] = round(mean(maslo_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[2,i] = round(mean(maslo_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[3,i] = round(mean(maslo_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[4,i] = round(mean(maslo_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[5,i] = round(mean(maslo_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[6,i] = round(mean(maslo_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[7,i] = round(mean(maslo_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[8,i] = round(mean(maslo_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[9,i] = round(mean(maslo_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[10,i] = round(mean(maslo_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[11,i] = round(mean(maslo_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[12,i] = round(mean(maslo_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[13,i] = round(mean(maslo_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[14,i] = round(mean(maslo_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[15,i] = round(mean(maslo_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_maslo[16,i] = round(mean(maslo_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_maslo = t(roczne_sr_maslo)
roczne_sr_maslo = unname(roczne_sr_maslo) #Usuwam zbędne teraz nazwy
roczne_sr_maslo = as.data.frame(roczne_sr_maslo) #Przekształcam na dataframe
#### Średnia cena masła dla każdego wojewódstwa ####
maslo_dolnoslaskie_sr = round(mean(maslo_dolnoslaskie), digits = 2) #1
maslo_kujawsko_pomorskie_sr = round(mean(maslo_kujawsko_pomorskie), digits = 2) #2
maslo_lubelskie_sr = round(mean(maslo_lubelskie), digits = 2) #3
maslo_lubuskie_sr = round(mean(maslo_lubuskie), digits = 2) #4
maslo_lodzkie_sr = round(mean(maslo_lodzkie), digits = 2) #5
maslo_malopolskie_sr = round(mean(maslo_malopolskie), digits = 2) #6
maslo_mazowieckie_sr = round(mean(maslo_mazowieckie), digits = 2) #7
maslo_opolskie_sr = round(mean(maslo_opolskie), digits = 2) #8
maslo_podkarpackie_sr = round(mean(maslo_podkarpackie), digits = 2) #9
maslo_podlaskie_sr = round(mean(maslo_podlaskie), digits = 2) #10
maslo_pomorskie_sr = round(mean(maslo_pomorskie), digits = 2) #11
maslo_slaskie_sr = round(mean(maslo_slaskie), digits = 2) #12
maslo_swietokrzyskie_sr = round(mean(maslo_swietokrzyskie), digits = 2) #13
maslo_warminsko_mazurskie_sr = round(mean(maslo_warminsko_mazurskie), digits = 2) #14
maslo_wielkopolskie_sr = round(mean(maslo_wielkopolskie), digits = 2) #15
maslo_zachodniopomorskie_sr = round(mean(maslo_zachodniopomorskie), digits = 2) #16
#### Masło średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_maslo = c(maslo_dolnoslaskie_sr,maslo_kujawsko_pomorskie_sr,maslo_lubelskie_sr,maslo_lubuskie_sr,maslo_lodzkie_sr,
maslo_malopolskie_sr,maslo_mazowieckie_sr,maslo_opolskie_sr,maslo_podkarpackie_sr,maslo_podlaskie_sr,
maslo_pomorskie_sr,maslo_slaskie_sr,maslo_swietokrzyskie_sr,maslo_warminsko_mazurskie_sr,
maslo_wielkopolskie_sr,maslo_zachodniopomorskie_sr)
maslo_najmn_w_kazdym_woj = c(min(maslo_dolnoslaskie),min(maslo_kujawsko_pomorskie),min(maslo_lubelskie),
min(maslo_lubuskie),min(maslo_lodzkie),min(maslo_malopolskie),
min(maslo_mazowieckie),min(maslo_opolskie),min(maslo_podkarpackie),
min(maslo_podlaskie),min(maslo_pomorskie),min(maslo_slaskie),
min(maslo_swietokrzyskie),min(maslo_warminsko_mazurskie),
min(maslo_wielkopolskie),min(maslo_zachodniopomorskie))
maslo_najw_w_kazdym_woj = c(max(maslo_dolnoslaskie),max(maslo_kujawsko_pomorskie),max(maslo_lubelskie),
max(maslo_lubuskie),max(maslo_lodzkie),max(maslo_malopolskie),
max(maslo_mazowieckie),max(maslo_opolskie),max(maslo_podkarpackie),
max(maslo_podlaskie),max(maslo_pomorskie),max(maslo_slaskie),
max(maslo_swietokrzyskie),max(maslo_warminsko_mazurskie),
max(maslo_wielkopolskie),max(maslo_zachodniopomorskie))
### Najwyższe i najniższe, różne
maslo_sr_cena = mean(sr_cena_maslo) #Średnia cena masła dla całego kraju
maslo_odsd_cena = sd(sr_cena_maslo) #Odchylenie standardowe ceny masła
maslo_najw_sr = max(sr_cena_maslo) #Najwyższa średnia cena masła
maslo_najm_sr = min(sr_cena_maslo) #Najniższa średnia cena masła
maslo_najmn_k = min(maslo_najmn_w_kazdym_woj) #Najniższa cena masła kiedykolwiek
maslo_najw_k = max(maslo_najw_w_kazdym_woj) #Najwyższa cena masła kiedykolwiek
mas_najw_sr = as.numeric(match(maslo_najw_sr,sr_cena_maslo)) #Numer województwa
mas_najmn_sr = as.numeric(match(maslo_najm_sr,sr_cena_maslo)) #Numer województwa
print(paste("Najwyższa średnia cena masła jest w województwie", wojewodztwa[mas_najw_sr],
"i wynosi",maslo_najw_sr,"za 200g"))
print(paste("Najniższa średnia cena masła jest w województwie", wojewodztwa[mas_najmn_sr],
"i wynosi",maslo_najm_sr,"za 200g"))
maslo_najmn_kazde = as.numeric(match(maslo_najmn_k, maslo_najmn_w_kazdym_woj)) #Numer województwa
maslo_najw_kazde = as.numeric(match(maslo_najw_k, maslo_najw_w_kazdym_woj)) #Numer województwa
maslo_najmn_kiedy = match(maslo_najmn_k, maslo_opolskie) #Kiedy
maslo_najw_kiedy = match(maslo_najw_k, maslo_zachodniopomorskie) #Kiedy
print(paste("Najniższa cena masła była w", daty[maslo_najmn_kiedy], "w województwie",
wojewodztwa[maslo_najmn_kazde],"i wynosiła", maslo_najmn_k, "zł za 200g"))
print(paste("Najwyższa cena masła była w", daty[maslo_najw_kiedy], "w województwie",
wojewodztwa[maslo_najw_kazde],"i wynosiła", maslo_najw_k, "zł za 200g"))
print(paste("Odchylenie standardowe cen masła wynosi", round(maslo_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny masła ####
maslo_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_maslo$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_maslo$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_maslo$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_maslo$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_maslo$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_maslo$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_maslo$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_maslo$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_maslo$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_maslo$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_maslo$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_maslo$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_maslo$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny masła wynosi", round(mean(maslo_placa_min_kor),
digits = 4), "co wskazuje na silną korelację"))
#### Korelacja średniej pensji do średniej ceny masła ####
maslo_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_maslo$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_maslo$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_maslo$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_maslo$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_maslo$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_maslo$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_maslo$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_maslo$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_maslo$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_maslo$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_maslo$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_maslo$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_maslo$V13))),
cor(WARMI, as.numeric(as.character(roczne_sr_maslo$V14))),
cor(WIELK, as.numeric(as.character(roczne_sr_maslo$V15))),
cor(ZACHO, as.numeric(as.character(roczne_sr_maslo$V16))))
sr_maslo_kor = mean(maslo_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny masła wynosi", round(sr_maslo_kor,
digits = 4), "co wskazuje na silną korelację"))
print(".........................................................")
#### Czekolada edycja nagłówków i tabel ####
czekolada_df = czekolada_df %>% remove_empty("cols") # Usuwam puste kolumny
czekolada_df = subset(czekolada_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(czekolada_df) <- gsub("styczeń.czekolada.mleczna...za.100g.cena.", "styczeń.", names(czekolada_df))
names(czekolada_df) <- gsub("luty.czekolada.mleczna...za.100g.cena.", "luty.", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.czekolada.mleczna...za.100g.cena.", "marzec.", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.czekolada.mleczna...za.100g.cena.", "kwiecień.", names(czekolada_df))
names(czekolada_df) <- gsub("maj.czekolada.mleczna...za.100g.cena.", "maj.", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.czekolada.mleczna...za.100g.cena.", "czerwiec.", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.czekolada.mleczna...za.100g.cena.", "lipiec.", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.czekolada.mleczna...za.100g.cena.", "sierpień.", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.czekolada.mleczna...za.100g.cena.", "wrzesień.", names(czekolada_df))
names(czekolada_df) <- gsub("październik.czekolada.mleczna...za.100g.cena.", "październik.", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.czekolada.mleczna...za.100g.cena.", "listopad.", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.czekolada.mleczna...za.100g.cena.", "grudzień.", names(czekolada_df))
names(czekolada_df) <- gsub("..zł.", "", names(czekolada_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(czekolada_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2006", "2006 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2007", "2007 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2008", "2008 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2009", "2009 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2010", "2010 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2011", "2011 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2012", "2012 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2013", "2013 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2014", "2014 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2015", "2015 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2016", "2016 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2017", "2017 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2018", "2018 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("luty.2019", "2019 2 luty", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2006", "2006 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2007", "2007 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2008", "2008 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2009", "2009 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2010", "2010 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2011", "2011 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2012", "2012 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2013", "2013 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2014", "2014 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2015", "2015 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2016", "2016 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2017", "2017 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2018", "2018 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("marzec.2019", "2019 3 marzec", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2006", "2006 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2007", "2007 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2008", "2008 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2009", "2009 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2010", "2010 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2011", "2011 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2012", "2012 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2013", "2013 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2014", "2014 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2015", "2015 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2016", "2016 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2017", "2017 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2018", "2018 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("maj.2019", "2019 5 maj", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2006", "2006 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2007", "2007 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2008", "2008 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2009", "2009 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2010", "2010 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2011", "2011 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2012", "2012 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2013", "2013 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2014", "2014 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2015", "2015 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2016", "2016 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2017", "2017 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2018", "2018 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("październik.2019", "2019 90 październik", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2006", "2006 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2007", "2007 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2008", "2008 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2009", "2009 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2010", "2010 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2011", "2011 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2012", "2012 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2013", "2013 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2014", "2014 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2015", "2015 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2016", "2016 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2017", "2017 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2018", "2018 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("listopad.2019", "2019 91 listopad", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(czekolada_df))
names(czekolada_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(czekolada_df))
czekolada_df = czekolada_df[sort(colnames(czekolada_df))] #Sortuję chronologicznie
#czekolada_df = subset(czekolada_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
czekolada_df = t(czekolada_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
czekolada_df = unname(czekolada_df) #Usuwam zbędne teraz nazwy
czekolada_df = as.data.frame(czekolada_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
czekolada_dolnoslaskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V1)))
czekolada_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V2)))
czekolada_lubelskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V3)))
czekolada_lubuskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V4)))
czekolada_lodzkie = as.numeric(gsub(",", ".", as.character(czekolada_df$V5)))
czekolada_malopolskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V6)))
czekolada_mazowieckie = as.numeric(gsub(",", ".", as.character(czekolada_df$V7)))
czekolada_opolskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V8)))
czekolada_podkarpackie = as.numeric(gsub(",", ".", as.character(czekolada_df$V9)))
czekolada_podlaskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V10)))
czekolada_pomorskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V11)))
czekolada_slaskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V12)))
czekolada_swietokrzyskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V13)))
czekolada_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V14)))
czekolada_wielkopolskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V15)))
czekolada_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(czekolada_df$V16)))
#### Wykres cen czekolady ####
y = (1:168)
#Wykres dla czekolady i wszystkich województw
czekolada_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen czekolady w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = czekolada_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = czekolada_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = czekolada_lubelskie, name = "lubelskie")%>%
add_lines(y = czekolada_lubuskie, name = "lubuskie")%>%
add_lines(y = czekolada_lodzkie, name = "łódzkie")%>%
add_lines(y = czekolada_malopolskie, name = "małopolskie")%>%
add_lines(y = czekolada_mazowieckie, name = "mazowieckie")%>%
add_lines(y = czekolada_opolskie, name = "opolskie")%>%
add_lines(y = czekolada_podkarpackie, name = "podkarpackie")%>%
add_lines(y = czekolada_podlaskie, name = "podlaskie")%>%
add_lines(y = czekolada_pomorskie, name = "pomorskie")%>%
add_lines(y = czekolada_slaskie, name = "śląskie")%>%
add_lines(y = czekolada_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = czekolada_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = czekolada_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = czekolada_zachodniopomorskie, name = "zachodniopomorskie")
#print(kielbasa_plot)
#### Średnie roczne ceny czekolady ####
roczne_sr_czekolada = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_czekolada) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_czekolada[1,i] = round(mean(czekolada_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[2,i] = round(mean(czekolada_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[3,i] = round(mean(czekolada_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[4,i] = round(mean(czekolada_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[5,i] = round(mean(czekolada_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[6,i] = round(mean(czekolada_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[7,i] = round(mean(czekolada_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[8,i] = round(mean(czekolada_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[9,i] = round(mean(czekolada_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[10,i] = round(mean(czekolada_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[11,i] = round(mean(czekolada_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[12,i] = round(mean(czekolada_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[13,i] = round(mean(czekolada_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[14,i] = round(mean(czekolada_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[15,i] = round(mean(czekolada_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_czekolada[16,i] = round(mean(czekolada_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_czekolada = t(roczne_sr_czekolada)
roczne_sr_czekolada = unname(roczne_sr_czekolada) #Usuwam zbędne teraz nazwy
roczne_sr_czekolada = as.data.frame(roczne_sr_czekolada) #Przekształcam na dataframe
#### Średnia cena czekolady dla każdego wojewódstwa ####
czekolada_dolnoslaskie_sr = round(mean(czekolada_dolnoslaskie), digits = 2) #1
czekolada_kujawsko_pomorskie_sr = round(mean(czekolada_kujawsko_pomorskie), digits = 2) #2
czekolada_lubelskie_sr = round(mean(czekolada_lubelskie), digits = 2) #3
czekolada_lubuskie_sr = round(mean(czekolada_lubuskie), digits = 2) #4
czekolada_lodzkie_sr = round(mean(czekolada_lodzkie), digits = 2) #5
czekolada_malopolskie_sr = round(mean(czekolada_malopolskie), digits = 2) #6
czekolada_mazowieckie_sr = round(mean(czekolada_mazowieckie), digits = 2) #7
czekolada_opolskie_sr = round(mean(czekolada_opolskie), digits = 2) #8
czekolada_podkarpackie_sr = round(mean(czekolada_podkarpackie), digits = 2) #9
czekolada_podlaskie_sr = round(mean(czekolada_podlaskie), digits = 2) #10
czekolada_pomorskie_sr = round(mean(czekolada_pomorskie), digits = 2) #11
czekolada_slaskie_sr = round(mean(czekolada_slaskie), digits = 2) #12
czekolada_swietokrzyskie_sr = round(mean(czekolada_swietokrzyskie), digits = 2) #13
czekolada_warminsko_mazurskie_sr = round(mean(czekolada_warminsko_mazurskie), digits = 2) #14
czekolada_wielkopolskie_sr = round(mean(czekolada_wielkopolskie), digits = 2) #15
czekolada_zachodniopomorskie_sr = round(mean(czekolada_zachodniopomorskie), digits = 2) #16
#### Czekolada średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_czekolada = c(czekolada_dolnoslaskie_sr,czekolada_kujawsko_pomorskie_sr,czekolada_lubelskie_sr,czekolada_lubuskie_sr,czekolada_lodzkie_sr,
czekolada_malopolskie_sr,czekolada_mazowieckie_sr,czekolada_opolskie_sr,czekolada_podkarpackie_sr,czekolada_podlaskie_sr,
czekolada_pomorskie_sr,czekolada_slaskie_sr,czekolada_swietokrzyskie_sr,czekolada_warminsko_mazurskie_sr,
czekolada_wielkopolskie_sr,czekolada_zachodniopomorskie_sr)
czekolada_najmn_w_kazdym_woj = c(min(czekolada_dolnoslaskie),min(czekolada_kujawsko_pomorskie),min(czekolada_lubelskie),
min(czekolada_lubuskie),min(czekolada_lodzkie),min(czekolada_malopolskie),
min(czekolada_mazowieckie),min(czekolada_opolskie),min(czekolada_podkarpackie),
min(czekolada_podlaskie),min(czekolada_pomorskie),min(czekolada_slaskie),
min(czekolada_swietokrzyskie),min(czekolada_warminsko_mazurskie),
min(czekolada_wielkopolskie),min(czekolada_zachodniopomorskie))
czekolada_najw_w_kazdym_woj = c(max(czekolada_dolnoslaskie),max(czekolada_kujawsko_pomorskie),max(czekolada_lubelskie),
max(czekolada_lubuskie),max(czekolada_lodzkie),max(czekolada_malopolskie),
max(czekolada_mazowieckie),max(czekolada_opolskie),max(czekolada_podkarpackie),
max(czekolada_podlaskie),max(czekolada_pomorskie),max(czekolada_slaskie),
max(czekolada_swietokrzyskie),max(czekolada_warminsko_mazurskie),
max(czekolada_wielkopolskie),max(czekolada_zachodniopomorskie))
### Najwyższe i najniższe, różne
czekolada_sr_cena = mean(sr_cena_czekolada) #Średnia cena czekolady dla całego kraju
czekolada_odsd_cena = sd(sr_cena_czekolada) #Odchylenie standardowe ceny czekolady
czekolada_najw_sr = max(sr_cena_czekolada) #Najwyższa średnia cena czekolady
czekolada_najm_sr = min(sr_cena_czekolada) #Najniższa średnia cena czekolady
czekolada_najmn_k = min(czekolada_najmn_w_kazdym_woj) #Najniższa cena czekolady kiedykolwiek
czekolada_najw_k = max(czekolada_najw_w_kazdym_woj) #Najwyższa cena czekolady kiedykolwiek
czek_najw_sr = as.numeric(match(czekolada_najw_sr,sr_cena_czekolada)) #Numer województwa
czek_najmn_sr = as.numeric(match(czekolada_najm_sr,sr_cena_czekolada)) #Numer województwa
print(paste("Najwyższa średnia cena czekolady jest w województwie", wojewodztwa[czek_najw_sr],
"i wynosi",czekolada_najw_sr,"za"))
print(paste("Najniższa średnia cena czekolady jest w województwie", wojewodztwa[czek_najmn_sr],
"i wynosi",czekolada_najm_sr,"za"))
czekolada_najmn_kazde = as.numeric(match(czekolada_najmn_k, czekolada_najmn_w_kazdym_woj)) #Numer województwa
czekolada_najw_kazde = as.numeric(match(czekolada_najw_k, czekolada_najw_w_kazdym_woj)) #Numer województwa
czekolada_najmn_kiedy = match(czekolada_najmn_k, czekolada_slaskie) #Kiedy
czekolada_najw_kiedy = match(czekolada_najw_k, czekolada_podkarpackie) #Kiedy
print(paste("Najniższa cena czekolady była w", daty[czekolada_najmn_kiedy], "w województwie",
wojewodztwa[czekolada_najmn_kazde],"i wynosiła", czekolada_najmn_k, "zł"))
print(paste("Najwyższa cena czekolady była w", daty[czekolada_najw_kiedy], "w województwie",
wojewodztwa[czekolada_najw_kazde],"i wynosiła", czekolada_najw_k, "zł"))
print(paste("Odchylenie standardowe cen czekolady wynosi", round(czekolada_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny czekolady ####
czekolada_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_czekolada$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_czekolada$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_czekolada$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_czekolada$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_czekolada$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_czekolada$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_czekolada$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_czekolada$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_czekolada$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_czekolada$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_czekolada$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_czekolada$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_czekolada$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny czekolady wynosi", round(mean(czekolada_placa_min_kor),
digits = 4), "co wskazuje na bardzo silną korelację"))
#### Korelacja średniej pensji do średniej ceny czekolady ####
czekolada_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_czekolada$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_czekolada$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_czekolada$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_czekolada$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_czekolada$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_czekolada$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_czekolada$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_czekolada$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_czekolada$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_czekolada$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_czekolada$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_czekolada$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_czekolada$V12))),
cor(WARMI, as.numeric(as.character(roczne_sr_czekolada$V12))),
cor(WIELK, as.numeric(as.character(roczne_sr_czekolada$V12))),
cor(ZACHO, as.numeric(as.character(roczne_sr_czekolada$V13))))
sr_czekolada_kor = mean(czekolada_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny czekolady wynosi", round(sr_czekolada_kor,
digits = 4), "co wskazuje na bardzo silną korelację"))
print(".........................................................")
#### Spodnie edycja nagłówków i tabel ####
spodnie_df = spodnie_df %>% remove_empty("cols") # Usuwam puste kolumny
spodnie_df2 = spodnie_df2 %>% remove_empty("cols") # Usuwam puste kolumny
spodnie_df = full_join(spodnie_df, spodnie_df2)
rm(spodnie_df2)
spodnie_df = subset(spodnie_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(spodnie_df) <- gsub("styczeń.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "styczeń.", names(spodnie_df))
names(spodnie_df) <- gsub("luty.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "luty.", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "marzec.", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "kwiecień.", names(spodnie_df))
names(spodnie_df) <- gsub("maj.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "maj.", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "czerwiec.", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "lipiec.", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "sierpień.", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "wrzesień.", names(spodnie_df))
names(spodnie_df) <- gsub("październik.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "październik.", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "listopad.", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.spodnie..6.11.lat..z.tkaniny.typu.jeans..2..cena.", "grudzień.", names(spodnie_df))
names(spodnie_df) <- gsub("..zł.", "", names(spodnie_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(spodnie_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2006", "2006 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2007", "2007 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2008", "2008 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2009", "2009 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2010", "2010 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2011", "2011 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2012", "2012 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2013", "2013 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2014", "2014 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2015", "2015 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2016", "2016 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2017", "2017 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2018", "2018 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("luty.2019", "2019 2 luty", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2006", "2006 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2007", "2007 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2008", "2008 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2009", "2009 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2010", "2010 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2011", "2011 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2012", "2012 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2013", "2013 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2014", "2014 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2015", "2015 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2016", "2016 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2017", "2017 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2018", "2018 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("marzec.2019", "2019 3 marzec", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2006", "2006 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2007", "2007 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2008", "2008 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2009", "2009 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2010", "2010 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2011", "2011 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2012", "2012 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2013", "2013 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2014", "2014 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2015", "2015 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2016", "2016 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2017", "2017 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2018", "2018 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("maj.2019", "2019 5 maj", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2006", "2006 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2007", "2007 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2008", "2008 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2009", "2009 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2010", "2010 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2011", "2011 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2012", "2012 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2013", "2013 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2014", "2014 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2015", "2015 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2016", "2016 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2017", "2017 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2018", "2018 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("październik.2019", "2019 90 październik", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2006", "2006 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2007", "2007 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2008", "2008 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2009", "2009 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2010", "2010 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2011", "2011 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2012", "2012 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2013", "2013 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2014", "2014 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2015", "2015 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2016", "2016 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2017", "2017 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2018", "2018 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("listopad.2019", "2019 91 listopad", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(spodnie_df))
names(spodnie_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(spodnie_df))
spodnie_df = spodnie_df[sort(colnames(spodnie_df))] #Sortuję chronologicznie
#spodnie_df = subset(spodnie_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
spodnie_df = t(spodnie_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
spodnie_df = unname(spodnie_df) #Usuwam zbędne teraz nazwy
spodnie_df = as.data.frame(spodnie_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
spodnie_dolnoslaskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V1)))
spodnie_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V2)))
spodnie_lubelskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V3)))
spodnie_lubuskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V4)))
spodnie_lodzkie = as.numeric(gsub(",", ".", as.character(spodnie_df$V5)))
spodnie_malopolskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V6)))
spodnie_mazowieckie = as.numeric(gsub(",", ".", as.character(spodnie_df$V7)))
spodnie_opolskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V8)))
spodnie_podkarpackie = as.numeric(gsub(",", ".", as.character(spodnie_df$V9)))
spodnie_podlaskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V10)))
spodnie_pomorskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V11)))
spodnie_slaskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V12)))
spodnie_swietokrzyskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V13)))
spodnie_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V14)))
spodnie_wielkopolskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V15)))
spodnie_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(spodnie_df$V16)))
#### Wykres cen spodni ####
y = (1:168)
#Wykres dla spodni i wszystkich województw
spodnie_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen spodni(6-11 lat) z tkaniny jeans w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = spodnie_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = spodnie_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = spodnie_lubelskie, name = "lubelskie")%>%
add_lines(y = spodnie_lubuskie, name = "lubuskie")%>%
add_lines(y = spodnie_lodzkie, name = "łódzkie")%>%
add_lines(y = spodnie_malopolskie, name = "małopolskie")%>%
add_lines(y = spodnie_mazowieckie, name = "mazowieckie")%>%
add_lines(y = spodnie_opolskie, name = "opolskie")%>%
add_lines(y = spodnie_podkarpackie, name = "podkarpackie")%>%
add_lines(y = spodnie_podlaskie, name = "podlaskie")%>%
add_lines(y = spodnie_pomorskie, name = "pomorskie")%>%
add_lines(y = spodnie_slaskie, name = "śląskie")%>%
add_lines(y = spodnie_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = spodnie_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = spodnie_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = spodnie_zachodniopomorskie, name = "zachodniopomorskie")
#print(spodnie_plot)
#### Średnie roczne ceny spodni ####
roczne_sr_spodnie = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_spodnie) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_spodnie[1,i] = round(mean(spodnie_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[2,i] = round(mean(spodnie_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[3,i] = round(mean(spodnie_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[4,i] = round(mean(spodnie_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[5,i] = round(mean(spodnie_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[6,i] = round(mean(spodnie_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[7,i] = round(mean(spodnie_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[8,i] = round(mean(spodnie_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[9,i] = round(mean(spodnie_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[10,i] = round(mean(spodnie_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[11,i] = round(mean(spodnie_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[12,i] = round(mean(spodnie_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[13,i] = round(mean(spodnie_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[14,i] = round(mean(spodnie_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[15,i] = round(mean(spodnie_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_spodnie[16,i] = round(mean(spodnie_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_spodnie = t(roczne_sr_spodnie)
roczne_sr_spodnie = unname(roczne_sr_spodnie) #Usuwam zbędne teraz nazwy
roczne_sr_spodnie = as.data.frame(roczne_sr_spodnie) #Przekształcam na dataframe
#### Średnia cena spodni dla każdego wojewódstwa ####
spodnie_dolnoslaskie_sr = round(mean(spodnie_dolnoslaskie), digits = 2) #1
spodnie_kujawsko_pomorskie_sr = round(mean(spodnie_kujawsko_pomorskie), digits = 2) #2
spodnie_lubelskie_sr = round(mean(spodnie_lubelskie), digits = 2) #3
spodnie_lubuskie_sr = round(mean(spodnie_lubuskie), digits = 2) #4
spodnie_lodzkie_sr = round(mean(spodnie_lodzkie), digits = 2) #5
spodnie_malopolskie_sr = round(mean(spodnie_malopolskie), digits = 2) #6
spodnie_mazowieckie_sr = round(mean(spodnie_mazowieckie), digits = 2) #7
spodnie_opolskie_sr = round(mean(spodnie_opolskie), digits = 2) #8
spodnie_podkarpackie_sr = round(mean(spodnie_podkarpackie), digits = 2) #9
spodnie_podlaskie_sr = round(mean(spodnie_podlaskie), digits = 2) #10
spodnie_pomorskie_sr = round(mean(spodnie_pomorskie), digits = 2) #11
spodnie_slaskie_sr = round(mean(spodnie_slaskie), digits = 2) #12
spodnie_swietokrzyskie_sr = round(mean(spodnie_swietokrzyskie), digits = 2) #13
spodnie_warminsko_mazurskie_sr = round(mean(spodnie_warminsko_mazurskie), digits = 2) #14
spodnie_wielkopolskie_sr = round(mean(spodnie_wielkopolskie), digits = 2) #15
spodnie_zachodniopomorskie_sr = round(mean(spodnie_zachodniopomorskie), digits = 2) #16
#### spodnie średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_spodnie = c(spodnie_dolnoslaskie_sr,spodnie_kujawsko_pomorskie_sr,spodnie_lubelskie_sr,spodnie_lubuskie_sr,spodnie_lodzkie_sr,
spodnie_malopolskie_sr,spodnie_mazowieckie_sr,spodnie_opolskie_sr,spodnie_podkarpackie_sr,spodnie_podlaskie_sr,
spodnie_pomorskie_sr,spodnie_slaskie_sr,spodnie_swietokrzyskie_sr,spodnie_warminsko_mazurskie_sr,
spodnie_wielkopolskie_sr,spodnie_zachodniopomorskie_sr)
spodnie_najmn_w_kazdym_woj = c(min(spodnie_dolnoslaskie),min(spodnie_kujawsko_pomorskie),min(spodnie_lubelskie),
min(spodnie_lubuskie),min(spodnie_lodzkie),min(spodnie_malopolskie),
min(spodnie_mazowieckie),min(spodnie_opolskie),min(spodnie_podkarpackie),
min(spodnie_podlaskie),min(spodnie_pomorskie),min(spodnie_slaskie),
min(spodnie_swietokrzyskie),min(spodnie_warminsko_mazurskie),
min(spodnie_wielkopolskie),min(spodnie_zachodniopomorskie))
spodnie_najw_w_kazdym_woj = c(max(spodnie_dolnoslaskie),max(spodnie_kujawsko_pomorskie),max(spodnie_lubelskie),
max(spodnie_lubuskie),max(spodnie_lodzkie),max(spodnie_malopolskie),
max(spodnie_mazowieckie),max(spodnie_opolskie),max(spodnie_podkarpackie),
max(spodnie_podlaskie),max(spodnie_pomorskie),max(spodnie_slaskie),
max(spodnie_swietokrzyskie),max(spodnie_warminsko_mazurskie),
max(spodnie_wielkopolskie),max(spodnie_zachodniopomorskie))
### Najwyższe i najniższe, różne
spodnie_sr_cena = mean(sr_cena_spodnie) #Średnia cena spodni dla całego kraju
spodnie_odsd_cena = sd(sr_cena_spodnie) #Odchylenie standardowe ceny spodni
spodnie_najw_sr = max(sr_cena_spodnie) #Najwyższa średnia cena spodni
spodnie_najm_sr = min(sr_cena_spodnie) #Najniższa średnia cena spodni
spodnie_najmn_k = min(spodnie_najmn_w_kazdym_woj) #Najniższa cena spodni kiedykolwiek
spodnie_najw_k = max(spodnie_najw_w_kazdym_woj) #Najwyższa cena spodni kiedykolwiek
spod_najw_sr = as.numeric(match(spodnie_najw_sr,sr_cena_spodnie)) #Numer województwa
spod_najmn_sr = as.numeric(match(spodnie_najm_sr,sr_cena_spodnie)) #Numer województwa
print(paste("Najwyższa średnia cena spodni jest w województwie", wojewodztwa[spod_najw_sr],
"i wynosi",spodnie_najw_sr))
print(paste("Najniższa średnia cena spodni jest w województwie", wojewodztwa[spod_najmn_sr],
"i wynosi",spodnie_najm_sr))
spodnie_najmn_kazde = as.numeric(match(spodnie_najmn_k, spodnie_najmn_w_kazdym_woj)) #Numer województwa
spodnie_najw_kazde = as.numeric(match(spodnie_najw_k, spodnie_najw_w_kazdym_woj)) #Numer województwa
spodnie_najmn_kiedy = match(spodnie_najmn_k, spodnie_zachodniopomorskie) #Kiedy
spodnie_najw_kiedy = match(spodnie_najw_k, spodnie_swietokrzyskie) #Kiedy
print(paste("Najniższa cena spodni była w", daty[spodnie_najmn_kiedy], "w województwie",
wojewodztwa[spodnie_najmn_kazde],"i wynosiła", spodnie_najmn_k))
print(paste("Najwyższa cena spodni była w", daty[spodnie_najw_kiedy], "w województwie",
wojewodztwa[spodnie_najw_kazde],"i wynosiła", spodnie_najw_k))
print(paste("Odchylenie standardowe cen spodni wynosi", round(spodnie_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny spodni ####
spodnie_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_spodnie$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_spodnie$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_spodnie$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_spodnie$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_spodnie$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_spodnie$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_spodnie$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_spodnie$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_spodnie$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_spodnie$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_spodnie$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_spodnie$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_spodnie$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny spodni wynosi", round(mean(spodnie_placa_min_kor),
digits = 4), "co wskazuje na brak korelacji"))
#### Korelacja średniej pensji do średniej ceny spodni ####
spodnie_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_spodnie$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_spodnie$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_spodnie$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_spodnie$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_spodnie$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_spodnie$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_spodnie$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_spodnie$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_spodnie$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_spodnie$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_spodnie$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_spodnie$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_spodnie$V13))),
cor(WARMI, as.numeric(as.character(roczne_sr_spodnie$V14))),
cor(WIELK, as.numeric(as.character(roczne_sr_spodnie$V15))),
cor(ZACHO, as.numeric(as.character(roczne_sr_spodnie$V16))))
sr_spodnie_kor = mean(spodnie_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny spodni wynosi", round(sr_spodnie_kor,
digits = 4), "co wskazuje na brak korelacji"))
print(".........................................................")
#### Półbuty edycja nagłówków i tabel ####
buty_df = buty_df %>% remove_empty("cols") # Usuwam puste kolumny
buty_df = subset(buty_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(buty_df) <- gsub("styczeń.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "styczeń.", names(buty_df))
names(buty_df) <- gsub("luty.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "luty.", names(buty_df))
names(buty_df) <- gsub("marzec.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "marzec.", names(buty_df))
names(buty_df) <- gsub("kwiecień.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "kwiecień.", names(buty_df))
names(buty_df) <- gsub("maj.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "maj.", names(buty_df))
names(buty_df) <- gsub("czerwiec.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "czerwiec.", names(buty_df))
names(buty_df) <- gsub("lipiec.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "lipiec.", names(buty_df))
names(buty_df) <- gsub("sierpień.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "sierpień.", names(buty_df))
names(buty_df) <- gsub("wrzesień.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "wrzesień.", names(buty_df))
names(buty_df) <- gsub("październik.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "październik.", names(buty_df))
names(buty_df) <- gsub("listopad.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "listopad.", names(buty_df))
names(buty_df) <- gsub("grudzień.półbuty.damskie.skórzane.na.podeszwie.nieskórzanej...za.1parę.cena.", "grudzień.", names(buty_df))
names(buty_df) <- gsub("..zł.", "", names(buty_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(buty_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(buty_df))
names(buty_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(buty_df))
names(buty_df) <- gsub("luty.2006", "2006 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2007", "2007 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2008", "2008 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2009", "2009 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2010", "2010 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2011", "2011 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2012", "2012 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2013", "2013 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2014", "2014 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2015", "2015 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2016", "2016 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2017", "2017 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2018", "2018 2 luty", names(buty_df))
names(buty_df) <- gsub("luty.2019", "2019 2 luty", names(buty_df))
names(buty_df) <- gsub("marzec.2006", "2006 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2007", "2007 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2008", "2008 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2009", "2009 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2010", "2010 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2011", "2011 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2012", "2012 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2013", "2013 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2014", "2014 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2015", "2015 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2016", "2016 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2017", "2017 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2018", "2018 3 marzec", names(buty_df))
names(buty_df) <- gsub("marzec.2019", "2019 3 marzec", names(buty_df))
names(buty_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(buty_df))
names(buty_df) <- gsub("maj.2006", "2006 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2007", "2007 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2008", "2008 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2009", "2009 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2010", "2010 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2011", "2011 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2012", "2012 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2013", "2013 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2014", "2014 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2015", "2015 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2016", "2016 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2017", "2017 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2018", "2018 5 maj", names(buty_df))
names(buty_df) <- gsub("maj.2019", "2019 5 maj", names(buty_df))
names(buty_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(buty_df))
names(buty_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(buty_df))
names(buty_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(buty_df))
names(buty_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(buty_df))
names(buty_df) <- gsub("październik.2006", "2006 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2007", "2007 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2008", "2008 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2009", "2009 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2010", "2010 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2011", "2011 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2012", "2012 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2013", "2013 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2014", "2014 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2015", "2015 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2016", "2016 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2017", "2017 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2018", "2018 90 październik", names(buty_df))
names(buty_df) <- gsub("październik.2019", "2019 90 październik", names(buty_df))
names(buty_df) <- gsub("listopad.2006", "2006 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2007", "2007 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2008", "2008 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2009", "2009 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2010", "2010 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2011", "2011 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2012", "2012 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2013", "2013 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2014", "2014 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2015", "2015 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2016", "2016 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2017", "2017 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2018", "2018 91 listopad", names(buty_df))
names(buty_df) <- gsub("listopad.2019", "2019 91 listopad", names(buty_df))
names(buty_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(buty_df))
names(buty_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(buty_df))
buty_df = buty_df[sort(colnames(buty_df))] #Sortuję chronologicznie
#buty_df = subset(buty_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
buty_df = t(buty_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
buty_df = unname(buty_df) #Usuwam zbędne teraz nazwy
buty_df = as.data.frame(buty_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
buty_dolnoslaskie = as.numeric(gsub(",", ".", as.character(buty_df$V1)))
buty_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(buty_df$V2)))
buty_lubelskie = as.numeric(gsub(",", ".", as.character(buty_df$V3)))
buty_lubuskie = as.numeric(gsub(",", ".", as.character(buty_df$V4)))
buty_lodzkie = as.numeric(gsub(",", ".", as.character(buty_df$V5)))
buty_malopolskie = as.numeric(gsub(",", ".", as.character(buty_df$V6)))
buty_mazowieckie = as.numeric(gsub(",", ".", as.character(buty_df$V7)))
buty_opolskie = as.numeric(gsub(",", ".", as.character(buty_df$V8)))
buty_podkarpackie = as.numeric(gsub(",", ".", as.character(buty_df$V9)))
buty_podlaskie = as.numeric(gsub(",", ".", as.character(buty_df$V10)))
buty_pomorskie = as.numeric(gsub(",", ".", as.character(buty_df$V11)))
buty_slaskie = as.numeric(gsub(",", ".", as.character(buty_df$V12)))
buty_swietokrzyskie = as.numeric(gsub(",", ".", as.character(buty_df$V13)))
buty_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(buty_df$V14)))
buty_wielkopolskie = as.numeric(gsub(",", ".", as.character(buty_df$V15)))
buty_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(buty_df$V16)))
#### Wykres cen półbutów ####
y = (1:168)
#Wykres dla buty i wszystkich województw
buty_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen półbutów damskich w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = buty_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = buty_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = buty_lubelskie, name = "lubelskie")%>%
add_lines(y = buty_lubuskie, name = "lubuskie")%>%
add_lines(y = buty_lodzkie, name = "łódzkie")%>%
add_lines(y = buty_malopolskie, name = "małopolskie")%>%
add_lines(y = buty_mazowieckie, name = "mazowieckie")%>%
add_lines(y = buty_opolskie, name = "opolskie")%>%
add_lines(y = buty_podkarpackie, name = "podkarpackie")%>%
add_lines(y = buty_podlaskie, name = "podlaskie")%>%
add_lines(y = buty_pomorskie, name = "pomorskie")%>%
add_lines(y = buty_slaskie, name = "śląskie")%>%
add_lines(y = buty_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = buty_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = buty_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = buty_zachodniopomorskie, name = "zachodniopomorskie")
#print(buty_plot)
#### Średnie roczne ceny półbutów ####
roczne_sr_buty = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_buty) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_buty[1,i] = round(mean(buty_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[2,i] = round(mean(buty_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[3,i] = round(mean(buty_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[4,i] = round(mean(buty_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[5,i] = round(mean(buty_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[6,i] = round(mean(buty_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[7,i] = round(mean(buty_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[8,i] = round(mean(buty_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[9,i] = round(mean(buty_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[10,i] = round(mean(buty_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[11,i] = round(mean(buty_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[12,i] = round(mean(buty_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[13,i] = round(mean(buty_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[14,i] = round(mean(buty_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[15,i] = round(mean(buty_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_buty[16,i] = round(mean(buty_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_buty = t(roczne_sr_buty)
roczne_sr_buty = unname(roczne_sr_buty) #Usuwam zbędne teraz nazwy
roczne_sr_buty = as.data.frame(roczne_sr_buty) #Przekształcam na dataframe
#### Średnia cena półbutów dla każdego wojewódstwa ####
buty_dolnoslaskie_sr = round(mean(buty_dolnoslaskie), digits = 2) #1
buty_kujawsko_pomorskie_sr = round(mean(buty_kujawsko_pomorskie), digits = 2) #2
buty_lubelskie_sr = round(mean(buty_lubelskie), digits = 2) #3
buty_lubuskie_sr = round(mean(buty_lubuskie), digits = 2) #4
buty_lodzkie_sr = round(mean(buty_lodzkie), digits = 2) #5
buty_malopolskie_sr = round(mean(buty_malopolskie), digits = 2) #6
buty_mazowieckie_sr = round(mean(buty_mazowieckie), digits = 2) #7
buty_opolskie_sr = round(mean(buty_opolskie), digits = 2) #8
buty_podkarpackie_sr = round(mean(buty_podkarpackie), digits = 2) #9
buty_podlaskie_sr = round(mean(buty_podlaskie), digits = 2) #10
buty_pomorskie_sr = round(mean(buty_pomorskie), digits = 2) #11
buty_slaskie_sr = round(mean(buty_slaskie), digits = 2) #12
buty_swietokrzyskie_sr = round(mean(buty_swietokrzyskie), digits = 2) #13
buty_warminsko_mazurskie_sr = round(mean(buty_warminsko_mazurskie), digits = 2) #14
buty_wielkopolskie_sr = round(mean(buty_wielkopolskie), digits = 2) #15
buty_zachodniopomorskie_sr = round(mean(buty_zachodniopomorskie), digits = 2) #16
#### Półbuty średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_buty = c(buty_dolnoslaskie_sr,buty_kujawsko_pomorskie_sr,buty_lubelskie_sr,buty_lubuskie_sr,buty_lodzkie_sr,
buty_malopolskie_sr,buty_mazowieckie_sr,buty_opolskie_sr,buty_podkarpackie_sr,buty_podlaskie_sr,
buty_pomorskie_sr,buty_slaskie_sr,buty_swietokrzyskie_sr,buty_warminsko_mazurskie_sr,
buty_wielkopolskie_sr,buty_zachodniopomorskie_sr)
buty_najmn_w_kazdym_woj = c(min(buty_dolnoslaskie),min(buty_kujawsko_pomorskie),min(buty_lubelskie),
min(buty_lubuskie),min(buty_lodzkie),min(buty_malopolskie),
min(buty_mazowieckie),min(buty_opolskie),min(buty_podkarpackie),
min(buty_podlaskie),min(buty_pomorskie),min(buty_slaskie),
min(buty_swietokrzyskie),min(buty_warminsko_mazurskie),
min(buty_wielkopolskie),min(buty_zachodniopomorskie))
buty_najw_w_kazdym_woj = c(max(buty_dolnoslaskie),max(buty_kujawsko_pomorskie),max(buty_lubelskie),
max(buty_lubuskie),max(buty_lodzkie),max(buty_malopolskie),
max(buty_mazowieckie),max(buty_opolskie),max(buty_podkarpackie),
max(buty_podlaskie),max(buty_pomorskie),max(buty_slaskie),
max(buty_swietokrzyskie),max(buty_warminsko_mazurskie),
max(buty_wielkopolskie),max(buty_zachodniopomorskie))
### Najwyższe i najniższe, różne
buty_sr_cena = mean(sr_cena_buty) #Średnia cena półbutów dla całego kraju
buty_odsd_cena = sd(sr_cena_buty) #Odchylenie standardowe ceny półbutów
buty_najw_sr = max(sr_cena_buty) #Najwyższa średnia cena półbutów
buty_najm_sr = min(sr_cena_buty) #Najniższa średnia cena półbutów
buty_najmn_k = min(buty_najmn_w_kazdym_woj) #Najniższa cena półbutów kiedykolwiek
buty_najw_k = max(buty_najw_w_kazdym_woj) #Najwyższa cena półbutów kiedykolwiek
but_najw_sr = as.numeric(match(buty_najw_sr,sr_cena_buty)) #Numer województwa
but_najmn_sr = as.numeric(match(buty_najm_sr,sr_cena_buty)) #Numer województwa
print(paste("Najwyższa średnia cena butów jest w województwie", wojewodztwa[but_najw_sr],
"i wynosi",buty_najw_sr, "zł"))
print(paste("Najniższa średnia cena butów jest w województwie", wojewodztwa[but_najmn_sr],
"i wynosi",buty_najm_sr, "zł"))
buty_najmn_kazde = as.numeric(match(buty_najmn_k, buty_najmn_w_kazdym_woj)) #Numer województwa
buty_najw_kazde = as.numeric(match(buty_najw_k, buty_najw_w_kazdym_woj)) #Numer województwa
buty_najmn_kiedy = match(buty_najmn_k, buty_podlaskie) #Kiedy
buty_najw_kiedy = match(buty_najw_k, buty_lubelskie) #Kiedy
print(paste("Najniższa cena butów była w", daty[buty_najmn_kiedy], "w województwie",
wojewodztwa[buty_najmn_kazde],"i wynosiła", buty_najmn_k, "zł"))
print(paste("Najwyższa cena butów była w", daty[buty_najw_kiedy], "w województwie",
wojewodztwa[buty_najw_kazde],"i wynosiła", buty_najw_k, "zł"))
print(paste("Odchylenie standardowe cen butów wynosi", round(buty_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny półbutów ####
buty_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_buty$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_buty$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_buty$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_buty$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_buty$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_buty$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_buty$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_buty$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_buty$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_buty$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_buty$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_buty$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_buty$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny butów wynosi", round(mean(buty_placa_min_kor),
digits = 4), "co wskazuje na silną korelację"))
#### Korelacja średniej pensji do średniej ceny półbutów ####
buty_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_buty$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_buty$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_buty$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_buty$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_buty$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_buty$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_buty$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_buty$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_buty$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_buty$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_buty$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_buty$V13))),
cor(SWIET, as.numeric(as.character(roczne_sr_buty$V14))),
cor(WARMI, as.numeric(as.character(roczne_sr_buty$V15))),
cor(WIELK, as.numeric(as.character(roczne_sr_buty$V16))),
cor(ZACHO, as.numeric(as.character(roczne_sr_buty$V13))))
sr_buty_kor = mean(buty_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny butów wynosi", round(sr_buty_kor,
digits = 4), "co wskazuje na silną korelację"))
print(".........................................................")
#### Zlewozmywak edycja nagłówków i tabel ####
zlewozmywak_df = zlewozmywak_df %>% remove_empty("cols") # Usuwam puste kolumny
zlewozmywak_df = subset(zlewozmywak_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(zlewozmywak_df) <- gsub("styczeń.bateria.zlewozmywakowa.cena.", "styczeń.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.bateria.zlewozmywakowa.cena.", "luty.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.bateria.zlewozmywakowa.cena.", "marzec.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.bateria.zlewozmywakowa.cena.", "kwiecień.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.bateria.zlewozmywakowa.cena.", "maj.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.bateria.zlewozmywakowa.cena.", "czerwiec.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.bateria.zlewozmywakowa.cena.", "lipiec.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.bateria.zlewozmywakowa.cena.", "sierpień.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.bateria.zlewozmywakowa.cena.", "wrzesień.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.bateria.zlewozmywakowa.cena.", "październik.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.bateria.zlewozmywakowa.cena.", "listopad.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.bateria.zlewozmywakowa.cena.", "grudzień.", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("..zł.", "", names(zlewozmywak_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(zlewozmywak_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2006", "2006 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2007", "2007 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2008", "2008 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2009", "2009 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2010", "2010 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2011", "2011 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2012", "2012 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2013", "2013 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2014", "2014 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2015", "2015 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2016", "2016 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2017", "2017 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2018", "2018 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("luty.2019", "2019 2 luty", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2006", "2006 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2007", "2007 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2008", "2008 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2009", "2009 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2010", "2010 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2011", "2011 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2012", "2012 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2013", "2013 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2014", "2014 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2015", "2015 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2016", "2016 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2017", "2017 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2018", "2018 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("marzec.2019", "2019 3 marzec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2006", "2006 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2007", "2007 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2008", "2008 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2009", "2009 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2010", "2010 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2011", "2011 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2012", "2012 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2013", "2013 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2014", "2014 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2015", "2015 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2016", "2016 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2017", "2017 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2018", "2018 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("maj.2019", "2019 5 maj", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2006", "2006 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2007", "2007 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2008", "2008 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2009", "2009 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2010", "2010 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2011", "2011 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2012", "2012 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2013", "2013 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2014", "2014 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2015", "2015 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2016", "2016 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2017", "2017 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2018", "2018 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("październik.2019", "2019 90 październik", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2006", "2006 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2007", "2007 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2008", "2008 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2009", "2009 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2010", "2010 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2011", "2011 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2012", "2012 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2013", "2013 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2014", "2014 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2015", "2015 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2016", "2016 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2017", "2017 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2018", "2018 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("listopad.2019", "2019 91 listopad", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(zlewozmywak_df))
names(zlewozmywak_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(zlewozmywak_df))
zlewozmywak_df = zlewozmywak_df[sort(colnames(zlewozmywak_df))] #Sortuję chronologicznie
#zlewozmywak_df = subset(zlewozmywak_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
zlewozmywak_df = t(zlewozmywak_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
zlewozmywak_df = unname(zlewozmywak_df) #Usuwam zbędne teraz nazwy
zlewozmywak_df = as.data.frame(zlewozmywak_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
zlewozmywak_dolnoslaskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V1)))
zlewozmywak_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V2)))
zlewozmywak_lubelskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V3)))
zlewozmywak_lubuskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V4)))
zlewozmywak_lodzkie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V5)))
zlewozmywak_malopolskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V6)))
zlewozmywak_mazowieckie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V7)))
zlewozmywak_opolskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V8)))
zlewozmywak_podkarpackie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V9)))
zlewozmywak_podlaskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V10)))
zlewozmywak_pomorskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V11)))
zlewozmywak_slaskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V12)))
zlewozmywak_swietokrzyskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V13)))
zlewozmywak_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V14)))
zlewozmywak_wielkopolskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V15)))
zlewozmywak_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(zlewozmywak_df$V16)))
#### Wykres cen zlewozmywaka ####
y = (1:168)
#Wykres dla zlewozmywaka i wszystkich województw
zlewozmywak_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen baterii zlewozmywakowej w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = zlewozmywak_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = zlewozmywak_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = zlewozmywak_lubelskie, name = "lubelskie")%>%
add_lines(y = zlewozmywak_lubuskie, name = "lubuskie")%>%
add_lines(y = zlewozmywak_lodzkie, name = "łódzkie")%>%
add_lines(y = zlewozmywak_malopolskie, name = "małopolskie")%>%
add_lines(y = zlewozmywak_mazowieckie, name = "mazowieckie")%>%
add_lines(y = zlewozmywak_opolskie, name = "opolskie")%>%
add_lines(y = zlewozmywak_podkarpackie, name = "podkarpackie")%>%
add_lines(y = zlewozmywak_podlaskie, name = "podlaskie")%>%
add_lines(y = zlewozmywak_pomorskie, name = "pomorskie")%>%
add_lines(y = zlewozmywak_slaskie, name = "śląskie")%>%
add_lines(y = zlewozmywak_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = zlewozmywak_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = zlewozmywak_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = zlewozmywak_zachodniopomorskie, name = "zachodniopomorskie")
#print(zlewozmywak_plot)
#### Średnie roczne ceny zlewozmywaka ####
roczne_sr_zlewozmywak = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_zlewozmywak) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_zlewozmywak[1,i] = round(mean(zlewozmywak_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[2,i] = round(mean(zlewozmywak_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[3,i] = round(mean(zlewozmywak_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[4,i] = round(mean(zlewozmywak_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[5,i] = round(mean(zlewozmywak_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[6,i] = round(mean(zlewozmywak_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[7,i] = round(mean(zlewozmywak_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[8,i] = round(mean(zlewozmywak_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[9,i] = round(mean(zlewozmywak_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[10,i] = round(mean(zlewozmywak_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[11,i] = round(mean(zlewozmywak_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[12,i] = round(mean(zlewozmywak_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[13,i] = round(mean(zlewozmywak_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[14,i] = round(mean(zlewozmywak_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[15,i] = round(mean(zlewozmywak_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_zlewozmywak[16,i] = round(mean(zlewozmywak_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_zlewozmywak = t(roczne_sr_zlewozmywak)
roczne_sr_zlewozmywak = unname(roczne_sr_zlewozmywak) #Usuwam zbędne teraz nazwy
roczne_sr_zlewozmywak = as.data.frame(roczne_sr_zlewozmywak) #Przekształcam na dataframe
#### Średnia cena zlewozmywaka dla każdego wojewódstwa ####
zlewozmywak_dolnoslaskie_sr = round(mean(zlewozmywak_dolnoslaskie), digits = 2) #1
zlewozmywak_kujawsko_pomorskie_sr = round(mean(zlewozmywak_kujawsko_pomorskie), digits = 2) #2
zlewozmywak_lubelskie_sr = round(mean(zlewozmywak_lubelskie), digits = 2) #3
zlewozmywak_lubuskie_sr = round(mean(zlewozmywak_lubuskie), digits = 2) #4
zlewozmywak_lodzkie_sr = round(mean(zlewozmywak_lodzkie), digits = 2) #5
zlewozmywak_malopolskie_sr = round(mean(zlewozmywak_malopolskie), digits = 2) #6
zlewozmywak_mazowieckie_sr = round(mean(zlewozmywak_mazowieckie), digits = 2) #7
zlewozmywak_opolskie_sr = round(mean(zlewozmywak_opolskie), digits = 2) #8
zlewozmywak_podkarpackie_sr = round(mean(zlewozmywak_podkarpackie), digits = 2) #9
zlewozmywak_podlaskie_sr = round(mean(zlewozmywak_podlaskie), digits = 2) #10
zlewozmywak_pomorskie_sr = round(mean(zlewozmywak_pomorskie), digits = 2) #11
zlewozmywak_slaskie_sr = round(mean(zlewozmywak_slaskie), digits = 2) #12
zlewozmywak_swietokrzyskie_sr = round(mean(zlewozmywak_swietokrzyskie), digits = 2) #13
zlewozmywak_warminsko_mazurskie_sr = round(mean(zlewozmywak_warminsko_mazurskie), digits = 2) #14
zlewozmywak_wielkopolskie_sr = round(mean(zlewozmywak_wielkopolskie), digits = 2) #15
zlewozmywak_zachodniopomorskie_sr = round(mean(zlewozmywak_zachodniopomorskie), digits = 2) #16
#### Zlewozmywak średnie, najw, najmn ceny w jednym wektorze ####
sr_cena_zlewozmywak = c(zlewozmywak_dolnoslaskie_sr,zlewozmywak_kujawsko_pomorskie_sr,zlewozmywak_lubelskie_sr,zlewozmywak_lubuskie_sr,zlewozmywak_lodzkie_sr,
zlewozmywak_malopolskie_sr,zlewozmywak_mazowieckie_sr,zlewozmywak_opolskie_sr,zlewozmywak_podkarpackie_sr,zlewozmywak_podlaskie_sr,
zlewozmywak_pomorskie_sr,zlewozmywak_slaskie_sr,zlewozmywak_swietokrzyskie_sr,zlewozmywak_warminsko_mazurskie_sr,
zlewozmywak_wielkopolskie_sr,zlewozmywak_zachodniopomorskie_sr)
zlewozmywak_najmn_w_kazdym_woj = c(min(zlewozmywak_dolnoslaskie),min(zlewozmywak_kujawsko_pomorskie),min(zlewozmywak_lubelskie),
min(zlewozmywak_lubuskie),min(zlewozmywak_lodzkie),min(zlewozmywak_malopolskie),
min(zlewozmywak_mazowieckie),min(zlewozmywak_opolskie),min(zlewozmywak_podkarpackie),
min(zlewozmywak_podlaskie),min(zlewozmywak_pomorskie),min(zlewozmywak_slaskie),
min(zlewozmywak_swietokrzyskie),min(zlewozmywak_warminsko_mazurskie),
min(zlewozmywak_wielkopolskie),min(zlewozmywak_zachodniopomorskie))
zlewozmywak_najw_w_kazdym_woj = c(max(zlewozmywak_dolnoslaskie),max(zlewozmywak_kujawsko_pomorskie),max(zlewozmywak_lubelskie),
max(zlewozmywak_lubuskie),max(zlewozmywak_lodzkie),max(zlewozmywak_malopolskie),
max(zlewozmywak_mazowieckie),max(zlewozmywak_opolskie),max(zlewozmywak_podkarpackie),
max(zlewozmywak_podlaskie),max(zlewozmywak_pomorskie),max(zlewozmywak_slaskie),
max(zlewozmywak_swietokrzyskie),max(zlewozmywak_warminsko_mazurskie),
max(zlewozmywak_wielkopolskie),max(zlewozmywak_zachodniopomorskie))
### Najwyższe i najniższe, różne
zlewozmywak_sr_cena = mean(sr_cena_zlewozmywak) #Średnia cena zlewozmywaka dla całego kraju
zlewozmywak_odsd_cena = sd(sr_cena_zlewozmywak) #Odchylenie standardowe ceny zlewozmywaka
zlewozmywak_najw_sr = max(sr_cena_zlewozmywak) #Najwyższa średnia cena zlewozmywaka
zlewozmywak_najm_sr = min(sr_cena_zlewozmywak) #Najniższa średnia cena zlewozmywaka
zlewozmywak_najmn_k = min(zlewozmywak_najmn_w_kazdym_woj) #Najniższa cena zlewozmywaka kiedykolwiek
zlewozmywak_najw_k = max(zlewozmywak_najw_w_kazdym_woj) #Najwyższa cena zlewozmywaka kiedykolwiek
zlew_najw_sr = as.numeric(match(zlewozmywak_najw_sr,sr_cena_zlewozmywak)) #Numer województwa
zlew_najmn_sr = as.numeric(match(zlewozmywak_najm_sr,sr_cena_zlewozmywak)) #Numer województwa
print(paste("Najwyższa średnia cena zlewozmywaka jest w województwie", wojewodztwa[zlew_najw_sr],
"i wynosi",zlewozmywak_najw_sr))
print(paste("Najniższa średnia cena zlewozmywaka jest w województwie", wojewodztwa[zlew_najmn_sr],
"i wynosi",zlewozmywak_najm_sr))
zlewozmywak_najmn_kazde = as.numeric(match(zlewozmywak_najmn_k, zlewozmywak_najmn_w_kazdym_woj)) #Numer województwa
zlewozmywak_najw_kazde = as.numeric(match(zlewozmywak_najw_k, zlewozmywak_najw_w_kazdym_woj)) #Numer województwa
zlewozmywak_najmn_kiedy = match(zlewozmywak_najmn_k, zlewozmywak_swietokrzyskie) #Kiedy
zlewozmywak_najw_kiedy = match(zlewozmywak_najw_k, zlewozmywak_opolskie) #Kiedy
print(paste("Najniższa cena zlewozmywaka była w", daty[zlewozmywak_najmn_kiedy], "w województwie",
wojewodztwa[zlewozmywak_najmn_kazde],"i wynosiła", zlewozmywak_najmn_k, "zł"))
print(paste("Najwyższa cena zlewozmywaka była w", daty[zlewozmywak_najw_kiedy], "w województwie",
wojewodztwa[zlewozmywak_najw_kazde],"i wynosiła", zlewozmywak_najw_k, "zł"))
print(paste("Odchylenie standardowe cen zlewozmywaka wynosi", round(zlewozmywak_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny zlewozmywaka ####
zlewozmywak_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_zlewozmywak$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_zlewozmywak$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_zlewozmywak$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_zlewozmywak$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_zlewozmywak$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_zlewozmywak$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_zlewozmywak$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_zlewozmywak$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_zlewozmywak$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_zlewozmywak$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_zlewozmywak$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_zlewozmywak$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_zlewozmywak$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny zlewozmywaka wynosi", round(mean(zlewozmywak_placa_min_kor),
digits = 4), "co wskazuje na silną korelację"))
#### Korelacja średniej pensji do średniej ceny zlewozmywaka ####
zlewozmywak_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_zlewozmywak$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_zlewozmywak$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_zlewozmywak$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_zlewozmywak$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_zlewozmywak$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_zlewozmywak$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_zlewozmywak$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_zlewozmywak$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_zlewozmywak$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_zlewozmywak$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_zlewozmywak$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_zlewozmywak$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_zlewozmywak$V13))),
cor(WARMI, as.numeric(as.character(roczne_sr_zlewozmywak$V14))),
cor(WIELK, as.numeric(as.character(roczne_sr_zlewozmywak$V15))),
cor(ZACHO, as.numeric(as.character(roczne_sr_zlewozmywak$V16))))
sr_zlewozmywak_kor = mean(zlewozmywak_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny zlewozmywaka wynosi", round(sr_zlewozmywak_kor,
digits = 4), "co wskazuje na silną korelację"))
print(".........................................................")
#### Lekarz edycja nagłówków i tabel ####
lekarz_df = lekarz_df %>% remove_empty("cols") # Usuwam puste kolumny
lekarz_df = subset(lekarz_df, select = -c(Kod,Nazwa))
#Edtuję nazwy kolumn na sensowne
names(lekarz_df) <- gsub("styczeń.wizyta.u.lekarza.specjalisty.cena.", "styczeń.", names(lekarz_df))
names(lekarz_df) <- gsub("luty.wizyta.u.lekarza.specjalisty.cena.", "luty.", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.wizyta.u.lekarza.specjalisty.cena.", "marzec.", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.wizyta.u.lekarza.specjalisty.cena.", "kwiecień.", names(lekarz_df))
names(lekarz_df) <- gsub("maj.wizyta.u.lekarza.specjalisty.cena.", "maj.", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.wizyta.u.lekarza.specjalisty.cena.", "czerwiec.", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.wizyta.u.lekarza.specjalisty.cena.", "lipiec.", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.wizyta.u.lekarza.specjalisty.cena.", "sierpień.", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.wizyta.u.lekarza.specjalisty.cena.", "wrzesień.", names(lekarz_df))
names(lekarz_df) <- gsub("październik.wizyta.u.lekarza.specjalisty.cena.", "październik.", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.wizyta.u.lekarza.specjalisty.cena.", "listopad.", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.wizyta.u.lekarza.specjalisty.cena.", "grudzień.", names(lekarz_df))
names(lekarz_df) <- gsub("..zł.", "", names(lekarz_df))
#Nie znalazłem inteligentnego sposobu na sensowne posortowanie chronologiczne więc robię to łopatologicznie
names(lekarz_df) <- gsub("styczeń.2006", "2006 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2007", "2007 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2008", "2008 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2009", "2009 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2010", "2010 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2011", "2011 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2012", "2012 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2013", "2013 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2014", "2014 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2015", "2015 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2016", "2016 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2017", "2017 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2018", "2018 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("styczeń.2019", "2019 1 styczeń", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2006", "2006 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2007", "2007 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2008", "2008 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2009", "2009 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2010", "2010 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2011", "2011 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2012", "2012 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2013", "2013 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2014", "2014 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2015", "2015 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2016", "2016 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2017", "2017 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2018", "2018 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("luty.2019", "2019 2 luty", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2006", "2006 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2007", "2007 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2008", "2008 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2009", "2009 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2010", "2010 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2011", "2011 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2012", "2012 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2013", "2013 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2014", "2014 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2015", "2015 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2016", "2016 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2017", "2017 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2018", "2018 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("marzec.2019", "2019 3 marzec", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2006", "2006 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2007", "2007 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2008", "2008 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2009", "2009 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2010", "2010 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2011", "2011 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2012", "2012 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2013", "2013 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2014", "2014 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2015", "2015 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2016", "2016 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2017", "2017 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2018", "2018 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("kwiecień.2019", "2019 4 kwiecień", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2006", "2006 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2007", "2007 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2008", "2008 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2009", "2009 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2010", "2010 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2011", "2011 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2012", "2012 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2013", "2013 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2014", "2014 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2015", "2015 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2016", "2016 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2017", "2017 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2018", "2018 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("maj.2019", "2019 5 maj", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2006", "2006 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2007", "2007 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2008", "2008 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2009", "2009 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2010", "2010 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2011", "2011 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2012", "2012 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2013", "2013 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2014", "2014 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2015", "2015 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2016", "2016 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2017", "2017 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2018", "2018 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("czerwiec.2019", "2019 6 czerwiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2006", "2006 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2007", "2007 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2008", "2008 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2009", "2009 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2010", "2010 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2011", "2011 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2012", "2012 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2013", "2013 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2014", "2014 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2015", "2015 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2016", "2016 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2017", "2017 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2018", "2018 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("lipiec.2019", "2019 7 lipiec", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2006", "2006 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2007", "2007 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2008", "2008 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2009", "2009 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2010", "2010 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2011", "2011 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2012", "2012 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2013", "2013 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2014", "2014 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2015", "2015 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2016", "2016 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2017", "2017 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2018", "2018 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("sierpień.2019", "2019 8 sierpień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2006", "2006 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2007", "2007 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2008", "2008 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2009", "2009 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2010", "2010 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2011", "2011 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2012", "2012 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2013", "2013 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2014", "2014 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2015", "2015 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2016", "2016 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2017", "2017 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2018", "2018 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("wrzesień.2019", "2019 9 wrzesień", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2006", "2006 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2007", "2007 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2008", "2008 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2009", "2009 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2010", "2010 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2011", "2011 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2012", "2012 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2013", "2013 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2014", "2014 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2015", "2015 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2016", "2016 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2017", "2017 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2018", "2018 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("październik.2019", "2019 90 październik", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2006", "2006 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2007", "2007 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2008", "2008 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2009", "2009 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2010", "2010 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2011", "2011 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2012", "2012 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2013", "2013 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2014", "2014 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2015", "2015 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2016", "2016 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2017", "2017 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2018", "2018 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("listopad.2019", "2019 91 listopad", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2006", "2006 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2007", "2007 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2008", "2008 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2009", "2009 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2010", "2010 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2011", "2011 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2012", "2012 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2013", "2013 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2014", "2014 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2015", "2015 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2016", "2016 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2017", "2017 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2018", "2018 92 grudzień", names(lekarz_df))
names(lekarz_df) <- gsub("grudzień.2019", "2019 92 grudzień", names(lekarz_df))
lekarz_df = lekarz_df[sort(colnames(lekarz_df))] #Sortuję chronologicznie
#lekarz_df = subset(lekarz_df, select = -c(Nazwa) ) # Usuwam zbędną kolumnę z nazwazmi województw
lekarz_df = t(lekarz_df) #Tramsponuję dataframe żeby poszczególne kolumny były województwami
lekarz_df = unname(lekarz_df) #Usuwam zbędne teraz nazwy
lekarz_df = as.data.frame(lekarz_df) #Przekształcam na dataframe
# Normalnie nie dało się przkonwertować danych na numeric, bo zamiast kropek były
# przecinki i niemiłosiernie długo się nad tym głowiłem. Cały czas otrzymywałem
# wartości NA
lekarz_dolnoslaskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V1)))
lekarz_kujawsko_pomorskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V2)))
lekarz_lubelskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V3)))
lekarz_lubuskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V4)))
lekarz_lodzkie = as.numeric(gsub(",", ".", as.character(lekarz_df$V5)))
lekarz_malopolskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V6)))
lekarz_mazowieckie = as.numeric(gsub(",", ".", as.character(lekarz_df$V7)))
lekarz_opolskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V8)))
lekarz_podkarpackie = as.numeric(gsub(",", ".", as.character(lekarz_df$V9)))
lekarz_podlaskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V10)))
lekarz_pomorskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V11)))
lekarz_slaskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V12)))
lekarz_swietokrzyskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V13)))
lekarz_warminsko_mazurskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V14)))
lekarz_wielkopolskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V15)))
lekarz_zachodniopomorskie = as.numeric(gsub(",", ".", as.character(lekarz_df$V16)))
#### Wykres cen lakarza ####
y = (1:168)
#Wykres dla lekarza i wszystkich województw
lekarz_plot = plot_ly(x = y )%>%
layout(title = 'Zmiana cen wyzyty u lekarza specjalisty w latach 2006-2019', xaxis = list(title = 'Rok',
ticktext = list("2006", "2007", "2008", "2009", "2010", "2011","2012","2013","2014","2015","2016","2017","2018","2019"),
tickvals = list(1, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156)),
yaxis = list(title = 'cena (zł)')) %>%
add_lines(y = lekarz_dolnoslaskie, name = "dolnoślaskie")%>%
add_lines(y = lekarz_kujawsko_pomorskie, name = "kujawsko-pomorskie")%>%
add_lines(y = lekarz_lubelskie, name = "lubelskie")%>%
add_lines(y = lekarz_lubuskie, name = "lubuskie")%>%
add_lines(y = lekarz_lodzkie, name = "łódzkie")%>%
add_lines(y = lekarz_malopolskie, name = "małopolskie")%>%
add_lines(y = lekarz_mazowieckie, name = "mazowieckie")%>%
add_lines(y = lekarz_opolskie, name = "opolskie")%>%
add_lines(y = lekarz_podkarpackie, name = "podkarpackie")%>%
add_lines(y = lekarz_podlaskie, name = "podlaskie")%>%
add_lines(y = lekarz_pomorskie, name = "pomorskie")%>%
add_lines(y = lekarz_slaskie, name = "śląskie")%>%
add_lines(y = lekarz_swietokrzyskie, name = "świetokrzyskie")%>%
add_lines(y = lekarz_warminsko_mazurskie, name = "warmińsko_mazurskie")%>%
add_lines(y = lekarz_wielkopolskie, name = "wielkopolskie")%>%
add_lines(y = lekarz_zachodniopomorskie, name = "zachodniopomorskie")
#print(lekarz_plot)
#### Średnie roczne ceny lekarza ####
roczne_sr_lekarz = data.frame('','','','','','','','','','','','','', stringsAsFactors = FALSE)
names(roczne_sr_lekarz) = c("2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016",
"2017","2018")
for (i in 1:13) {
roczne_sr_lekarz[1,i] = round(mean(lekarz_dolnoslaskie[(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[2,i] = round(mean(lekarz_kujawsko_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[3,i] = round(mean(lekarz_lubelskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[4,i] = round(mean(lekarz_lubuskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[5,i] = round(mean(lekarz_lodzkie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[6,i] = round(mean(lekarz_malopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[7,i] = round(mean(lekarz_mazowieckie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[8,i] = round(mean(lekarz_opolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[9,i] = round(mean(lekarz_podkarpackie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[10,i] = round(mean(lekarz_podlaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[11,i] = round(mean(lekarz_pomorskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[12,i] = round(mean(lekarz_slaskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[13,i] = round(mean(lekarz_swietokrzyskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[14,i] = round(mean(lekarz_warminsko_mazurskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[15,i] = round(mean(lekarz_wielkopolskie [(1+(i-1)*12):(12*i)]), digits = 2)
roczne_sr_lekarz[16,i] = round(mean(lekarz_zachodniopomorskie[(1+(i-1)*12):(12*i)]), digits = 2)
}
roczne_sr_lekarz = t(roczne_sr_lekarz)
roczne_sr_lekarz = unname(roczne_sr_lekarz) #Usuwam zbędne teraz nazwy
roczne_sr_lekarz = as.data.frame(roczne_sr_lekarz) #Przekształcam na dataframe
#### Średnia cena lekarza dla każdego wojewódstwa ####
lekarz_dolnoslaskie_sr = round(mean(lekarz_dolnoslaskie), digits = 2) #1
lekarz_kujawsko_pomorskie_sr = round(mean(lekarz_kujawsko_pomorskie), digits = 2) #2
lekarz_lubelskie_sr = round(mean(lekarz_lubelskie), digits = 2) #3
lekarz_lubuskie_sr = round(mean(lekarz_lubuskie), digits = 2) #4
lekarz_lodzkie_sr = round(mean(lekarz_lodzkie), digits = 2) #5
lekarz_malopolskie_sr = round(mean(lekarz_malopolskie), digits = 2) #6
lekarz_mazowieckie_sr = round(mean(lekarz_mazowieckie), digits = 2) #7
lekarz_opolskie_sr = round(mean(lekarz_opolskie), digits = 2) #8
lekarz_podkarpackie_sr = round(mean(lekarz_podkarpackie), digits = 2) #9
lekarz_podlaskie_sr = round(mean(lekarz_podlaskie), digits = 2) #10
lekarz_pomorskie_sr = round(mean(lekarz_pomorskie), digits = 2) #11
lekarz_slaskie_sr = round(mean(lekarz_slaskie), digits = 2) #12
lekarz_swietokrzyskie_sr = round(mean(lekarz_swietokrzyskie), digits = 2) #13
lekarz_warminsko_mazurskie_sr = round(mean(lekarz_warminsko_mazurskie), digits = 2) #14
lekarz_wielkopolskie_sr = round(mean(lekarz_wielkopolskie), digits = 2) #15
lekarz_zachodniopomorskie_sr = round(mean(lekarz_zachodniopomorskie), digits = 2) #16
#### <NAME>, najw, najmn ceny w jednym wektorze ####
sr_cena_lekarz = c(lekarz_dolnoslaskie_sr,lekarz_kujawsko_pomorskie_sr,lekarz_lubelskie_sr,lekarz_lubuskie_sr,lekarz_lodzkie_sr,
lekarz_malopolskie_sr,lekarz_mazowieckie_sr,lekarz_opolskie_sr,lekarz_podkarpackie_sr,lekarz_podlaskie_sr,
lekarz_pomorskie_sr,lekarz_slaskie_sr,lekarz_swietokrzyskie_sr,lekarz_warminsko_mazurskie_sr,
lekarz_wielkopolskie_sr,lekarz_zachodniopomorskie_sr)
lekarz_najmn_w_kazdym_woj = c(min(lekarz_dolnoslaskie),min(lekarz_kujawsko_pomorskie),min(lekarz_lubelskie),
min(lekarz_lubuskie),min(lekarz_lodzkie),min(lekarz_malopolskie),
min(lekarz_mazowieckie),min(lekarz_opolskie),min(lekarz_podkarpackie),
min(lekarz_podlaskie),min(lekarz_pomorskie),min(lekarz_slaskie),
min(lekarz_swietokrzyskie),min(lekarz_warminsko_mazurskie),
min(lekarz_wielkopolskie),min(lekarz_zachodniopomorskie))
lekarz_najw_w_kazdym_woj = c(max(lekarz_dolnoslaskie),max(lekarz_kujawsko_pomorskie),max(lekarz_lubelskie),
max(lekarz_lubuskie),max(lekarz_lodzkie),max(lekarz_malopolskie),
max(lekarz_mazowieckie),max(lekarz_opolskie),max(lekarz_podkarpackie),
max(lekarz_podlaskie),max(lekarz_pomorskie),max(lekarz_slaskie),
max(lekarz_swietokrzyskie),max(lekarz_warminsko_mazurskie),
max(lekarz_wielkopolskie),max(lekarz_zachodniopomorskie))
### Najwyższe i najniższe, różne
lekarz_sr_cena = mean(sr_cena_lekarz) #Średnia cena lekarza dla całego kraju
lekarz_odsd_cena = sd(sr_cena_lekarz) #Odchylenie standardowe ceny lekarza
lekarz_najw_sr = max(sr_cena_lekarz) #Najwyższa średnia cena lekarza
lekarz_najm_sr = min(sr_cena_lekarz) #Najniższa średnia cena lekarza
lekarz_najmn_k = min(lekarz_najmn_w_kazdym_woj) #Najniższa cena lekarza kiedykolwiek
lekarz_najw_k = max(lekarz_najw_w_kazdym_woj) #Najwyższa cena lekarza kiedykolwiek
lek_najw_sr = as.numeric(match(lekarz_najw_sr,sr_cena_lekarz)) #Numer województwa
lek_najmn_sr = as.numeric(match(lekarz_najm_sr,sr_cena_lekarz)) #Numer województwa
print(paste("Najwyższa średnia cena wizyty u lekarza specjalisty jest w województwie", wojewodztwa[lek_najw_sr],
"i wynosi",lekarz_najw_sr))
print(paste("Najniższa średnia cena wizyty u lekarza specjalisty jest w województwie", wojewodztwa[lek_najmn_sr],
"i wynosi",lekarz_najm_sr))
lekarz_najmn_kazde = as.numeric(match(lekarz_najmn_k, lekarz_najmn_w_kazdym_woj)) #Numer województwa
lekarz_najw_kazde = as.numeric(match(lekarz_najw_k, lekarz_najw_w_kazdym_woj)) #Numer województwa
lekarz_najmn_kiedy = match(lekarz_najmn_k, lekarz_warminsko_mazurskie) #Kiedy
lekarz_najw_kiedy = match(lekarz_najw_k, lekarz_wielkopolskie ) #Kiedy
print(paste("Najniższa cena wizyty u lekarza specjalisty była w", daty[lekarz_najmn_kiedy], "w województwie",
wojewodztwa[lekarz_najmn_kazde],"i wynosiła", lekarz_najmn_k, "zł"))
print(paste("Najwyższa cena wizyty u lekarza specjalisty była w", daty[lekarz_najw_kiedy], "w województwie",
wojewodztwa[lekarz_najw_kazde],"i wynosiła", lekarz_najw_k, "zł"))
print(paste("Odchylenie standardowe cen wizyty u lekarza specjalisty wynosi", round(lekarz_odsd_cena, digits = 2), "złotego"))
#### Korelacja płacy minimalnej do średniej ceny lekarza ####
lekarz_placa_min_kor = c(cor(as.numeric(as.character(placa_min_df$V1)), as.numeric(as.character(roczne_sr_lekarz$V1))),
cor(as.numeric(as.character(placa_min_df$V2)), as.numeric(as.character(roczne_sr_lekarz$V2))),
cor(as.numeric(as.character(placa_min_df$V3)), as.numeric(as.character(roczne_sr_lekarz$V3))),
cor(as.numeric(as.character(placa_min_df$V4)), as.numeric(as.character(roczne_sr_lekarz$V4))),
cor(as.numeric(as.character(placa_min_df$V5)), as.numeric(as.character(roczne_sr_lekarz$V5))),
cor(as.numeric(as.character(placa_min_df$V6)), as.numeric(as.character(roczne_sr_lekarz$V6))),
cor(as.numeric(as.character(placa_min_df$V7)), as.numeric(as.character(roczne_sr_lekarz$V7))),
cor(as.numeric(as.character(placa_min_df$V8)), as.numeric(as.character(roczne_sr_lekarz$V8))),
cor(as.numeric(as.character(placa_min_df$V9)), as.numeric(as.character(roczne_sr_lekarz$V9))),
cor(as.numeric(as.character(placa_min_df$V10)), as.numeric(as.character(roczne_sr_lekarz$V10))),
cor(as.numeric(as.character(placa_min_df$V11)), as.numeric(as.character(roczne_sr_lekarz$V11))),
cor(as.numeric(as.character(placa_min_df$V12)), as.numeric(as.character(roczne_sr_lekarz$V12))),
cor(as.numeric(as.character(placa_min_df$V13)), as.numeric(as.character(roczne_sr_lekarz$V13))))
print(paste("Uśredniona korelacja minimalnej pensji do ceny lekarza wynosi", round(mean(lekarz_placa_min_kor),
digits = 4), "co wskazuje na bardzo silną korelację"))
#### Korelacja średniej pensji do średniej ceny lekarza ####
lekarz_sr_pensja_kor = c(cor(DOLNO, as.numeric(as.character(roczne_sr_lekarz$V1))),
cor(KUJAW, as.numeric(as.character(roczne_sr_lekarz$V2))),
cor(LUBEL, as.numeric(as.character(roczne_sr_lekarz$V3))),
cor(LUBUS, as.numeric(as.character(roczne_sr_lekarz$V4))),
cor(LODZK, as.numeric(as.character(roczne_sr_lekarz$V5))),
cor(MALOP, as.numeric(as.character(roczne_sr_lekarz$V6))),
cor(MAZOW, as.numeric(as.character(roczne_sr_lekarz$V7))),
cor(OPOLS, as.numeric(as.character(roczne_sr_lekarz$V8))),
cor(PODKA, as.numeric(as.character(roczne_sr_lekarz$V9))),
cor(PODLA, as.numeric(as.character(roczne_sr_lekarz$V10))),
cor(POMOR, as.numeric(as.character(roczne_sr_lekarz$V11))),
cor(SLASK, as.numeric(as.character(roczne_sr_lekarz$V12))),
cor(SWIET, as.numeric(as.character(roczne_sr_lekarz$V13))),
cor(WARMI, as.numeric(as.character(roczne_sr_lekarz$V14))),
cor(WIELK, as.numeric(as.character(roczne_sr_lekarz$V15))),
cor(ZACHO, as.numeric(as.character(roczne_sr_lekarz$V16))))
sr_lekarz_kor = mean(lekarz_sr_pensja_kor)
print(paste("Uśredniona korelacja średniej pensji do ceny lekarza wynosi", round(sr_lekarz_kor,
digits = 4), "co wskazuje na bardzo silną korelację"))
<file_sep># Projekt-R
Na pewno udało mi się stworzyć najbardziej obszery kod dla tego zadania z całej grupy.
Jego znaczną część zajmuje zmienianie nazw kolumn i na pewno jest na to bardziej inteligentny sposób,
lecz ja nie potrafiłem takiego znaleźć w odpowiednio krótkim czasie.
Kilka dni zajęło mi ogarnięcie, że w tabelkach od GUS są przecinki zamiast kropek.
| 1e111eb29e7bba59752d4248afe06801295a3574 | [
"Markdown",
"R"
] | 2 | R | michalkostrzewski/Projekt-R | e7c30b6f51731782a170701117c03fbbdf051893 | 74291583b8f9bcfd68a742600da1ba35d798b05d |
refs/heads/master | <file_sep>#/bin/sh
composer dump-autoload
php artisan migrate --seed
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Bill;
use App\Models\BillItem;
use App\Models\Product;
use App\Models\Stock;
use App\Models\StockItem;
class ManageDashboardController extends Controller
{
public function view()
{
$balance = Bill::sum('line_total') - Stock::sum('line_total');
$sellCount = BillItem::sum('quantity');
$inStock = StockItem::sum('quantity') - $sellCount;
return view('admin.manager.dashboard', [
'balance' => $balance,
'sellCount' => $sellCount,
'inStock' => $inStock
]);
}
}<file_sep>APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=UTC
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=412shop
DB_USERNAME=root
DB_PASSWORD=
CACHE_DRIVER=file
QUEUE_DRIVER=sync
SESSION_DRIVER=cookie
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router->get('/', 'ProductController@viewHomeProduct');
$router->get('/product', 'ProductController@viewAllProducts');
$router->get('/product/{productId}', 'ProductController@viewDetailProducts');
$router->get('/category', 'ProductController@viewAllCategories');
$router->get('/category/{categoryId}', 'ProductController@viewProductsByCategory');
$router->get('/feedback', 'FeedbackController@view');
$router->post('/feedback', 'FeedbackController@create');
$router->get('/login', [
'as' => 'login',
'use' => function () {
return view('admin.login');
}]);
$router->post('/login', 'AuthenticationController@login');
$router->get('/logout', 'AuthenticationController@logout');
$router->group(['prefix' => 'shop-admin', 'as' => 'admin'], function () use ($router) {
$router->get('/', function () {
return redirect()->route('admin.manager.dashboard');
});
$router->group(['prefix' => 'manager', 'as' => 'manager', 'middleware' => 'auth:manager'], function () use ($router) {
$router->get('/', [
'as' => 'dashboard',
'uses' => 'ManageDashboardController@view'
]);
$router->group(['prefix' => 'category', 'as' => 'category'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageCategoryController@all'
]);
$router->get('{id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageCategoryController@view'
]);
$router->get('{id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageCategoryController@delete'
]);
$router->post('{id:[0-9]+}', [
'as' => 'edit',
'uses' => 'ManageCategoryController@edit'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageCategoryController@create'
]);
});
$router->group(['prefix' => 'product', 'as' => 'product'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageProductController@all'
]);
$router->get('{id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageProductController@view'
]);
$router->get('{id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageProductController@delete'
]);
$router->post('{id:[0-9]+}', [
'as' => 'edit',
'uses' => 'ManageProductController@edit'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageProductController@create'
]);
});
$router->group(['prefix' => 'user', 'as' => 'user'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageUserController@all'
]);
$router->get('{id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageUserController@view'
]);
$router->get('{id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageUserController@delete'
]);
$router->post('{id:[0-9]+}', [
'as' => 'edit',
'uses' => 'ManageUserController@edit'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageUserController@create'
]);
});
$router->group(['prefix' => 'stock', 'as' => 'stock'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageStockController@all'
]);
$router->get('{stock_id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageStockController@view'
]);
$router->get('{stock_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageStockController@delete'
]);
$router->post('{stock_id:[0-9]+}', [
'as' => 'edit',
'uses' => 'ManageStockController@edit'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageStockController@create'
]);
$router->group(['prefix' => '{stock_id:[0-9]+}/item', 'as' => 'item'], function () use ($router) {
$router->get('{product_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageStockController@deleteItem'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageStockController@createItem'
]);
});
});
$router->group(['prefix' => 'bill', 'as' => 'bill'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageBillController@all'
]);
$router->get('{bill_id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageBillController@view'
]);
$router->get('{bill_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageBillController@delete'
]);
$router->post('{bill_id:[0-9]+}', [
'as' => 'edit',
'uses' => 'ManageBillController@edit'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageBillController@create'
]);
$router->group(['prefix' => '{bill_id:[0-9]+}/item', 'as' => 'item'], function () use ($router) {
$router->get('{product_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageBillController@deleteItem'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageBillController@createItem'
]);
});
});
$router->group(['prefix' => 'feedback', 'as' => 'feedback'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageFeedbackController@all'
]);
$router->get('{bill_id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageFeedbackController@view'
]);
$router->get('{bill_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageFeedbackController@delete'
]);
});
$router->group(['prefix' => 'notification', 'as' => 'notification'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageNotificationController@all'
]);
$router->get('{notification_id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageNotificationController@view'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageNotificationController@create'
]);
$router->get('{notification_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageNotificationController@delete'
]);
});
$router->group(['prefix' => 'daily', 'as' => 'daily'], function () use ($router) {
$router->get('/', [
'uses' => 'ManageDailyController@all'
]);
$router->get('{daily_id:[0-9]+}', [
'as' => 'view',
'uses' => 'ManageDailyController@view'
]);
$router->get('{daily_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageDailyController@delete'
]);
$router->post('{daily_id:[0-9]+}', [
'as' => 'edit',
'uses' => 'ManageDailyController@edit'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageDailyController@create'
]);
$router->group(['prefix' => '{daily_id:[0-9]+}/item', 'as' => 'item'], function () use ($router) {
$router->get('{product_id:[0-9]+}/delete', [
'as' => 'delete',
'uses' => 'ManageDailyController@deleteItem'
]);
$router->post('/', [
'as' => 'create',
'uses' => 'ManageDailyController@createItem'
]);
});
});
});
$router->group(['prefix' => 'statistic', 'as' => 'statistic', 'middleware' => 'auth:founder'], function () use ($router) {
$router->get('/', [
'as' => 'popular',
'uses' => 'StatisticController@popular'
]);
$router->group(['prefix' => 'bill', 'as' => 'bill'], function () use ($router) {
$router->get('/', [
'uses' => 'StatisticBillController@view'
]);
$router->get('/{date:[0-9]{4}-[0-9]{2}-[0-9]{2}}', [
'as' => 'dated',
'uses' => 'StatisticBillController@billDate'
]);
$router->get('/{dateF:[0-9]{4}-[0-9]{2}-[0-9]{2}}/{dateT:[0-9]{4}-[0-9]{2}-[0-9]{2}}', [
'uses' => 'StatisticBillController@billRange'
]);
$router->get('/{month:[0-9]{4}-[0-9]{2}}', [
'uses' => 'StatisticBillController@billMonth'
]);
$router->get('/{year:[0-9]{4}}', [
'uses' => 'StatisticBillController@billYear'
]);
$router->post('/',[
'as' => 'dateRedirect',
'uses' => 'StatisticBillController@dateRedirect'
]);
});
$router->group(['prefix' => 'daily', 'as' => 'daily'], function () use ($router) {
$router->get('/',[
'as' => 'daily',
'uses' => 'StatisticDailyController@daily'
]);
$router->post('/',[
'as' => 'dailyRedirect',
'uses' => 'StatisticDailyController@dailyRedirect'
]);
$router->get('{created_at:[0-9]+-[0-9]+-[0-9]+}', [
'as' => 'view',
'uses' => 'StatisticDailyController@view'
]);
});
$router->group(['prefix' => 'product', 'as' => 'product'], function () use ($router) {
$router->get('/',[
'as' => 'product',
'uses' => 'StatisticProductController@all'
]);
$router->post('/',[
'as' => 'productRedirect',
'uses' => 'StatisticProductController@productRedirect'
]);
$router->get('{product_id:[0-9]+}/{date_start}/{date_end}', [
'as' => 'view',
'uses' => 'StatisticProductController@view'
]);
});
});
});<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Notification;
class ManageNotificationController extends Controller
{
public function all()
{
$notifications = Notification::all();
return view('admin.manager.notification.view', [
'notifications' => $notifications
]);
}
public function view($id)
{
$notification = Notification::findOrFail($id);
$notifications = Notification::all();
return view('admin.manager.notification.view', [
'notification' => $notification,
'notifications' => $notifications
]);
}
public function create(Request $request)
{
$notification = new Notification;
$notification->message = $request->input('message');
$notification->url = $request->input('url');
$notification->status = "SEND";
// TODO: Send Notification
$notification->save();
return redirect()->route('admin.manager.notification');
}
public function delete($id)
{
$notification = Notification::findOrFail($id);
$notification->status = "CANCEL";
// TODO: Cancel Notification
$notification->save();
return redirect()->route('admin.manager.notification');
}
}<file_sep>
# 412-Shop
fund db project
## Requirement
* php7
* mariadb or mysql
* composer
## Installation
- Copy `.env.example` to `.env`
- Create database `412shop`
- Install dependencies
```bash
composer install
```
- Migrate database
```bash
php artisan migrate
```
## Develop
- Seed database
```bash
php artisan db:seed
```
- Run local server
```bash
php -S localhost:8000 -t public
```
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Feedback;
use Illuminate\Http\Request;
class FeedbackController extends Controller
{
public function view()
{
return view('feedbackForm', [
'title' => 'Feedback'
]);
}
public function create(Request $request)
{
$feedback = new Feedback;
$feedback->name = $request->input('name');
$feedback->comment = $request->input('comment');
$feedback->save();
return redirect('/');
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\BillItem;
use Carbon\Carbon;
class StatisticDailyController extends Controller
{
public function daily(){
$startOfWeek = Carbon::now()->startOfWeek();
$endOfWeek = Carbon::now()->endOfWeek();
$time = Carbon::today()->toDateString();
$todayDaily = BillItem::with('product')
->orderBy('quantity', 'desc')
->whereDate('created_at', '=', Carbon::now()->toDateString())
->groupBy('product_id')
->selectRaw('product_id, sum(quantity) as quantity')
->get();
return view('admin.statistic.daily_sale_summary', ['daily' => $todayDaily, 'time' => $time]);
}
public function dailyRedirect(Request $request){
$date = $request->input('time');
return redirect()->route('admin.statistic.daily.view', ['created_at' => $date]);
}
public function view($time){
$startOfWeek = Carbon::now()->startOfWeek();
$endOfWeek = Carbon::now()->endOfWeek();
$today = Carbon::today()->toDateString();
$todayDaily = BillItem::with('product')
->orderBy('quantity', 'desc')
->whereDate('created_at', '=', $time)
->groupBy('product_id')
->selectRaw('product_id, sum(quantity) as quantity')
->get();
return view('admin.statistic.daily_sale_summary', ['daily' => $todayDaily, 'time' => $time]);
}
}<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\BillItem;
use App\Models\Notification;
use App\Models\DailyProduct;
use App\Models\Daily;
use Carbon\Carbon;
class ProductController extends Controller
{
public function viewAllProducts()
{
$products = Product::all();
return view('product.all', [
'title' => 'All Products',
'products' => $products
]);
}
public function viewProductsByCategory($categoryId)
{
$category = ProductCategory::findOrFail($categoryId);
$products = $category->products;
return view('product.byCategory', [
'title' => 'Products By Categories - $category',
'products' => $products,
'category' => $category
]);
}
public function viewAllCategories()
{
$categories = ProductCategory::all();
return view('product.allCategory', [
'title' => 'All Categories',
'categories' => $categories
]);
}
public function viewHomeProduct()
{
$BillItems = BillItem::with('product')->orderBy('sum', 'desc')
->groupBy('product_id')
->selectRaw('product_id, sum(quantity) as sum')->limit(9)
->get();
$productsPopular = $BillItems->map(function($billItem) {
return $billItem->product;
});
$beforeDay = Carbon::today();
$dailyProducts = Daily::with('products')
->whereDate('created_date', '=', $beforeDay)
->firstOrFail();
$productsDaily = $dailyProducts->products;
return view('product.home', [
'title' => 'Home - 412shop',
'productsPop' => $productsPopular,
'productsDaily' => $productsDaily
]);
}
public function viewFollow($id)
{
$notification = Notification::findOrFail($id);
$products = $notification->products;
return view('product.follow', [
'title' => 'subscriber ',
'products' => $products,
]);
}
public function viewDetailProducts($productId)
{
$products = Product::findOrFail($productId);
return view('product.detailProduct', [
'title' => 'Products - $products',
'product' => $products,
]);
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Bill extends Model
{
public function items()
{
return $this->hasMany('App\Models\BillItem');
}
public function products()
{
return $this->belongsToMany('App\Models\Product', 'bill_items')->withPivot('quantity')->withTimestamps();
}
public function quantity()
{
return $this->products->sum('pivot.quantity');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Stock;
use App\Models\Product;
use App\Models\User;
class ManageStockController extends Controller
{
public function all()
{
$stocks = Stock::all();
return view('admin.manager.stock.view', [
'stocks' => $stocks,
]);
}
public function view($id)
{
$stock = Stock::findOrFail($id);
$products = Product::orderBy('name')->get();
$stocks = Stock::all();
return view('admin.manager.stock.view', [
'stock' => $stock,
'stocks' => $stocks,
'products' => $products
]);
}
public function create(Request $request)
{
$stock = new Stock;
$stock->user_id = User::first()->id;
$stock->line_total = 0;
$stock->save();
return redirect()->route('admin.manager.stock.view', ['stock_id' => $stock->id]);
}
public function edit(Request $request, $id)
{
$stock = Stock::findOrFail($id);
$items = $request->input('item');
$syncs = [];
foreach($items as $item) {
$syncs[$item['product_id']] = ['price' => $item['price'], 'quantity' => $item['quantity']];
}
$stock->products()->sync($syncs);
$stock->line_total = $this->stockValue($stock);
$stock->save();
return redirect()->route('admin.manager.stock.view', ['stock_id' => $stock->id]);
}
public function delete($id)
{
$stock = Stock::findOrFail($id);
$stock->items()->delete();
$stock->delete();
return redirect()->route('admin.manager.stock');
}
public function createItem(Request $request, $stock_id)
{
$stock = Stock::findOrFail($stock_id);
$stock->products()->attach($request->input('product_id'), [
'price' => $request->input('price', 10),
'quantity' => $request->input('quantity', 1)
]);
$stock->line_total = $this->stockValue($stock);
$stock->save();
return redirect()->route('admin.manager.stock.view', ['stock_id' => $stock_id]);
}
public function deleteItem($stock_id, $product_id)
{
$stock = Stock::findOrFail($stock_id);
$stock->products()->detach($product_id);
$stock->line_total = $this->stockValue($stock);
$stock->save();
return redirect()->route('admin.manager.stock.view', ['stock_id' => $stock_id]);
}
private function stockValue($stock) {
$value = 0;
foreach($stock->items as $item) {
$value += $item->price * $item->quantity;
}
return $value;
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\BillItem;
use App\Models\Bill;
use Carbon\Carbon;
class StatisticBillController extends Controller
{
public function view() {
$bills = Bill::all();
$today = Carbon::now(7);
$tbills = $this->billCalculate(Carbon::now(7), Carbon::now(7));
$wbills = $this->billCalculate(Carbon::now(7)->startOfWeek(), Carbon::now(7)->endOfWeek());
$mbills = $this->billCalculate(Carbon::now(7)->startOfMonth(), Carbon::now(7)->endOfMonth());
$ybills = $this->billCalculate(Carbon::now(7)->startOfYear(), Carbon::now(7)->endOfYear());
$tcount = $tbills->count();
$wcount = $wbills->count();
$mcount = $mbills->count();
$ycount = $ybills->count();
$tsold = $tbills->sum(function ($bill) {
return $bill->quantity();
});
$wsold = $wbills->sum(function ($bill) {
return $bill->quantity();
});
$msold = $mbills->sum(function ($bill) {
return $bill->quantity();
});
$ysold = $ybills->sum(function ($bill) {
return $bill->quantity();
});
$ttotal = $tbills->sum('line_total');
$wtotal = $wbills->sum('line_total');
$mtotal = $mbills->sum('line_total');
$ytotal = $ybills->sum('line_total');
return view('admin.statistic.bill.bill_main', ['today' => $today
,'tcount' => $tcount, 'tsold' => $tsold, 'ttotal' => $ttotal
,'wcount' => $wcount, 'wsold' => $wsold, 'wtotal' => $wtotal
,'mcount' => $mcount, 'msold' => $msold, 'mtotal' => $mtotal
,'ycount' => $ycount, 'ysold' => $ysold, 'ytotal' => $ytotal]);
}
private function billCalculate($dateF, $dateT){
$bills = Bill::with('products')->where('created_at', '>=', $dateF->startOfDay())
->where('created_at', '<=', $dateT->endOfDay())->get();
return $bills;
}
public function billDate($date) {
$odate = Carbon::createFromFormat('Y-m-d', $date)->addHour(7);
$bills = $this->billCalculate($odate, $odate);
$count = $bills->sum('quantity');
$sum = $bills->sum('line_total');
return view('admin.statistic.bill.bill_view', ['date' => $date
,'bills' => $bills
,'count' => $count
,'sum' => $sum]);
}
public function billRange($dateF, $dateT) {
$fdate = Carbon::createFromFormat('Y-m-d', $dateF)->addHour(7);
$tdate = Carbon::createFromFormat('Y-m-d', $dateT)->addHour(7);
$bills = $this->billCalculate($fdate, $tdate);
$count = $bills->sum('quantity');
$sum = $bills->sum('line_total');
return view('admin.statistic.bill.bill_view', ['date' => $dateF . " ~ " . $dateT
,'bills' => $bills
,'count' => $count
,'sum' => $sum]);
}
public function billMonth($month) {
$mdate = Carbon::createFromFormat('Y-m', $month)->addHour(7);
$ndate = Carbon::createFromFormat('Y-m', $month)->addHour(7);
$bills = $this->billCalculate($mdate->startOfMonth(), $ndate->endOfMonth());
$count = $bills->sum('quantity');
$sum = $bills->sum('line_total');
return view('admin.statistic.bill.bill_view', ['date' => $mdate->format('F')
,'bills' => $bills
,'count' => $count
,'sum' => $sum]);
}
public function billYear($year) {
$xdate = Carbon::create($year,1,1,0)->addHour(7);
$ydate = Carbon::create($year,1,1,0)->addHour(7);
$bills = $this->billCalculate($xdate->startOfYear(), $ydate->endOfYear());
$count = $bills->sum('quantity');
$sum = $bills->sum('line_total');
return view('admin.statistic.bill.bill_view', ['date' => $year
,'bills' => $bills
,'count' => $count
,'sum' => $sum]);
}
public function dateRedirect(Request $request){
$date = $request->input('datetimepickerSD');
$date = "2017-12-12";
return redirect()->route('admin.statistic.bill.dated', ['date' => $date]);
}
}<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function productCategory()
{
return $this->belongsTo('App\Models\ProductCategory');
}
public function notifications()
{
return $this->belongsToMany('App\Models\Notification', 'subscribes');
}
public function bills()
{
return $this->belongsToMany('App\Models\Bill', 'bill_items')->withPivot('quantity')->withTimestamps();
}
public function stocks()
{
return $this->belongsToMany('App\Models\Stock', 'stock_items')->withPivot('quantity')->withTimestamps();
}
public function balance(){
return $this->stocks->sum('pivot.quantity') - $this->bills->sum('pivot.quantity');
}
public function dailyProduct()
{
return $this->belongsTo('App\Models\DailyProduct');
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model
{
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function items()
{
return $this->hasMany('App\Models\StockItem');
}
public function products()
{
return $this->belongsToMany('App\Models\Product', 'stock_items')->withPivot('quantity')->withTimestamps();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\BillItem;
use Carbon\Carbon;
class StatisticController extends Controller
{
public function popular() {
$startOfWeek = Carbon::now()->startOfWeek();
$endOfWeek = Carbon::now()->endOfWeek();
$weekPopularProduct = BillItem::with('product')
->orderBy('quantity', 'desc')
->where('created_at', '>=', $startOfWeek)
->where('created_at', '<=', $endOfWeek)
->groupBy('product_id')
->selectRaw('product_id, sum(quantity) as quantity')
->get();
$todayPopularProduct = BillItem::with('product')
->orderBy('quantity', 'desc')
->whereDate('created_at', '>=', Carbon::now()->toDateString())
->groupBy('product_id')
->selectRaw('product_id, sum(quantity) as quantity')
->get();
return view('admin.statistic.popular_product', ['weekPopularProduct' => $weekPopularProduct
, 'todayPopularProduct' => $todayPopularProduct]);
}
}<file_sep><?php
use Illuminate\Database\Seeder;
class BillItemSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('bill_items')->delete();
DB::table('bill_items')->insert([
'bill_id' => 1001,
'product_id' => 1,
'quantity' => 1,
'price' => 15,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('bill_items')->insert([
'bill_id' => 1001,
'product_id' => 3,
'quantity' => 2,
'price' => 18,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('bill_items')->insert([
'bill_id' => 2002,
'product_id' => 4,
'quantity' => 2,
'price' => 34,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('bill_items')->insert([
'bill_id' => 3003,
'product_id' => 5,
'quantity' => 1,
'price' => 75,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('bill_items')->insert([
'bill_id' => 3003,
'product_id' => 3,
'quantity' => 1,
'price' => 9,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('bill_items')->insert([
'bill_id' => 3003,
'product_id' => 2,
'quantity' => 2,
'price' => 20,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class ManageUserController extends Controller
{
private function getToken($length){
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[random_int(0, $max-1)];
}
return $token;
}
public function all()
{
$users = User::all();
return view('admin.manager.user.view', [
'users' => $users
]);
}
public function view($id)
{
$user = User::findOrFail($id);
$users = User::all();
return view('admin.manager.user.view', [
'user' => $user,
'users' => $users
]);
}
public function create(Request $request)
{
$user = new User;
$user->name = $request->input('name');
$user->manager_flag = $request->input('manager_flag');
$user->founder_flag = $request->input('founder_flag');
$user->username = $request->input('username');
$user->password = <PASSWORD>($request->input('<PASSWORD>'));
$user->token = $this->getToken(32);
$user->total_fund = $request->input('total_fund');
$user->save();
return redirect()->route('admin.manager.user');
}
public function edit(Request $request, $id)
{
$user = User::findOrFail($id);
$user->name = $request->input('name') ?? $user->name;
$user->manager_flag = $request->input('manager_flag') ?? false;
$user->founder_flag = $request->input('founder_flag') ?? false;
$user->username = $request->input('username') ?? $user->username;
if (!empty($request->input('password')))
$user->password = <PASSWORD>($request->input('password'));
$user->total_fund = $request->input('total_fund') ?? $user->total_fund;
$user->save();
return redirect()->route('admin.manager.user');
}
public function delete($id)
{
$user = User::findOrFail($id);
$user->delete();
return redirect()->route('admin.manager.user');
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Feedback;
class ManageFeedbackController extends Controller
{
public function all()
{
$feedbacks = Feedback::all();
return view('admin.manager.feedback.view', [
'feedbacks' => $feedbacks
]);
}
public function view($id)
{
$feedback = Feedback::findOrFail($id);
$feedbacks = Feedback::all();
return view('admin.manager.feedback.view', [
'feedback' => $feedback,
'feedbacks' => $feedbacks
]);
}
public function delete($id)
{
$feedback = Feedback::findOrFail($id);
$feedback->delete();
return redirect()->route('admin.manager.feedback');
}
}<file_sep><?php
use Illuminate\Database\Seeder;
class ProductCategorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('product_categories')->delete();
DB::table('product_categories')->insert([
'id' => 101,
'name' => 'Snack',
'description' => 'snack',
'created_at' => '2017-11-2 1:05:44',
'updated_at' => '2017-11-2 1:05:44'
]);
DB::table('product_categories')->insert([
'id' => 102,
'name' => 'Candy',
'description' => 'candy',
'created_at' => '2017-11-2 1:06:37',
'updated_at' => '2017-11-2 1:06:37'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\Cookie;
class AuthenticationController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
private function getToken($length){
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[random_int(0, $max-1)];
}
return $token;
}
public function login(Request $request) {
$username = $request->input('username');
$password = $request->input('password');
$user = User::where('username', $username)->first();
if ($user && Hash::check($password, $user->password)) {
$token = $this->getToken(32);
$user->token = $token;
$user->save();
$cookie = new Cookie('token', $token);
if ($user->manager_flag)
return redirect()->route('admin.manager.dashboard')->withCookie($cookie);
return redirect()->route('admin.statistic.popular')->withCookie($cookie);
}
return redirect()->route('login');
}
public function logout() {
$cookie = new Cookie('token', '-');
return redirect('/')->withCookie($cookie);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ProductCategory;
class ManageCategoryController extends Controller
{
public function all()
{
$categories = ProductCategory::all();
return view('admin.manager.category.view', [
'categories' => $categories
]);
}
public function view($id)
{
$category = ProductCategory::findOrFail($id);
$categories = ProductCategory::all();
return view('admin.manager.category.view', [
'category' => $category,
'categories' => $categories
]);
}
public function create(Request $request)
{
$category = new ProductCategory;
$category->name = $request->input('name');
$category->description = $request->input('description');
$category->save();
return redirect()->route('admin.manager.category');
}
public function edit(Request $request, $id)
{
$category = ProductCategory::findOrFail($id);
$category->name = $request->input('name') ?? $category->name;
$category->description = $request->input('description') ?? $category->description;
$category->save();
return redirect()->route('admin.manager.category');
}
public function delete($id)
{
$category = ProductCategory::findOrFail($id);
$category->delete();
return redirect()->route('admin.manager.category');
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Daily;
use App\Models\Product;
use Carbon\Carbon;
class ManageDailyController extends Controller
{
public function all()
{
$dailies = Daily::all();
return view('admin.manager.daily.view', [
'dailies' => $dailies,
]);
}
public function view($id)
{
$daily = Daily::findOrFail($id);
$products = Product::orderBy('name')->get();
$dailies = Daily::all();
$today = Carbon::now()->toDateString();
return view('admin.manager.daily.view', [
'daily' => $daily,
'dailies' => $dailies,
'products' => $products,
'today' => $today
]);
}
public function create(Request $request)
{
try{
$daily = new Daily;
$daily->today = Carbon::now()->toDateString();
$daily->save();
} catch(\Exception $e){
$daily = Daily::orderBy('id', 'desc')->firstOrFail();
return redirect()->route('admin.manager.daily.view', ['daily_id' => $daily->id]);
}
return redirect()->route('admin.manager.daily.view', ['daily_id' => $daily->id]);
}
public function edit(Request $request, $id)
{
$daily = Daily::findOrFail($id);
$items = $request->input('item');
$syncs = [];
foreach($items as $item) {
$syncs[] = $item['product_id'];
}
$daily->products()->sync($syncs);
$daily->save();
return redirect()->route('admin.manager.daily.view', ['daily_id' => $daily->id]);
}
public function delete($id)
{
$daily = Daily::findOrFail($id);
$daily->items()->delete();
$daily->delete();
return redirect()->route('admin.manager.daily');
}
public function createItem(Request $request, $daily_id)
{
$daily = Daily::findOrFail($daily_id);
$daily->products()->attach($request->input('product_id'));
$daily->save();
return redirect()->route('admin.manager.daily.view', ['daily_id' => $daily_id]);
}
public function deleteItem($daily_id, $product_id)
{
$daily = Daily::findOrFail($daily_id);
$daily->products()->detach($product_id);
$daily->save();
return redirect()->route('admin.manager.daily.view', ['daily_id' => $daily_id]);
}
}<file_sep><?php
use Illuminate\Database\Seeder;
class FeedbackSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('feedbacks')->delete();
DB::table('feedbacks')->insert([
'id' => 7001,
'name' => 'Pakin',
'comment' => 'pom tid money wai 10 bath so soory TT',
'created_at' => '2017-11-6 8:00:11',
'updated_at' => '2017-11-6 8:00:11'
]);
DB::table('feedbacks')->insert([
'id' => 7002,
'name' => 34,
'comment' => 'I want to present new goods for sale, It is condom 15mm',
'created_at' => '2017-11-6 8:00:11',
'updated_at' => '2017-11-6 8:00:11'
]);
DB::table('feedbacks')->insert([
'id' => 7003,
'name' => 104,
'comment' => 'This is a good shop in 30 years building LOVE IT',
'created_at' => '2017-11-6 8:00:11',
'updated_at' => '2017-11-6 8:00:11'
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class ProductSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('products')->delete();
DB::table('products')->insert([
'id' => 1,
'product_category_id' => 101,
'retail_price' => 15.0,
'name' => '<NAME>',
'description' => '7-select snack',
'ian' => '7612100053805',
'created_at' => '2017-10-25 11:59:59',
'updated_at' => '2017-10-25 11:59:59',
'image' => 'https://pbs.twimg.com/media/DIUQ8ibUEAAyc5k.jpg'
]);
DB::table('products')->insert([
'id' => 2,
'product_category_id' => 102,
'retail_price' => 10.0,
'name' => 'LUSH',
'description' => 'Chocolate Chewy Candy',
'ian' => '2212100053805',
'created_at' => '2017-10-24 10:00:23',
'updated_at' => '2017-10-24 10:00:23',
'image' => 'https://secure.ap-tescoassets.com/assets/TH/035/8850309140035/ShotType1_328x328.jpg'
]);
DB::table('products')->insert([
'id' => 3,
'product_category_id' => 101,
'retail_price' => 9.0,
'name' => '<NAME>',
'description' => 'fram house chocolate bun',
'ian' => '5661100874326',
'created_at' => '2017-10-27 8:00:11',
'updated_at' => '2017-10-27 8:00:11',
'image' => 'http://www.farmhouse.co.th/uploads/products/2015/4/1429513646.png'
]);
DB::table('products')->insert([
'id' => 4,
'product_category_id' => 102,
'retail_price' => 17.0,
'name' => 'Mentos Incredible Chew',
'description' => 'mentos incredible chew grape flavour',
'ian' => '8345683312456',
'created_at' => '2017-10-28 9:30:45',
'updated_at' => '2017-10-28 9:30:45',
'image' => 'https://www.waangoo.com/content/images/thumbs/0010320_mentos-incredible-chew-grape_600.jpeg'
]);
DB::table('products')->insert([
'id' => 5,
'product_category_id' => 101,
'retail_price' => 75.0,
'name' => 'durex',
'description' => 'condom',
'ian' => '0145123435678',
'created_at' => '2017-11-1 00:54:39',
'updated_at' => '2017-11-1 00:54:39',
'image' => 'https://grandcondom.com/image/cache/data/durex-comfort/durex-comfort-zoom-750x750.jpg'
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Schema::disableForeignKeyConstraints();
$this->call('ProductSeeder');
$this->call('ProductCategorySeeder');
$this->call('StockSeeder');
$this->call('StockItemSeeder');
$this->call('BillSeeder');
$this->call('UserSeeder');
$this->call('BillItemSeeder');
$this->call('FeedbackSeeder');
$this->call('DailyProductSeeder');
$this->call('DailySeeder');
Schema::enableForeignKeyConstraints();
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class DailyProductSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('daily_products')->delete();
DB::table('daily_products')->insert([
'daily_id' => 1002568,
'product_id' => 2,
]);
DB::table('daily_products')->insert([
'daily_id' => 1002568,
'product_id' => 3,
]);
DB::table('daily_products')->insert([
'daily_id' => 1002568,
'product_id' => 5,
]);
}
}<file_sep><?php
use Illuminate\Database\Seeder;
class StockSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('stocks')->delete();
DB::table('stocks')->insert([
'id' => 1111,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11',
'line_total' => 275,
'user_id' => 631
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class StockItemSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('stock_items')->delete();
DB::table('stock_items')->insert([
'product_id' => 1,
'stock_id' => 1111,
'quantity' => 40,
'price' => 12,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('stock_items')->insert([
'product_id' => 2,
'stock_id' => 1111,
'quantity' => 55,
'price' => 9,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('stock_items')->insert([
'product_id' => 3,
'stock_id' => 1111,
'quantity' => 150,
'price' => 7,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('stock_items')->insert([
'product_id' => 4,
'stock_id' => 1111,
'quantity' => 15,
'price' => 17,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('stock_items')->insert([
'product_id' => 5,
'stock_id' => 1111,
'quantity' => 10,
'price' => 40,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
}
}<file_sep><?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('users')->delete();
DB::table('users')->insert([
'id' => 631,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11',
'username' => 'aik',
'password' => Hash::make('aik'),
'name' => 'aik',
'manager_flag' => 1,
'founder_flag' => 1,
'total_fund' => 999999999,
'token' => '<PASSWORD>'
]);
DB::table('users')->insert([
'id' => 648,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11',
'username' => 'aom',
'password' => <PASSWORD>::make('aom'),
'name' => 'aom',
'manager_flag' => 1,
'founder_flag' => 0,
'total_fund' => 20,
'token' => '22222222222222222222222222222222'
]);
DB::table('users')->insert([
'id' => 642,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11',
'username' => 'opal',
'password' => <PASSWORD>::<PASSWORD>('<PASSWORD>'),
'name' => 'opal',
'manager_flag' => 1,
'founder_flag' => 0,
'total_fund' => 15,
'token' => '<PASSWORD>'
]);
DB::table('users')->insert([
'id' => 681,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11',
'username' => 'lek',
'password' => <PASSWORD>('lek'),
'name' => 'lek',
'manager_flag' => 0,
'founder_flag' => 1,
'total_fund' => 200,
'token' => '<PASSWORD>'
]);
DB::table('users')->insert([
'id' => 646,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11',
'username' => 'boom',
'password' => <PASSWORD>('<PASSWORD>'),
'name' => 'boom',
'manager_flag' => 0,
'founder_flag' => 1,
'total_fund' => 100,
'token' => '5555555555555555555555<PASSWORD>55'
]);
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class DailySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('dailies')->delete();
DB::table('dailies')->insert([
'id' => 1002568,
'created_date' => '2017-12-13'
]);
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\ProductCategory;
class ManageProductController extends Controller
{
public function all()
{
$categories = ProductCategory::all();
$products = Product::all();
return view('admin.manager.product.view', [
'categories' => $categories,
'products' => $products
]);
}
public function view($id)
{
$product = Product::findOrFail($id);
$categories = ProductCategory::all();
$products = Product::all();
return view('admin.manager.product.view', [
'product' => $product,
'categories' => $categories,
'products' => $products
]);
}
public function create(Request $request)
{
$product = new Product;
$product->ian = $request->input('ian');
$product->name = $request->input('name');
$product->productCategory()->associate($request->input('category'));
$product->retail_price = $request->input('retail_price');
$product->image = $request->input('image', '/image/no_image.svg');
$product->save();
return redirect()->route('admin.manager.product');
}
public function edit(Request $request, $id)
{
$product = Product::findOrFail($id);
$product->ian = $request->input('ian') ?? $product->ian;
$product->name = $request->input('name') ?? $product->name;
$product->productCategory()->associate($request->input('category'));
$product->retail_price = $request->input('retail_price') ?? $product->retail_price;
$product->image = $request->input('image') ?? $product->image;
$product->save();
return redirect()->route('admin.manager.product');
}
public function delete($id)
{
$product = Product::findOrFail($id);
$product->delete();
return redirect()->route('admin.manager.product');
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\BillItem;
use App\Models\Bill;
use Carbon\Carbon;
class StatisticProductController extends Controller
{
public function all(){
$products = Product::all();
return view('admin.statistic.product_history.product_main', ['products' => $products]);
}
public function productRedirect(Request $request){
$product_id = $request->input('product_id');
$date_start = $request->input('date_start');
$date_end = $request->input('date_end');
return redirect()->route('admin.statistic.product.view', [
'product_id' => $product_id,
'date_start' => $date_start,
'date_end' => $date_end
]);
}
public function view($product_id,$date_start,$date_end) {
$products = Product::all();
$product = Product::findOrFail($product_id);
$bills = BillItem::with('product')
->orderBy('quantity', 'desc')
->whereDate('created_at', '>=', $date_start)
->whereDate('created_at', '<=', $date_end)
->where('product_id', '=' , $product_id)
->get();
return view('admin.statistic.product_history.product_view',[
'product' => $product,
'products' => $products,
'bills' => $bills,
'date' => $product_id . " ~ " . $date_end
]) ;
}
}<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Bill;
use App\Models\Product;
use App\Models\User;
class ManageBillController extends Controller
{
public function all()
{
$bills = Bill::all();
return view('admin.manager.bill.view', [
'bills' => $bills,
]);
}
public function view($id)
{
$bill = Bill::findOrFail($id);
$products = Product::orderBy('name')->get();
$bills = Bill::all();
return view('admin.manager.bill.view', [
'bill' => $bill,
'bills' => $bills,
'products' => $products
]);
}
public function create(Request $request)
{
$bill = new Bill;
$bill->line_total = 0;
$bill->save();
return redirect()->route('admin.manager.bill.view', ['bill_id' => $bill->id]);
}
public function edit(Request $request, $id)
{
$bill = Bill::findOrFail($id);
$items = $request->input('item');
$syncs = [];
foreach($items as $item) {
$syncs[$item['product_id']] = ['price' => $item['price'], 'quantity' => $item['quantity']];
}
$bill->products()->sync($syncs);
$bill->line_total = $this->billValue($bill);
$bill->save();
return redirect()->route('admin.manager.bill.view', ['bill_id' => $bill->id]);
}
public function delete($id)
{
$bill = Bill::findOrFail($id);
$bill->items()->delete();
$bill->delete();
return redirect()->route('admin.manager.bill');
}
public function createItem(Request $request, $bill_id)
{
$bill = Bill::findOrFail($bill_id);
$bill->products()->attach($request->input('product_id'), [
'price' => $request->input('price', 10),
'quantity' => $request->input('quantity', 1)
]);
$bill->line_total = $this->billValue($bill);
$bill->save();
return redirect()->route('admin.manager.bill.view', ['bill_id' => $bill_id]);
}
public function deleteItem($bill_id, $product_id)
{
$bill = Bill::findOrFail($bill_id);
$bill->products()->detach($product_id);
$bill->line_total = $this->billValue($bill);
$bill->save();
return redirect()->route('admin.manager.bill.view', ['bill_id' => $bill_id]);
}
private function billValue($bill) {
$value = 0;
foreach($bill->items as $item) {
$value += $item->price * $item->quantity;
}
return $value;
}
}<file_sep><?php
use Illuminate\Database\Seeder;
class BillSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('bills')->delete();
DB::table('bills')->insert([
'id' => 1001,
'line_total' => 33,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('bills')->insert([
'id' => 2002,
'line_total' => 34,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
DB::table('bills')->insert([
'id' => 3003,
'line_total' => 104,
'created_at' => '2017-11-4 8:00:11',
'updated_at' => '2017-11-4 8:00:11'
]);
}
}
| 94afff3228dc322673ad1459fdc6bbd5500bec2b | [
"Markdown",
"PHP",
"Shell"
] | 34 | Shell | cpe24fundb/412-Shop | f7c7576e812aa9ef3761cc01025dedd456adf956 | 9711f693b7ed1349d382b0b2b63bf86f0491dc6d |
refs/heads/master | <repo_name>leiyuan1989/UI<file_sep>/dev/readme.txt
name title changed to - ASTRI INTELLIGENT DEVICE AND SYSTEM MODELING PLATFORM
author changed to - 2019 made with by ASTRI-TCD Group
<file_sep>/Chart.js-master/Chart.js-master/test/specs/helpers.math.tests.js
'use strict';
describe('Chart.helpers.math', function() {
var factorize = Chart.helpers.math._factorize;
it('should factorize', function() {
expect(factorize(1000)).toEqual([1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500]);
expect(factorize(60)).toEqual([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]);
expect(factorize(30)).toEqual([1, 2, 3, 5, 6, 10, 15]);
expect(factorize(24)).toEqual([1, 2, 3, 4, 6, 8, 12]);
expect(factorize(12)).toEqual([1, 2, 3, 4, 6]);
expect(factorize(4)).toEqual([1, 2]);
expect(factorize(-1)).toEqual([]);
expect(factorize(2.76)).toEqual([]);
});
});
<file_sep>/dev/dashboard3.js
type = ['primary', 'info', 'success', 'warning', 'danger'];
demo = {
initPickColor: function() {
$('.pick-class-label').click(function() {
var new_class = $(this).attr('new-class');
var old_class = $('#display-buttons').attr('data-class');
var display_div = $('#display-buttons');
if (display_div.length) {
var display_buttons = display_div.find('.btn');
display_buttons.removeClass(old_class);
display_buttons.addClass(new_class);
display_div.attr('data-class', new_class);
}
});
},
initDocChart: function() {
chartColor = "#FFFFFF";
// General configuration for the charts with Line gradientStroke
gradientChartOptionsConfiguration = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
bodySpacing: 4,
mode: "nearest",
intersect: 0,
position: "nearest",
xPadding: 10,
yPadding: 10,
caretPadding: 10
},
responsive: true,
scales: {
yAxes: [{
display: 0,
gridLines: 0,
ticks: {
display: false
},
gridLines: {
zeroLineColor: "transparent",
drawTicks: false,
display: false,
drawBorder: false
}
}],
xAxes: [{
display: 0,
gridLines: 0,
ticks: {
display: false
},
gridLines: {
zeroLineColor: "transparent",
drawTicks: false,
display: false,
drawBorder: false
}
}]
},
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 15
}
}
};
ctx = document.getElementById('lineChartExample').getContext("2d");
gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
gradientStroke.addColorStop(0, '#80b6f4');
gradientStroke.addColorStop(1, chartColor);
gradientFill = ctx.createLinearGradient(0, 170, 0, 50);
gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)");
gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)");
myChart = new Chart(ctx, {
type: 'line',
responsive: true,
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Active Users",
borderColor: "#f96332",
pointBorderColor: "#FFF",
pointBackgroundColor: "#f96332",
pointBorderWidth: 2,
pointHoverRadius: 4,
pointHoverBorderWidth: 1,
pointRadius: 4,
fill: true,
backgroundColor: gradientFill,
borderWidth: 2,
data: [542, 480, 430, 550, 530, 453, 380, 434, 568, 610, 700, 630]
}]
},
options: gradientChartOptionsConfiguration
});
},
initDashboardPageCharts: function() {
gradientChartOptionsConfigurationWithTooltipBlue = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.0)',
zeroLineColor: "transparent",
},
ticks: {
suggestedMin: 60,
suggestedMax: 125,
padding: 20,
fontColor: "#2380f7"
}
}],
xAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#2380f7"
}
}]
}
};
gradientChartOptionsConfigurationWithTooltipPurple = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.0)',
zeroLineColor: "transparent",
},
ticks: {
//suggestedMin: 60,
//suggestedMax: 125,
padding: 20,
fontColor: "#9a9a9a"
}
}],
xAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#9a9a9a"
}
}]
}
};
gradientChartOptionsConfigurationWithTooltipPurple2 = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.0)',
zeroLineColor: "transparent",
},
ticks: {
//suggestedMin: 60,
//suggestedMax: 125,
precision:2,
padding: 20,
fontColor: "#9a9a9a"
}
}],
xAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#9a9a9a"
}
}]
}
};
gradientChartOptionsConfigurationWithTooltipOrange = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.0)',
zeroLineColor: "transparent",
},
ticks: {
suggestedMin: 50,
suggestedMax: 110,
padding: 20,
fontColor: "#ff8a76"
}
}],
xAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(220,53,69,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#ff8a76"
}
}]
}
};
gradientChartOptionsConfigurationWithTooltipGreen = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.0)',
zeroLineColor: "transparent",
},
ticks: {
//suggestedMin: 50,
//suggestedMax: 125,
padding: 20,
fontColor: "#9e9e9e"
}
}],
xAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(0,242,195,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#9e9e9e"
}
}]
}
};
gradientBarChartConfiguration = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.1)',
zeroLineColor: "transparent",
},
ticks: {
suggestedMin: 60,
suggestedMax: 120,
padding: 20,
fontColor: "#9e9e9e"
}
}],
xAxes: [{
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#9e9e9e"
}
}]
}
};
//---------------------------------------------------------------------------------------------------------------
function init_dataset_y() {
var modeling_init_iter = modeling[modeling.length - 1];
var modeling_init_page = modeling_init_iter['data'][0];
var modeling_init_data = modeling_init_page['data'];
var dataset= [];
var dataset2 = [];
var label = modeling_init_data[0]['x'];
for (var i=0;i<modeling_init_data.length;i++)
{
var data1 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#d346b1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['y'] ,
showLine: false
}
var data2 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 0,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['y_pred'] ,
showLine: true
}
dataset.push(data1);
dataset.push(data2);
var data3 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#d346b1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['dy'] ,
showLine: false
}
var data4 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 0,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['dy_pred'] ,
showLine: true
}
dataset2.push(data3);
dataset2.push(data4);
}
var rt = [label,[dataset,dataset2],modeling.length - 1,0];
return rt
}
function gen_dataset_y(iternum,page) {
var new_iternum = iternum;
var modeling_init_iter = modeling[new_iternum];
var modeling_init_page = modeling_init_iter['data'][page];
var modeling_init_data = modeling_init_page['data'];
var dp_Width = modeling_init_page['w']
var dp_Length = modeling_init_page['l']
var mse_y = modeling_init_page['mse_y']
var mse_dy = modeling_init_page['mse_dy']
var dataset= [];
var dataset2= [];
var label = modeling_init_data[0]['x'];
for (var i=0;i<modeling_init_data.length;i++)
{
var data1 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#d346b1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['y'] ,
showLine: false
}
var data2 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 0,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['y_pred'] ,
showLine: true
}
dataset.push(data1);
dataset.push(data2);
var data3 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#d346b1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['dy'] ,
showLine: false
}
var data4 = {
label: modeling_init_data[i]['p'] ,
fill: true,
backgroundColor: gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#d346b1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#d346b1',
pointBorderWidth: 20,
pointHoverRadius: 0,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: modeling_init_data[i]['dy_pred'] ,
showLine: true
}
dataset2.push(data3);
dataset2.push(data4);
}
var rt = [label,[dataset,dataset2],new_iternum,page,dp_Width,dp_Length,mse_y,mse_dy];
return rt
}
var train_loss = []
var test_loss = []
var label = []
for(var i=0;i<modeling2.length;i++){
var data_t = modeling2[i]
label.push(data_t['iter_num'])
train_loss.push(data_t['train_loss'])
test_loss.push(data_t['test_loss'])
}
function init_loss(){
var data = {
labels: label,
datasets: [
{
label: "train loss",
fill: true,
backgroundColor: gradientStroke_loss,
borderColor: '#00d6b4',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#00d6b4',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#00d6b4',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: train_loss,
},
{
label: "est loss",
fill: true,
backgroundColor: gradientStroke_loss,
borderColor: '#f58220',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#f58220',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#f58220',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
data: test_loss,
}]
};
return data
}
//---------------------------------------------------------------------------------------------------------------
var ctx_dy = document.getElementById("chartLinePurple").getContext("2d");
var gradientStroke = ctx_dy.createLinearGradient(0, 230, 0, 50);
gradientStroke.addColorStop(1, 'rgba(66,134,121,0.15)');
gradientStroke.addColorStop(0.4, 'rgba(66,134,121,0.0)'); //green colors
gradientStroke.addColorStop(0, 'rgba(66,134,121,0)'); //green colors
var config = {
type: 'line',
data: {
labels: init_dataset_y()[0] ,
datasets: init_dataset_y()[1][1],
iternum:init_dataset_y()[2],
page:init_dataset_y()[3]
},
options: gradientChartOptionsConfigurationWithTooltipPurple2
};
var myChart_dy = new Chart(ctx_dy, config);
//---------------------------------------------------------------------------------------------------------------
var ctx_loss = document.getElementById("chartLineLoss").getContext("2d");
var gradientStroke_loss = ctx_loss.createLinearGradient(0, 230, 0, 50);
gradientStroke_loss.addColorStop(1, 'rgba(66,134,121,0.15)');
gradientStroke_loss.addColorStop(0.4, 'rgba(66,134,121,0.0)'); //green colors
gradientStroke_loss.addColorStop(0, 'rgba(66,134,121,0)'); //green colors
var myChart = new Chart(ctx_loss, {
type: 'line',
data: init_loss(),
options: gradientChartOptionsConfigurationWithTooltipGreen
});
//---------------------------------------------------------------------------------------------------------------
var chart_labels = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var chart_data = [100, 70, 90, 70, 85, 60, 75, 60, 90, 80, 110, 100];
var chart_data2 = [10, 90, 9, 7, 85, 6, 75, 6, 9, 80, 110, 100];
var ctx_y = document.getElementById("chartY").getContext('2d');
var gradientStroke = ctx_y.createLinearGradient(0, 230, 0, 50);
gradientStroke.addColorStop(1, 'rgba(72,72,176,0.1)');
gradientStroke.addColorStop(0.4, 'rgba(72,72,176,0.0)');
gradientStroke.addColorStop(0, 'rgba(119,52,169,0)'); //purple colors
var config = {
type: 'line',
data: {
labels: init_dataset_y()[0] ,
datasets: init_dataset_y()[1][0],
iternum:init_dataset_y()[2],
page:init_dataset_y()[3]
},
options: gradientChartOptionsConfigurationWithTooltipPurple
};
var myChart_y = new Chart(ctx_y, config);
$("#0").click(function() {
var data = myChart_y.config.data;
var new_dataset = init_dataset_y();
data.datasets = new_dataset[1][0];
data.labels = new_dataset[0];
data.iternum = new_dataset[2] ;
data.page = new_dataset[3] ;
var data2 = myChart_dy.config.data;
data2.datasets = new_dataset[1][1] ;
myChart_y.update();
myChart_dy.update();
});
function click1(){
var data = myChart_y.config.data;
var new_iternum = data.iternum;
if(new_iternum == (modeling.length - 1))
{
new_iternum = 0;
}
else{
new_iternum++;
}
var new_dataset = gen_dataset_y(new_iternum,data.page);
data.datasets = new_dataset[1][0] ;
data.labels = new_dataset[0] ;
data.iternum = new_dataset[2] ;
data.page = new_dataset[3] ;
var data2 = myChart_dy.config.data;
data2.datasets = new_dataset[1][1] ;
myChart_y.update();
myChart_dy.update();
var iter_num = document.getElementById("iter_num");
iter_num.innerHTML = "Training Iterations: " + label[new_dataset[2]] ;
var traintest_loss = document.getElementById("train_loss");
traintest_loss.innerHTML = "Train Error: " + train_loss[new_dataset[2]] ;
var traintest_loss = document.getElementById("test_loss");
traintest_loss.innerHTML = "Test Error: " + test_loss[new_dataset[2]];
}
$("#1").click(function() {
var timesRun = 0
var interval = setInterval(function ()
{
timesRun += 1
click1()
if(timesRun === 19){
clearInterval(interval);
}
}, 500);
});
$("#2").click(function() {
var data = myChart_y.config.data;
var new_page = data.page;
if(new_page == (modeling[0]['data'].length - 1))
{
new_page = 0;
}
else{
new_page++;
}
var new_dataset = gen_dataset_y(data.iternum,new_page);
data.datasets = new_dataset[1][0] ;
data.labels = new_dataset[0] ;
data.iternum = new_dataset[2] ;
data.page = new_dataset[3] ;
var data2 = myChart_dy.config.data;
data2.datasets = new_dataset[1][1];
var table = document.getElementById("dp_width");
table.innerHTML = new_dataset[4];
var table = document.getElementById("dp_length");
table.innerHTML = new_dataset[5];
myChart_y.update();
myChart_dy.update();
});
//---------------------------------------------------------------------------------------------------------------
var ctx = document.getElementById("CountryChart").getContext("2d");
var gradientStroke = ctx.createLinearGradient(0, 230, 0, 50);
gradientStroke.addColorStop(1, 'rgba(29,140,248,0.2)');
gradientStroke.addColorStop(0.4, 'rgba(29,140,248,0.0)');
gradientStroke.addColorStop(0, 'rgba(29,140,248,0)'); //blue colors
var myChart = new Chart(ctx, {
type: 'bar',
responsive: true,
legend: {
display: false
},
data: {
labels: ['USA', 'GER', 'AUS', 'UK', 'RO', 'BR'],
datasets: [{
label: "Countries",
fill: true,
backgroundColor: gradientStroke,
hoverBackgroundColor: gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
data: [53, 20, 10, 80, 100, 45],
}]
},
options: gradientBarChartConfiguration
});
},
initGoogleMaps: function() {
var myLatlng = new google.maps.LatLng(40.748817, -73.985428);
var mapOptions = {
zoom: 13,
center: myLatlng,
scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page
styles: [{
"elementType": "geometry",
"stylers": [{
"color": "#1d2c4d"
}]
},
{
"elementType": "labels.text.fill",
"stylers": [{
"color": "#8ec3b9"
}]
},
{
"elementType": "labels.text.stroke",
"stylers": [{
"color": "#1a3646"
}]
},
{
"featureType": "administrative.country",
"elementType": "geometry.stroke",
"stylers": [{
"color": "#4b6878"
}]
},
{
"featureType": "administrative.land_parcel",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#64779e"
}]
},
{
"featureType": "administrative.province",
"elementType": "geometry.stroke",
"stylers": [{
"color": "#4b6878"
}]
},
{
"featureType": "landscape.man_made",
"elementType": "geometry.stroke",
"stylers": [{
"color": "#334e87"
}]
},
{
"featureType": "landscape.natural",
"elementType": "geometry",
"stylers": [{
"color": "#023e58"
}]
},
{
"featureType": "poi",
"elementType": "geometry",
"stylers": [{
"color": "#283d6a"
}]
},
{
"featureType": "poi",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#6f9ba5"
}]
},
{
"featureType": "poi",
"elementType": "labels.text.stroke",
"stylers": [{
"color": "#1d2c4d"
}]
},
{
"featureType": "poi.park",
"elementType": "geometry.fill",
"stylers": [{
"color": "#023e58"
}]
},
{
"featureType": "poi.park",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#3C7680"
}]
},
{
"featureType": "road",
"elementType": "geometry",
"stylers": [{
"color": "#304a7d"
}]
},
{
"featureType": "road",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#98a5be"
}]
},
{
"featureType": "road",
"elementType": "labels.text.stroke",
"stylers": [{
"color": "#1d2c4d"
}]
},
{
"featureType": "road.highway",
"elementType": "geometry",
"stylers": [{
"color": "#2c6675"
}]
},
{
"featureType": "road.highway",
"elementType": "geometry.fill",
"stylers": [{
"color": "#9d2a80"
}]
},
{
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [{
"color": "#9d2a80"
}]
},
{
"featureType": "road.highway",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#b0d5ce"
}]
},
{
"featureType": "road.highway",
"elementType": "labels.text.stroke",
"stylers": [{
"color": "#023e58"
}]
},
{
"featureType": "transit",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#98a5be"
}]
},
{
"featureType": "transit",
"elementType": "labels.text.stroke",
"stylers": [{
"color": "#1d2c4d"
}]
},
{
"featureType": "transit.line",
"elementType": "geometry.fill",
"stylers": [{
"color": "#283d6a"
}]
},
{
"featureType": "transit.station",
"elementType": "geometry",
"stylers": [{
"color": "#3a4762"
}]
},
{
"featureType": "water",
"elementType": "geometry",
"stylers": [{
"color": "#0e1626"
}]
},
{
"featureType": "water",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#4e6d70"
}]
}
]
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title: "Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
},
showNotification: function(from, align) {
color = Math.floor((Math.random() * 4) + 1);
$.notify({
icon: "tim-icons icon-bell-55",
message: "Welcome to <b>Black Dashboard</b> - a beautiful freebie for every web developer."
}, {
type: type[color],
timer: 8000,
placement: {
from: from,
align: align
}
});
}
}; | e6fac6086a0d83eea99600aefd3cd96fc059d437 | [
"JavaScript",
"Text"
] | 3 | Text | leiyuan1989/UI | 37a4e3178686c20183aa62cff25232ce7800be60 | 95306e3490a8a9871d41979b5ecf747198fc6b47 |
refs/heads/master | <file_sep># NodeESModules
Experimental
SUCRASE and NODE.js or not ?
## Install
yarn
Then you can run:
node src/server.js
## URL
localhost:3333
<file_sep>import express from 'express'
const routes = express.Router();
routes.get('/users', (req, res) => {
return res.send('users')
})
export default routes;
// Não consigo desestruturar o Router do express pois ele só export o express.(lib do express e não do node)
<file_sep>import express from 'express';
import { userRoutes, companyRoutes} from './modules/index.js'
const app = express();
app.get('/', (req, res) => {
return res.send('Booooom');
})
app.use(userRoutes);
app.use(companyRoutes);
export default app;<file_sep>export { default as userRoutes } from './user.routes.js'
export { default as companyRoutes } from './company.routes.js'
// Vamos ainda utilizar o Sucrase
// Ainda tenho que prover a extensão do arquivo no path | f1b37dbf650c9ad4a7e8703813fbf210386221ac | [
"Markdown",
"JavaScript"
] | 4 | Markdown | Alexandra-Lischt/NodeESModules | ecc1daf2ecf06a6be5e6fe4cc35185aa4139a938 | 54eb944a753e00f93243051565c32be63b0c6453 |
refs/heads/master | <file_sep>//
// MyPinAnnotation.swift
// ofoBike
//
// Created by 翟帅 on 2017/7/16.
// Copyright © 2017年 翟帅. All rights reserved.
//
import Foundation
//大头针
class MyPinAnnotation: MAPointAnnotation {
}
<file_sep>//
// ViewController.swift
// ofoBike
//
// Created by 翟帅 on 2017/7/10.
// Copyright © 2017年 翟帅. All rights reserved.
//
import UIKit
import SWRevealViewController
import FTIndicator
class ViewController: UIViewController, MAMapViewDelegate, AMapSearchDelegate, AMapNaviWalkManagerDelegate {
var mapView : MAMapView!
var search : AMapSearchAPI!
var pin : MyPinAnnotation!
var pinView :MAAnnotationView!
var nearBySearch = true
var start,end : CLLocationCoordinate2D!
var walkManager : AMapNaviWalkManager!
var faceView : SureMinionsView!
@IBOutlet weak var inputBtn: UIButton!
@IBOutlet weak var panelView: UIView!
@IBAction func buttonView(_ sender: Any) {
nearBySearch = true //按钮响应事件,回到我的定位附近
searchBikeNearby()
}
override func viewDidLoad() {
super.viewDidLoad()
let screenh = UIScreen.main.applicationFrame.size.height
let screenw = UIScreen.main.applicationFrame.size.width
mapView = MAMapView(frame: view.bounds)
view.addSubview(mapView)
view.bringSubview(toFront: panelView)
//带重力感应的小黄人的脸
faceView = SureMinionsView(frame: CGRect(x: 0, y: 0, width: 190, height: 190))
faceView.center = CGPoint(x: screenw / 2, y: screenh - 55)
view.addSubview(faceView)
view.bringSubview(toFront: inputBtn)
mapView.delegate = self
AMapServices.shared().enableHTTPS = true //允许高德地图 htpps 协议
mapView.zoomLevel = 17
//获取定位蓝点 并设置为追踪
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
//搜索附近位置API 兴趣点
search = AMapSearchAPI()
search.delegate = self
walkManager = AMapNaviWalkManager()
walkManager.delegate = self
self.navigationItem.titleView = UIImageView(image: #imageLiteral(resourceName: "yellowBikeLogo"))
self.navigationItem.leftBarButtonItem?.image = #imageLiteral(resourceName: "user_center_icon").withRenderingMode(.alwaysOriginal)
self.navigationItem.rightBarButtonItem?.image = #imageLiteral(resourceName: "gift_icon").withRenderingMode(.alwaysOriginal)
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
// SW 视图容器的切换 侧滑栏
if let revealVC = revealViewController(){
revealVC.rearViewRevealWidth = 280
navigationItem.leftBarButtonItem?.target = revealVC
navigationItem.leftBarButtonItem?.action = #selector(SWRevealViewController.revealToggle(_:))
view.addGestureRecognizer(revealVC.panGestureRecognizer())
}
// 用于加载启动页数据,可放到网络请求的回调中,图片异步缓存
LaunchADView.setValue(imgURL: "http://img.shenghuozhe.net/shz/2016/05/07/750w_1224h_043751462609867.jpg", webURL: "http://www.ofo.so", showTime: 3)
// 用于显示启动页。若启动数据更新,则将在下次启动后展示新的启动页
LaunchADView.show { (url) in
let vc = WebView()
vc.url = url
self.navigationController?.pushViewController(vc, animated: true)
}
}
//小黄人点击事件
func tapped(){
print("tapped")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//地图初始化完成之后
func mapInitComplete(_ mapView: MAMapView!) {
pin = MyPinAnnotation()
pin.coordinate = mapView.centerCoordinate //定位屏幕中心
pin.lockedScreenPoint = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2)
pin.isLockedToScreen = true //锁定
mapView.addAnnotations([pin])
mapView.showAnnotations([pin], animated: true)
searchBikeNearby() //启动就搜索附近
}
// MARK: 大头针的动画
func pinAnimaation() {
//追落效果。y轴加位移
let endFrame = pinView.frame
pinView.frame = endFrame.offsetBy(dx: 0, dy: -15)
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0, options: [], animations: {
self.pinView.frame = endFrame
}, completion: nil) //添加物理弹性 1秒发生0.2的弹性
}
// MARK: MapView Delegate
//在地图上渲染规划的路线
func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
if overlay is MAPolyline {
//取消将大头针锁定至屏幕中央的锁定
pin.isLockedToScreen = false
//将地图缩放至显示全部的路线
mapView.visibleMapRect = overlay.boundingMapRect
//绘制路线时将大头针进行锁定,不在移动位置
let renderer = MAPolylineRenderer(overlay: overlay)
renderer?.lineWidth = 3.0
renderer?.strokeColor = UIColor.green
return renderer
}
return nil
}
// 获取点击坐标点的路线规划
func mapView(_ mapView: MAMapView!, didSelect view: MAAnnotationView!) {
start = pin.coordinate
end = view.annotation.coordinate
let startPoint = AMapNaviPoint.location(withLatitude: CGFloat(start.latitude), longitude: CGFloat(end.longitude))!
let endPoint = AMapNaviPoint.location(withLatitude: CGFloat(end.latitude), longitude: CGFloat(end.longitude))!
walkManager.calculateWalkRoute(withStart: [startPoint], end: [endPoint])
}
// 制作动画,附近地标的显示动画 从小变大持续0.5秒
func mapView(_ mapView: MAMapView!, didAddAnnotationViews views: [Any]!) {
let aViews = views as! [MAAnnotationView]
for aViews in aViews {
guard aViews.annotation is MAPointAnnotation else {
continue
}
aViews.transform = CGAffineTransform(scaleX: 0, y: 0)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: [], animations: {
aViews.transform = .identity
}, completion: nil)
}
}
/// 用户发生地图移动时的交互
///
/// - Parameters:
/// - mapView: mapView
/// - wasUserAction: 用户是否移动
func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) {
if wasUserAction {
pin.isLockedToScreen = true //保持大头针的位置,不会因显示全部地标而移动位置
pinAnimaation() //动画
searchCustomLocation(mapView.centerCoordinate)
}
}
/// 自定义大头针视图
///
/// - Parameters:
/// - mapView: mapView
/// - annotation: 标注
/// - Returns: 大头针视图
func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
//将用户自己的地标排除在外
if annotation is MAUserLocation {
return nil
}
// 自定义大头针的图标
if annotation is MyPinAnnotation {
let reuseid = "anchor"
var pinImage = mapView.dequeueReusableAnnotationView(withIdentifier: reuseid)
if pinImage == nil {
pinImage = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseid)
}
pinImage?.image = #imageLiteral(resourceName: "homePage_wholeAnchor")
pinImage?.canShowCallout = false
pinView = pinImage
return pinImage
}
let reuseid = "myid"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseid) as? MAPinAnnotationView
if annotationView == nil{
annotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: reuseid)
}
if annotation.title == "正常使用"{
annotationView?.image = #imageLiteral(resourceName: "HomePage_nearbyBike")
}
else{
annotationView?.image = #imageLiteral(resourceName: "HomePage_ParkRedPack")
}
annotationView?.canShowCallout = true
annotationView?.animatesDrop = true
return annotationView
}
// MARK: Map Search Delegate
//搜索周边的小黄车,用附近的餐厅位置代替
func searchBikeNearby() {
searchCustomLocation(mapView.userLocation.coordinate)
}
func searchCustomLocation(_ center:CLLocationCoordinate2D) {
let request = AMapPOIAroundSearchRequest()
request.location = AMapGeoPoint.location(withLatitude: CGFloat(center.latitude), longitude: CGFloat(center.longitude))
request.keywords = "餐馆"
request.radius = 1000
request.requireExtension = true
search.aMapPOIAroundSearch(request)
}
//回调 搜索完周边后的处理
func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
guard response.count > 0 else {
print("周边没有小黄车")
return
}
//创建一个数组,将附近地标的信息装进数组
var annotations : [MAPointAnnotation] = []
annotations = response.pois.map{
let annotation = MAPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees($0.location.latitude), longitude: CLLocationDegrees($0.location.longitude))
if $0.distance < 200{
annotation.title = "红包区域内开锁任意小黄车"
annotation.subtitle = "骑行10分钟可获得红包奖励"
}else{
annotation.title = "正常使用"
}
return annotation
}
//将地标数组信息添加到地图上
mapView.addAnnotations(annotations)
if nearBySearch { //判断,如果是用户刚进入 APP,要进行缩放,如果是用户自己移动,则不进行缩放
//自动缩放地图,将全部地标展示在地图上
mapView.showAnnotations(annotations, animated: true)
nearBySearch = !nearBySearch
}
for poi in response.pois {
print(poi.name)//输出附近地标
}
}
// MARK: AMapNaviWalkManager Delegate 导航的代理
// 路线的规划
func walkManager(onCalculateRouteSuccess walkManager: AMapNaviWalkManager) {
print("步行路线规划成功")
//路线规划成功之后,对原来的线和多余的线去掉
mapView.removeOverlays(mapView.overlays)
//配置路线
var coordinates = walkManager.naviRoute!.routeCoordinates!.map {
return CLLocationCoordinate2D(latitude: CLLocationDegrees($0.latitude), longitude: CLLocationDegrees($0.longitude))
}
let polyline = MAPolyline(coordinates: &coordinates, count:UInt(coordinates.count))
mapView.add(polyline)
//显示到目标地点的距离与时间
let walkMinute = walkManager.naviRoute!.routeTime / 60
var timeDesc = "一分钟以内"
if walkMinute > 0 {
timeDesc = walkMinute.description + "分钟"
}
let hintTitle = "步行" + timeDesc
let hinSubtile = "距离" + walkManager.naviRoute!.routeLength.description + "米"
//系统的弹窗 提示步行的距离和时间
// let ac = UIAlertController(title: hintTitle, message: hinSubtile, preferredStyle: .alert)
// let action = UIAlertAction(title: "ok", style: .default, handler: nil)
// ac.addAction(action)
// self.present(ac, animated: true, completion: nil)
// FTIndicator弹框的提示
FTIndicator.setIndicatorStyle(.dark)
FTIndicator.showNotification(with: #imageLiteral(resourceName: "clock"), title: hintTitle, message: hinSubtile)
}
func walkManager(_ walkManager: AMapNaviWalkManager, onCalculateRouteFailure error: Error) {
print("路线规划失败:",error)
}
}
<file_sep>//
// ShowPassCodeViewController.swift
// ofoBike
//
// Created by 翟帅 on 2017/7/19.
// Copyright © 2017年 翟帅. All rights reserved.
//
import UIKit
import SwiftyTimer
import SwiftySound
class ShowPassCodeViewController: UIViewController {
@IBOutlet weak var label1st: MyPreviewTextField!
@IBOutlet weak var label2nd: MyPreviewTextField!
@IBOutlet weak var label3rd: MyPreviewTextField!
@IBOutlet weak var label4th: MyPreviewTextField!
var code = ""
var passArr : [String] = []
// { //加括号就是属性监视器,监视属性的变化
// willSet{
// //即将发生变更之前,要做好的事情
// }
// didSet {//属性监视器,当发现有值发生变化,就刷新改变
// self.label1st.text = passArr[0]
// self.label2nd.text = passArr[1]
// self.label3rd.text = passArr[2]
// self.label4th.text = passArr[3]
// }
// } //加{}号是观察
let defaults = UserDefaults.standard
@IBOutlet weak var torchBtn: UIButton!
var isTorchOn = false
@IBOutlet weak var VoiceBtn: UIButton!
var isVoiceOn = true
@IBAction func voiceBtnTap(_ sender: UIButton) {
if isVoiceOn {
VoiceBtn.setImage(#imageLiteral(resourceName: "voice_close"), for: .normal)
defaults.set(true, forKey: "isVoiceOn")
} else {
VoiceBtn.setImage(#imageLiteral(resourceName: "voice_icon"), for: .normal)
defaults.set(false, forKey: "isVoiceOn")
}
isVoiceOn = !isVoiceOn
}
@IBAction func torchBtnTap(_ sender: UIButton) {
turnTorch()
if isTorchOn {
torchBtn.setImage(#imageLiteral(resourceName: "btn_torch_disable"), for: .normal)
} else {
torchBtn.setImage(#imageLiteral(resourceName: "btn_enableTorch"), for: .normal)
}
isTorchOn = !isTorchOn
}
@IBOutlet weak var countDownLabel: UILabel!
var remindSeconds = 121;
@IBAction func reportBtnTap(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
title = "解锁密码"
//设置倒计时
Timer.every(1) { (timer: Timer) in
self.remindSeconds -= 1
// print(self.remindSeconds)
self.countDownLabel.text = self.remindSeconds.description
if self.remindSeconds == 0{
timer.invalidate()
}
}
//从defaults中获取上个界面对声音的设置,判断
// if defaults.bool(forKey: "isVoiceOn"){
// VoiceBtn.setImage(#imageLiteral(resourceName: "voice_close"), for: .normal)
//
// }else{
// VoiceBtn.setImage(#imageLiteral(resourceName: "voice_icon"), for: .normal)
// Sound.play(file: "上车前_LH.m4a")
//
// }
//UIViewHeather中写成方法
voiceBtnStatus(voiceBtn: VoiceBtn, playSound: true)
self.label1st.text = passArr[0]
self.label2nd.text = passArr[1]
self.label3rd.text = passArr[2]
self.label4th.text = passArr[3]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep># ofoBike
小黄车 swift 高仿
共享单车的项目没有什么难点,基本上就是高德地图的深度使用,难点在于优化用户体验上,这个项目单独看还凑合,真的跟小黄、小蓝单车去比体验,真的是自己都嫌弃🙄
定位、路线规划、附件的地标、自定义 UI
因为目前没有开放的共享单车 SDk,所以把位置点附近的“餐厅”假设为小黄车,因为餐厅无处不在嘛,跟共享单车一样,自定义显示 UI 之后,能达到以假乱真的效果
显示附近的“小黄车”、到达附近小黄车的路线规划(逻辑没有问题,但是绘制出来的路线还是感觉怪怪的)、二维码扫描、调用闪光灯、左右侧边栏、leanclound 云服务器调取解锁密码、
播放鲜肉鹿晗的开锁声音、桥接一个大神的OC写的模仿小黄人重力旋转眼球(https://github.com/LSure/SureOFOCopy)功能。
<file_sep>//
// UIViewHeather.swift
// ofoBike
//
// Created by 翟帅 on 2017/7/19.
// Copyright © 2017年 翟帅. All rights reserved.
// 拓展 UIView 的功能 拓展之后所有的属性都能在故事版中设置
import SwiftySound
extension UIView{//边框
@IBInspectable var boarwith : CGFloat{
get{
return self.layer.borderWidth
}
set{
self.layer.borderWidth = newValue
}
}
@IBInspectable var borderColor : UIColor{//边框颜色
get{
return UIColor(cgColor: self.layer.backgroundColor!)
}
set{
self.layer.borderColor = newValue.cgColor
}
}
@IBInspectable var cornerRadius : CGFloat{//圆角
get{
return self.layer.cornerRadius
}
set{
self.layer.cornerRadius = newValue
self.layer.masksToBounds = newValue > 0
}
}
}
//让故事版可视化,即对上面设置的属性在故事版改变值时,可以跟其他系统属性一样,立即显示出来
@IBDesignable class MyPreviewTextField: UITextField{
}
@IBDesignable class MyPreviewButton: UIButton{
}
import AVFoundation
func turnTorch() {
guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else { return }//用打开摄像头权限的方式打开闪光灯
if device.hasTorch && device.isTorchAvailable {
try? device.lockForConfiguration()
if device.torchMode == .off {
device.torchMode = .on
}else{
device.torchMode = .off
}
device.unlockForConfiguration()
}
}
//将声音按钮和播放声音关联,同时作用前后界面
func voiceBtnStatus (voiceBtn : UIButton, playSound : Bool){
let defaults = UserDefaults.standard
//从defaults中获取上个界面对声音的设置,判断
if defaults.bool(forKey: "isVoiceOn"){
voiceBtn.setImage(#imageLiteral(resourceName: "voice_close"), for: .normal)
}else{
if playSound {
Sound.play(file: "上车前_LH.m4a")
}
voiceBtn.setImage(#imageLiteral(resourceName: "voice_icon"), for: .normal)
}
}
<file_sep>//
// ColorHeader.swift
// ofoBike
//
// Created by 翟帅 on 2017/7/18.
// Copyright © 2017年 翟帅. All rights reserved.
//定义一个全局的 ofo 黄
extension UIColor{
static var ofo : UIColor{
return UIColor(red: 247/255.0, green: 215/255.0, blue: 80/255.0, alpha: 1)
}
}
| 6fe457f062037c102b503d3c0ac68bb5ca8b46fc | [
"Swift",
"Markdown"
] | 6 | Swift | 498424106/ofoBike | 258888270d15fa4b823ae2385f568c0108e68ede | 2ab86308ffc103f3a1aa7e0ad99754a8f327a1ca |
refs/heads/master | <file_sep>import actor
@actor.actor
def Input():
stdin = input()
Output.push(stdin)
@actor.actor
def Output():
print(Output.pop())
if __name__ == "__main__":
actor.run(Input, Output)
<file_sep>Silly actor library for Python
===============================
Inspired by `Talk #86 on destroyallsoftware.com <https://www.destroyallsoftware.com/screencasts/catalog/actor-syntax-from-scratch>`_
Python is a flexible language too!
::
import actor
@actor.actor
def Input():
stdin = input()
Output.push(stdin)
@actor.actor
def Output():
print(Output.pop())
actor.run(Input, Output)
<file_sep>import threading
import queue
def actor(f):
res = Actor(f.__name__)
res.fun = f
return res
def run(*actors):
[actor.start() for actor in actors]
[actor.join() for actor in actors]
class Actor(threading.Thread):
work_queue = queue.Queue()
def __init__(self, name):
super().__init__(name=name)
def push(self, value):
self.work_queue.put(value)
def pop(self):
return self.work_queue.get()
def run(self):
try:
while True:
self.fun()
except Exception as e:
print(e)
| e461092808d8a395ffc1f80f5645e280034dfb22 | [
"Python",
"reStructuredText"
] | 3 | Python | yannicklm/python-actors | 439a81f221c03ac399bfc3547e81acc607152f16 | f460d83e6735b8916207e0db1a3fc2507c272d5e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.